diff --git a/.gitignore b/.gitignore index f6636d015e..9658daad89 100644 --- a/.gitignore +++ b/.gitignore @@ -7,8 +7,10 @@ *.rpm.md5 *.log /sqled -/sqled.yml* +/sqled.yml +etc /swag bin/ ui/ +static/ .vscode/ \ No newline at end of file diff --git a/Makefile b/Makefile index 6062038513..79c8f8385f 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ override GIT_VERSION = $(shell git rev-parse --abbrev-ref HEAD)${CUSTOM} $(shell git rev-parse HEAD) override GIT_COMMIT = $(shell git rev-parse HEAD) override PROJECT_NAME = sqle -override LDFLAGS = -ldflags "-X 'main.version=\"${GIT_VERSION}\"'" +override LDFLAGS = -ldflags "-X 'main.version=${GIT_VERSION}'" override DOCKER = $(shell which docker) override GOOS = linux override OS_VERSION = el7 @@ -31,6 +31,8 @@ EDITION ?= ce GO_BUILD_TAGS = dummyhead ifeq ($(EDITION),ee) GO_BUILD_TAGS :=$(GO_BUILD_TAGS),enterprise +else ifeq ($(EDITION),trial) + GO_BUILD_TAGS :=$(GO_BUILD_TAGS),enterprise,trial endif RELEASE = qa ifeq ($(RELEASE),rel) @@ -63,8 +65,8 @@ vet: swagger GOOS=$(GOOS) GOARCH=amd64 go vet $$(GOOS=${GOOS} GOARCH=${GOARCH} go list ./...) ## Unit Test -test: swagger - cd $(PROJECT_NAME) && GOOS=$(GOOS) GOARCH=amd64 go test -v ./... +test: + cd $(PROJECT_NAME) && GOOS=$(GOOS) GOARCH=amd64 go test -v ./... -count 1 clean: GOOS=$(GOOS) GOARCH=$(GOARCH) go clean @@ -77,6 +79,8 @@ install_sqled: swagger install_scannerd: GOOS=$(GOOS) GOARCH=$(GOARCH) go build $(GO_BUILD_FLAGS) ${LDFLAGS} -tags $(GO_BUILD_TAGS) -o $(GOBIN)/scannerd ./$(PROJECT_NAME)/cmd/scannerd +dlv_install: + GOOS=$(GOOS) GOARCH=$(GOARCH) go build -gcflags "all=-N -l" $(GO_BUILD_FLAGS) ${LDFLAGS} -tags $(GO_BUILD_TAGS) -o $(GOBIN)/sqled ./$(PROJECT_NAME)/cmd/sqled swagger: GOARCH=amd64 go build -o ${shell pwd}/bin/swag ${shell pwd}/build/swag/main.go rm -rf ${shell pwd}/sqle/docs @@ -141,9 +145,9 @@ docker_rpm: docker_install override SQLE_DOCKER_IMAGE ?= actiontech/$(PROJECT_NAME)-$(EDITION):$(PROJECT_VERSION) -docker_image: fill_ui_dir docker_rpm +docker_image: cp $(shell pwd)/$(RPM_NAME) $(shell pwd)/sqle.rpm - $(DOCKER) build -t $(SQLE_DOCKER_IMAGE) -f ./docker-images/sqle/Dockerfile . + $(DOCKER) build -t $(SQLE_DOCKER_IMAGE) -f ./docker-images/sqle/Dockerfile . docker_start: cd ./docker-images/sqle && SQLE_IMAGE=$(SQLE_DOCKER_IMAGE) docker-compose up -d @@ -151,6 +155,16 @@ docker_start: docker_stop: cd ./docker-images/sqle && docker-compose down +docker_rpm_with_dms: docker_install + $(DOCKER) run -v $(dir $(CURDIR))dms:/universe/dms -v $(shell pwd):/universe/sqle --user root --rm $(RPM_BUILD_IMAGE) sh -c "(mkdir -p /root/rpmbuild/SOURCES >/dev/null 2>&1);cd /root/rpmbuild/SOURCES; \ + (tar zcf ${PROJECT_NAME}.tar.gz /universe/sqle /universe/dms --transform 's/universe/${PROJECT_NAME}-$(GIT_COMMIT)/' > /tmp/build.log 2>&1) && \ + (rpmbuild --define 'group_name $(RPM_USER_GROUP_NAME)' --define 'user_name $(RPM_USER_NAME)' \ + --define 'commit $(GIT_COMMIT)' --define 'os_version $(OS_VERSION)' \ + --target $(RPMBUILD_TARGET) -bb --with qa /universe/sqle/build/sqled_with_dms.spec >> /tmp/build.log 2>&1) && \ + (cat ~/rpmbuild/RPMS/$(RPMBUILD_TARGET)/${PROJECT_NAME}-$(GIT_COMMIT)-qa.$(OS_VERSION).$(RPMBUILD_TARGET).rpm) || (cat /tmp/build.log && exit 1)" > $(RPM_NAME) && \ + md5sum $(RPM_NAME) > $(RPM_NAME).md5 + + ###################################### ui ##################################################### fill_ui_dir: # fill ui dir, it is used by rpm build. @@ -161,4 +175,4 @@ help: $(warning ---------------------------------------------------------------------------------) $(warning Supported Variables And Values:) $(warning ---------------------------------------------------------------------------------) - $(foreach v, $(.VARIABLES), $(if $(filter file,$(origin $(v))), $(info $(v)=$($(v))))) \ No newline at end of file + $(foreach v, $(.VARIABLES), $(if $(filter file,$(origin $(v))), $(info $(v)=$($(v))))) diff --git a/README.md b/README.md index 564928d637..e28e99fe62 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,14 @@ - +
+ + + +

一个支持多种不同类型数据库,覆盖事前控制、事后监督、标准发布场景,帮助您建立质量规范的SQL全生命周期质量管理平台。

+

每周发版,快速迭代中

+ 简体中文 | [English](./README_en.md) + [![Release](https://img.shields.io/github/release/actiontech/sqle.svg?style=flat-square)](https://github.com/actiontech/sqle/releases) [![GitHub license](https://img.shields.io/github/license/actiontech/sqle.svg)](https://github.com/actiontech/sqle/blob/main/LICENSE) [![GitHub stars](https://img.shields.io/github/stars/actiontech/sqle.svg)](https://github.com/actiontech/sqle/stargazers) @@ -9,52 +16,150 @@ [![GitHub closed issues](https://img.shields.io/github/issues-closed-raw/actiontech/sqle.svg)](https://github.com/actiontech/sqle/issues?q=is%3Aissue+is%3Aclosed) [![Docker Pulls](https://img.shields.io/docker/pulls/actiontech/sqle-ce.svg)](https://hub.docker.com/r/actiontech/sqle-ce) -SQLE 由上海爱可生信息技术股份有限公司(以下简称爱可生公司)出品和维护,是爱可生公司[云树®SQL质量管理软件SQLE](https://www.actionsky.com/sqle)(简称:CTREE SQLE)软件产品的开源版本。SQLE 是一个支持多场景,原生支持 MySQL 审核且数据库类型可扩展的 SQL 审核工具。 + + + +
+ + +# 🔍 SQLE是什么 +SQLE 是爱可生自主研发支持多元数据库的 SQL 质量管理平台。应用于开发、测试、上线发布、生产运行阶段的 SQL 质量治理。通过 “建立规范、事前控制、事后监督、标准发布” 的方式,为企业提供 SQL 全生命周期质量管控能力,规避业务 SQL 不规范引起的生产事故,提高业务稳定性,也可推动企业内部开发规范快速落地。 + +# 📌 功能特性 +### 更丰富的数据源支持 + + 支持主流商业和开源数据库,包括 MySQL、PostgreSQL、Oracle、SQL Server、DB2、TiDB、OceanBase 等,持续增加新的数据源类型,以满足您不同的需求。 + +### 更全面的审核规则 + + 审核规则源自我们经验丰富的 DBA 运维专家团队多年的技术积累。您可以借助我们的审核规则快速达到专家级的 SQL 诊断能力,并且我们的规则库目前已经拥有规则 700+,并在不断增加中。 + +### 更智能的 SQL 采集 + + 提供多种智能扫描方式,例如慢日志、JAVA 应用等,以满足您的事前和事后 SQL 采集需求。一旦配置完成,我们的系统会自动持续采集各业务库中的 SQL,极大地减轻了您对 SQL 监督的压力,并及时发现问题 SQL。 + +### 更高效的审批流转路径 + + 提供标准化的工作流,化解了在沟通和进度追踪上的难题,从而提升了上线效率。您可以通过与飞书、钉钉等多种消息通道的对接,及时了解更新进度,减少了沟通交流的成本。 + +### 更便捷的 SQL 数据操作 + + 集成了在线数据库客户端 CloudBeaver,无需安装,通过可视化界面进行数据库管理和查询,提升了数据操作的易用性和效率。 + +### 全生命周期的 SQL 管控 + + 提供 SQL 全流程的管控视角,帮助您统一管理SQL质量。您可以追踪问题SQL的解决进度,并提供快捷的优化功能,以提升 SQL 的效率。 + +查看更多[社区版与企业版对比](https://actiontech.github.io/sqle-docs/docs/support/compare)。 + +# 💡 使用场景 + +
+ SQL 太复杂,执行性能低,如何优化? + + 知识赋能,助您构建质量规范、提升 SQL 质量。提供审核规则及规则知识库,将专家经验赋能开发,快速提升问题 SQL 诊断能力,并支持私有云用户自主沉淀。 + +- **从审核结果看 SQL 优化方向** + + 平台提供丰富的审核规则,用以覆盖不同 SQL 审核场景,您可以根据触发的规则,有针对性地优化 SQL。 + +- **从知识库了解问题解决经验** -[官方网站](https://opensource.actionsky.com/sqle/) | [文档](https://actiontech.github.io/sqle-docs/docs/intro/) | [安装](https://actiontech.github.io/sqle-docs/docs/deploy-manual/intro) | [在线体验](https://actiontech.github.io/sqle-docs/docs/online-demo) + 每个规则包含对应的知识库,是运维专家的经验沉淀,您可以借鉴并强化自身的运维认知。 + +- **对知识库做自主沉淀** -## 产品展示 -![product_show](./SQLE_product_show.gif) + 除了平台提供的知识库信息,我们还支持私有云用户在知识库中进行自主沉淀,建立您的质量规范。 + +
-[更多产品展示](https://actiontech.github.io/sqle-docs-cn/0.overview/2_product_show.html) +
+ 应用数量多,SQL 采集难,如何摆脱重复劳动? -## 产品特色 +提供智能扫描任务,可以自动持续采集不同来源的 SQL,帮助您摆脱重复劳动,极大地降低 SQL 采集难度。同时,根据不同业务要求定期巡检和生成审核报告,快速发现问题并提供优化建议。 -|特色|说明| -|--|--| -|SQL审核规范 |1. 审核规则自定义(700+)
2. 支持审核结果分级展示,支持生成下载审核报告
3. 支持规则模版,灵活组合规则
4. 审核白名单,跳过特例 SQL
5. 支持集成 IDE 自助审核
| -| 多场景审核 | 支持事前事后审核,覆盖开发、测试、上线、生产等环节 -| 标准化上线流程 | 1. SQL 审核流程按需自定义,满足企业内部不同流程管理要求
2. 支持定时上线
3. 支持设置运维时间
4. 支持 Online DDL | -| 多数据库类型支持 | 1. 统一接口,可通过插件进行多数据库审核扩展
2. 内置 MySQL 审核插件,官方支持常用数据库类型(包括:PostgreSQL、DB2、SQL Server、Oracle、TiDB、OceanBase) | -| 统一的 SQL 客户端入口 | 提供审核管控的 SQL 客户端,杜绝执行不合规 SQL| -| 丰富的集成能力 | 1. 标准 HTTP API 接口可与客户内部流程系统对接
2. 支持 LDAP,OAuth2.0 用户对接
3. 支持邮件、微信企业号、webhook 告警对接 | +- **配置扫描任务,释放 SQL 采集负担** -## 应用场景 -|场景|介绍| -| --- | --- | -| 上线前控制 | 1. SQLE 赋能开发,在代码开发阶段检查 SQL 质量
2. SQLE 集成专家经验,形成可复用的 SQL 规范标准规则,用户在平台提交工单后,平台将基于审核规则模板对提交的 SQL 语句进行初审,用以解决事前审核规范不标准难题| -|上线后监督| 1. SQLE 提供智能扫描审核功能,实现生产环境下的 SQL 审核优化
2. SQLE 支持多种类型的扫描任务,基于任务需求执行周期性的扫描任务,并生成扫描结果报告,及时告警| + 平台支持十余种扫描任务类型,支持采集不同来源的 SQL,如:JAVA 应用程序、慢日志文件、TopSQL、MyBatis 文件等。 -## 在线体验 +- **定期持续巡检,提前发现问题 SQL** + + 平台将根据配置的采集周期,为您自动、持续采集相应 SQL。 + + 平台将根据配置的审核规则模板,定期巡检和生成审核报告,有助于您及时发现问题 SQL,并提供优化方向。 + +
-| 社区版 | 企业版 | -| --- | --- | -| [SQLE 社区版](http://demo.sqle.actionsky.com/) | [SQLE 企业版](http://demo.sqle.actionsky.com:8889/) | -| 超级管理员: admin
密码: admin | 超级管理员: admin
密码: admin | +
+ 公司规模大,流程周转长,如何有效追踪进度? + +提供标准化工作流,帮助提高工作透明度和上线效率。您可以根据实际组织架构配置自定义审批流程模板,化解沟通和进度追踪难题。同时,平台支持与多种消息通道对接,可以及时更新进度,减少沟通成本。 -### 测试 MySQL -|配置项|值| +- **生成您的自定义审批流程** + + 平台支持您根据自身实际业务,配置SQL审批、上线流程,适配不同业务的上线节奏,提升业务响应效率。 + +- **配置消息推送渠道,快捷订阅变更** + + 平台支持对接多种主流IM应用,您可以将 SQL 审核集成到日常工作流中,协同办公,提升工作效率。 + +
+ +
+ SQL 变更频,审批瓶颈大,如何分散审核压力? + +将审核环节灵活嵌入到研发流程,从研发环节入手,减轻 DBA 审核压力。平台支持多种事前审核场景,将 SQL 审核前置到代码阶段,从源头实现降本增效。 + +- **使用 IDE 插件,前置规范检查** + + 可以使用 IDE 审核插件,在代码编写过程中进行实时审核和规范检查,实现编码即审核的效果。 + +- **对接 CI/CD 流程,保证应用代码上线无忧** + + 可以配置 CI/CD 审核流程,自动抓取代码变更中的 SQL,减少人工错误和代码缺陷,提高开发团队的效率和代码质量。 + +
+ + + +# 🧩 快速开始 + +## 在线试用 + 我们同时提供了 SQLE 社区版 和 SQLE 企业版 的线上 DEMO 环境,登录后您可以轻松体验 SQLE 的丰富功能。 + +- [SQLE 社区版](http://demo.sqle.actionsky.com/) +- [SQLE 企业版](http://demo.sqle.actionsky.com:8889/) + +**登录信息** +|user|password| |---|---| -| 地址 | 20.20.20.3 | -| 端口 | 3306 | -| 用户 | root | -| 密码 | test +|admin|admin| + +**您可以连接MySQL实例,进行测试** + +|variable|value| +|---|---| +|地址| 20.20.20.3| +|端口| 3306| +|用户| root| +|密码| test| > 注意事项 > 1. 该服务仅用于在线功能体验,请勿在生产环境使用; > 2. 该测试服务数据会定期清理。 -## SQL 审核插件 + +## 本地安装 +SQLE 提供了多种安装部署的方式,用户可以结合自己的环境和现状选择。初次体验或者测试使用的话建议使用docker-compose 或 docker 快速部署。 + +部署方式: + +1. [源码安装](https://actiontech.github.io/sqle-docs/docs/deploy-manual/source) +2. [RPM 部署](https://actiontech.github.io/sqle-docs/docs/deploy-manual/rpm) +3. [Docker 部署](https://actiontech.github.io/sqle-docs/docs/deploy-manual/Docker) +4. [Docker Compose部署](https://actiontech.github.io/sqle-docs/docs/deploy-manual/DockerCompose) + +## 插件开发 目前支持其他种类数据库的审核插件: * [PostgreSQL](https://github.com/actiontech/sqle-pg-plugin) * [Oracle](https://github.com/actiontech/sqle-oracle-plugin) @@ -63,22 +168,24 @@ SQLE 由上海爱可生信息技术股份有限公司(以下简称爱可生公 更多了解:《[功能说明及开发手册](https://actiontech.github.io/sqle-docs/docs/dev-manual/plugins/intro) 》 -## 官方技术支持 -|渠道 | 链接 | -| -- | -- | -| 代码库 | [github.com/actiontech/sqle](https://github.com/actiontech/sqle) | -| UI 库 | [github.com/actiontech/sqle-ui](https://github.com/actiontech/sqle-ui) | -| 文档库 | [github.com/actiontech/sqle-docs](https://github.com/actiontech/sqle-docs) | -| 文档主页 | [actiontech.github.io/sqle-docs](https://actiontech.github.io/sqle-docs/) | -| 社区网站 | [opensource.actionsky.com](https://opensource.actionsky.com) | -| 微信技术交流群 | 添加管理员:ActionOpenSource | -| 开源社区微信公众号 | ![QR_code](./QR_code.png) | +# 🧑🏻‍💻社区支持 +我们感谢您的关注与贡献,社区将引导您了解如何使用和贡献。欢迎以下方式加入社区: +* [官方网站](https://opensource.actionsky.com/sqle/) +* [文档手册](https://actiontech.github.io/sqle-docs/) +* 微信交流群:请添加管理员微信 ActionOpenSource +* 微信公众号:爱可生开源社区 + + ![QR_code](./QR_code.png) + +* 其他媒体 [Gitee](https://gitee.com/mirrors/SQLE?_from=gitee_search) | [思否](https://segmentfault.com/blog/sqle) | [开源中国](https://www.oschina.net/p/sqle) | [墨天轮](https://www.modb.pro/wiki/2759) | [CSDN](https://blog.csdn.net/ActionTech) | [稀土掘金](https://juejin.cn/column/7241238544252829753) | [知乎](https://www.zhihu.com/people/Actionsky-86-50/columns) + +🤗 欢迎将体验中产生的 Bug、问题和需求提交到 [SQLE GitHub Issue](https://github.com/actiontech/sqle/issues)。 -## 联系我们 -如果想获得 SQLE 的商业支持, 您可以联系我们: +# 📞 商业支持 +如果您想获得 SQLE 的商业支持, 您可以联系我们: * 全国支持: 400-820-6580 * 华北地区: 86-13910506562, 汪先生 * 华南地区: 86-18503063188, 曹先生 * 华东地区: 86-18930110869, 梁先生 -* 西南地区: 86-13540040119, 洪先生 +* 西南地区: 86-13540040119, 洪先生 \ No newline at end of file diff --git a/build/sqled.spec b/build/sqled.spec index 10f394c9cd..bef3d87ee9 100644 --- a/build/sqled.spec +++ b/build/sqled.spec @@ -38,11 +38,14 @@ Acitontech Sqle rm -rf $RPM_BUILD_ROOT mkdir -p $RPM_BUILD_ROOT/usr/local/sqle/bin mkdir -p %{_builddir}/%{buildsubdir}/sqle/plugins +mkdir -p $RPM_BUILD_ROOT/usr/local/sqle/scripts cp %{_builddir}/%{buildsubdir}/sqle/bin/sqled $RPM_BUILD_ROOT/usr/local/sqle/bin/sqled cp %{_builddir}/%{buildsubdir}/sqle/bin/scannerd $RPM_BUILD_ROOT/usr/local/sqle/bin/scannerd cp -R %{_builddir}/%{buildsubdir}/sqle/plugins $RPM_BUILD_ROOT/usr/local/sqle/plugins -cp -R %{_builddir}/%{buildsubdir}/sqle/scripts $RPM_BUILD_ROOT/usr/local/sqle/scripts -cp -R %{_builddir}/%{buildsubdir}/sqle/ui $RPM_BUILD_ROOT/usr/local/sqle/ui +cp %{_builddir}/%{buildsubdir}/sqle/scripts/sqled.systemd $RPM_BUILD_ROOT/usr/local/sqle/scripts/sqled.systemd +cp %{_builddir}/%{buildsubdir}/sqle/scripts/sqled.initd $RPM_BUILD_ROOT/usr/local/sqle/scripts/sqled.initd +cp %{_builddir}/%{buildsubdir}/sqle/scripts/pt-online-schema-change.template $RPM_BUILD_ROOT/usr/local/sqle/scripts/pt-online-schema-change.template +# cp -R %{_builddir}/%{buildsubdir}/sqle/ui $RPM_BUILD_ROOT/usr/local/sqle/ui ########## @@ -102,25 +105,30 @@ mkdir -p $RPM_INSTALL_PREFIX/logs mkdir -p $RPM_INSTALL_PREFIX/etc cat > $RPM_INSTALL_PREFIX/etc/sqled.yml.template< $RPM_INSTALL_PREFIX/etc/gh-ost.ini</dev/null 2>&1 +if [ $? -eq 0 ]; then + if [ ! -d "/lib/systemd/system" ];then + mkdir -p /lib/systemd/system + chmod 0755 /lib/systemd/system + fi +fi + +#create group & user +(which nologin 1>/dev/null 2>&1) || (echo "require nologin" && exit 11) +(which bash 1>/dev/null 2>&1) || (echo "require bash" && exit 12) +(which pkill 1>/dev/null 2>&1) || (echo "require pkill" && exit 13) +(getent group %{group_name} 1>/dev/null 2>&1) || groupadd -g 5700 %{group_name} +(id %{user_name} 1>/dev/null 2>&1) || (useradd -M -g %{group_name} -s $(which nologin) -u 5700 %{user_name} && chage -M 99999 %{user_name}) + + +#check bash env +bash -c "" 2>&1 | grep -e 'warning' -e 'error' +if [ $? -eq 0 ]; then + exit 14 +fi + +########## + +%post + +#service +grep systemd /proc/1/comm 1>/dev/null 2>&1 +if [ $? -eq 0 ]; then + sed -e "s|PIDFile=|PIDFile=$RPM_INSTALL_PREFIX\/sqled.pid|g" \ + -e "s|User=|User=actiontech-universe|g" \ + -e "s|ExecStart=|ExecStart=/bin/sh -c 'exec $RPM_INSTALL_PREFIX\/bin\/sqled --config $RPM_INSTALL_PREFIX\/etc\/config.yaml --pidfile=$RPM_INSTALL_PREFIX\/sqled.pid >>$RPM_INSTALL_PREFIX\/std.log 2>\&1'|g" \ + -e "s|WorkingDirectory=|WorkingDirectory=$RPM_INSTALL_PREFIX|g" \ + $RPM_INSTALL_PREFIX/scripts/sqled.systemd > /lib/systemd/system/sqled.service + sed -e "s|PIDFile=|PIDFile=$RPM_INSTALL_PREFIX\/dms.pid|g" -e "s|User=|User=actiontech-universe|g" -e "s|ExecStart=|ExecStart=$RPM_INSTALL_PREFIX\/bin\/dms -conf $RPM_INSTALL_PREFIX\/etc\/config.yaml|g" -e "s|WorkingDirectory=|WorkingDirectory=$RPM_INSTALL_PREFIX|g" $RPM_INSTALL_PREFIX/scripts/dms.systemd > /lib/systemd/system/dms.service + systemctl daemon-reload + systemctl enable sqled.service + systemctl enable dms.service +fi + +mkdir -p $RPM_INSTALL_PREFIX/logs +# mkdir -p $RPM_INSTALL_PREFIX/etc + + +if [ $1 -eq 1 ]; then +cat >> $RPM_INSTALL_PREFIX/etc/config.yaml< $RPM_INSTALL_PREFIX/etc/gh-ost.ini</dev/null 2>&1 + if [ $? -eq 0 ]; then + systemctl stop sqled.service || true + else + service sqled stop || true + fi +fi + +function kill_and_wait { + pidfile=$1 + if [ -e $pidfile ]; then + kill $(cat $pidfile) &>/dev/null + fi + for i in {1..60}; do + if [ ! -e $pidfile ]; then + return 0 + fi + kill -0 $(cat $pidfile) &>/dev/null + if [ $? -ne 0 ]; then + return 0 + fi + sleep 1 + done + return 1 +} + +if [ "$1" = "0" ]; then + kill_and_wait $RPM_INSTALL_PREFIX/sqled.pid + if [ $? -ne 0 ]; then + (>&2 echo "wait sqled pid shutdown timeout") + exit 1 + fi + kill_and_wait $RPM_INSTALL_PREFIX/dms.pid + if [ $? -ne 0 ]; then + (>&2 echo "wait dms pid shutdown timeout") + exit 1 + fi +fi + +########## + +%postun + +if [ "$1" = "0" ]; then + grep systemd /proc/1/comm 1>/dev/null 2>&1 + if [ $? -eq 0 ]; then + systemctl disable sqled.service || true + rm -f /lib/systemd/system/sqled.service || true + systemctl disable dms.service || true + rm -f /lib/systemd/system/dms.service || true + systemctl daemon-reload + systemctl reset-failed sqled.service || true + systemctl reset-failed dms.service || true + else + chkconfig --del sqled || true + rm -f /etc/init.d/sqled || true + chkconfig --del dms || true + rm -f /etc/init.d/dms || true + fi +fi + +########## + +%files +%defattr(-,root,root) +/usr/local/%{name}/bin/sqled +/usr/local/%{name}/bin/scannerd +/usr/local/%{name}/bin/dms +/usr/local/%{name}/plugins +/usr/local/%{name}/scripts/* +/usr/local/%{name}/static/* +/usr/local/%{name}/etc/config.yaml + + +%config /usr/local/%{name}/etc/config.yaml diff --git a/docker-images/sqle/Dockerfile b/docker-images/sqle/Dockerfile index 4e51c9028b..95348cd5b0 100644 --- a/docker-images/sqle/Dockerfile +++ b/docker-images/sqle/Dockerfile @@ -30,7 +30,8 @@ ENV MYSQL_HOST "" ENV MYSQL_PORT 3306 ENV MYSQL_USER "" ENV MYSQL_PASSWORD "" -ENV MYSQL_SCHEMA "" +ENV MYSQL_DMS_SCHEMA "" +ENV MYSQL_SQLE_SCHEMA "" ENV DEBUG false ENV AUTO_MIGRATE_TABLE true diff --git a/docker-images/sqle/docker-compose.yaml b/docker-images/sqle/docker-compose.yaml index f0afc7fd4e..5648f1d470 100644 --- a/docker-images/sqle/docker-compose.yaml +++ b/docker-images/sqle/docker-compose.yaml @@ -14,12 +14,14 @@ services: - sqle_net ports: - 10000:10000 + - 10001:10001 environment: - MYSQL_HOST=20.20.20.2 - MYSQL_PORT=3306 - MYSQL_USER=root - MYSQL_PASSWORD=mysqlpass - - MYSQL_SCHEMA=sqle + - MYSQL_SQLE_SCHEMA=sqle + - MYSQL_DMS_SCHEMA=dms depends_on: - mysql-for-sqle command: bash -c "sleep 10 && /opt/start.sh" @@ -41,6 +43,8 @@ services: environment: - MYSQL_ROOT_PASSWORD=mysqlpass - MYSQL_DATABASE=sqle + volumes: + - ./init:/docker-entrypoint-initdb.d command: ['mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci'] networks: diff --git a/docker-images/sqle/init/db.sql b/docker-images/sqle/init/db.sql new file mode 100644 index 0000000000..5a0c67ec83 --- /dev/null +++ b/docker-images/sqle/init/db.sql @@ -0,0 +1 @@ +CREATE DATABASE IF NOT EXISTS `dms`; \ No newline at end of file diff --git a/docker-images/sqle/start.sh b/docker-images/sqle/start.sh index 7f3f7a472b..ad00e4821e 100644 --- a/docker-images/sqle/start.sh +++ b/docker-images/sqle/start.sh @@ -1,27 +1,74 @@ #!/bin/bash SQLE_BASE="/opt/sqle" -SQLE_CONF="${SQLE_BASE}/etc/sqled.yml" +CONF="${SQLE_BASE}/etc/config.yml" -if [ ! -f "${SQLE_CONF}" ];then - cat > ${SQLE_CONF} < ${CONF} < /dev/null; do + sleep 1 +done +# 启动sqle +./bin/sqled --config ${CONF} diff --git a/go.mod b/go.mod index 63a584b087..7844ef063b 100644 --- a/go.mod +++ b/go.mod @@ -3,9 +3,9 @@ module github.com/actiontech/sqle go 1.19 require ( - github.com/99designs/gqlgen v0.17.20 github.com/DATA-DOG/go-sqlmock v1.5.0 github.com/Masterminds/semver/v3 v3.1.1 + github.com/actiontech/dms v0.0.0-20231129083427-a97a77db08e0 github.com/actiontech/java-sql-extractor v0.0.0-20231103015812-cdd5fc040f62 github.com/actiontech/mybatis-mapper-2-sql v0.5.0 github.com/agiledragon/gomonkey v2.0.2+incompatible @@ -19,6 +19,7 @@ require ( github.com/alibabacloud-go/tea-utils/v2 v2.0.1 github.com/baidubce/bce-sdk-go v0.9.151 github.com/bwmarrin/snowflake v0.3.0 + github.com/clbanning/mxj/v2 v2.5.6 // indirect github.com/cznic/mathutil v0.0.0-20181122101859-297441e03548 github.com/cznic/parser v0.0.0-20181122101858-d773202d5b1f github.com/cznic/sortutil v0.0.0-20181122101858-f5f958428db8 @@ -26,15 +27,19 @@ require ( github.com/cznic/y v0.0.0-20181122101901-b05e8c2e8d7b github.com/denisenkom/go-mssqldb v0.9.0 github.com/facebookgo/grace v0.0.0-20180706040059-75cf19382434 - github.com/fatih/color v1.9.0 + github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 // indirect + github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 // indirect + github.com/fatih/color v1.13.0 github.com/github/gh-ost v1.1.3-0.20210727153850-e484824bbd68 github.com/go-git/go-git/v5 v5.9.0 github.com/go-ini/ini v1.63.2 - github.com/go-ldap/ldap/v3 v3.4.1 - github.com/go-playground/locales v0.14.0 - github.com/go-playground/universal-translator v0.18.0 - github.com/go-playground/validator/v10 v10.9.0 - github.com/go-sql-driver/mysql v1.6.0 + github.com/go-openapi/jsonreference v0.19.4 // indirect + github.com/go-openapi/spec v0.19.8 // indirect + github.com/go-openapi/swag v0.19.9 // indirect + github.com/go-playground/locales v0.14.1 + github.com/go-playground/universal-translator v0.18.1 + github.com/go-playground/validator/v10 v10.14.1 + github.com/go-sql-driver/mysql v1.7.0 github.com/golang-jwt/jwt v3.2.2+incompatible github.com/golang/protobuf v1.5.3 github.com/hashicorp/go-hclog v0.14.1 @@ -42,8 +47,10 @@ require ( github.com/jackc/pgx/v4 v4.13.0 github.com/jinzhu/gorm v1.9.15 github.com/jmoiron/sqlx v1.3.3 - github.com/labstack/echo/v4 v4.6.1 - github.com/larksuite/oapi-sdk-go/v3 v3.0.18 + github.com/labstack/echo/v4 v4.10.2 + github.com/larksuite/oapi-sdk-go/v3 v3.0.23 + github.com/mattn/go-runewidth v0.0.9 // indirect + github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect github.com/openark/golib v0.0.0-20210531070646-355f37940af8 github.com/percona/go-mysql v0.0.0-20210427141028-73d29c6da78c github.com/pingcap/parser v3.0.12+incompatible @@ -53,24 +60,22 @@ require ( github.com/sijms/go-ora/v2 v2.2.15 github.com/sirupsen/logrus v1.9.0 github.com/spf13/cobra v1.1.1 - github.com/stretchr/testify v1.7.1 + github.com/stretchr/testify v1.8.4 github.com/swaggo/echo-swagger v1.0.0 github.com/swaggo/swag v1.6.7 github.com/ungerik/go-dry v0.0.0-20210209114055-a3e162a9e62e github.com/urfave/cli/v2 v2.8.1 - github.com/vektah/gqlparser/v2 v2.5.1 golang.org/x/net v0.15.0 - google.golang.org/grpc v1.39.0 - gopkg.in/chanxuehong/wechat.v1 v1.0.0-20171118020122-aad7e298d1e7 - gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df + google.golang.org/grpc v1.50.1 gopkg.in/natefinch/lumberjack.v2 v2.0.0 gopkg.in/yaml.v2 v2.4.0 vitess.io/vitess v0.12.0 ) +require github.com/huaweicloud/huaweicloud-sdk-go-v3 v0.1.69 + require ( dario.cat/mergo v1.0.0 // indirect - github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c // indirect github.com/KyleBanks/depth v1.2.1 // indirect github.com/Microsoft/go-winio v0.6.1 // indirect github.com/ProtonMail/go-crypto v0.0.0-20230828082145-3c4c8a2d2371 // indirect @@ -78,7 +83,6 @@ require ( github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect github.com/acomagu/bufpipe v1.0.4 // indirect - github.com/agnivade/levenshtein v1.1.1 // indirect github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.4 // indirect github.com/alibabacloud-go/debug v0.0.0-20190504072949-9472017b5c68 // indirect github.com/alibabacloud-go/endpoint-util v1.1.0 // indirect @@ -86,32 +90,30 @@ require ( github.com/alibabacloud-go/tea-xml v1.1.2 // indirect github.com/aliyun/credentials-go v1.1.2 // indirect github.com/antlr4-go/antlr/v4 v4.13.0 // indirect - github.com/chanxuehong/util v0.0.0-20200304121633-ca8141845b13 // indirect - github.com/clbanning/mxj/v2 v2.5.6 // indirect + github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/cloudflare/circl v1.3.3 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/cyphar/filepath-securejoin v0.2.4 // indirect github.com/cznic/golex v0.0.0-20181122101858-9c343928389c // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c // indirect github.com/facebookgo/freeport v0.0.0-20150612182905-d4adf43b75b9 // indirect - github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 // indirect - github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 // indirect + github.com/gabriel-vasile/mimetype v1.4.2 // indirect github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32 // indirect - github.com/go-asn1-ber/asn1-ber v1.5.1 // indirect github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect github.com/go-git/go-billy/v5 v5.5.0 // indirect github.com/go-mysql-org/go-mysql v1.3.0 // indirect github.com/go-ole/go-ole v1.2.4 // indirect + github.com/go-openapi/errors v0.20.3 // indirect github.com/go-openapi/jsonpointer v0.19.3 // indirect - github.com/go-openapi/jsonreference v0.19.4 // indirect - github.com/go-openapi/spec v0.19.8 // indirect - github.com/go-openapi/swag v0.19.9 // indirect + github.com/go-openapi/strfmt v0.21.7 // indirect + github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe // indirect github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb // indirect + github.com/iancoleman/strcase v0.3.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.10.0 // indirect @@ -122,19 +124,19 @@ require ( github.com/jackc/pgtype v1.8.1 // indirect github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect github.com/jinzhu/inflection v1.0.0 // indirect - github.com/jinzhu/now v1.1.1 // indirect - github.com/json-iterator/go v1.1.11 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/kevinburke/ssh_config v1.2.0 // indirect - github.com/labstack/gommon v0.3.0 // indirect - github.com/leodido/go-urn v1.2.1 // indirect + github.com/labstack/gommon v0.4.0 // indirect + github.com/leodido/go-urn v1.2.4 // indirect github.com/mailru/easyjson v0.7.1 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.16 // indirect - github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect + github.com/mattn/go-isatty v0.0.17 // indirect github.com/mitchellh/go-testing-interface v1.14.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.1 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/oklog/run v1.0.0 // indirect + github.com/oklog/ulid v1.3.1 // indirect github.com/opentracing/opentracing-go v1.1.0 // indirect github.com/pingcap/errors v0.11.5-0.20201126102027-b0a155152ca3 // indirect github.com/pingcap/log v0.0.0-20210317133921-96f4fcab92a4 // indirect @@ -152,11 +154,12 @@ require ( github.com/skeema/knownhosts v1.2.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14 // indirect - github.com/tjfoc/gmsm v1.3.2 // indirect + github.com/tjfoc/gmsm v1.4.1 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasttemplate v1.2.1 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect + go.mongodb.org/mongo-driver v1.12.0 // indirect go.uber.org/atomic v1.7.0 // indirect go.uber.org/multierr v1.6.0 // indirect go.uber.org/zap v1.17.0 // indirect @@ -165,17 +168,18 @@ require ( golang.org/x/mod v0.12.0 // indirect golang.org/x/sys v0.12.0 // indirect golang.org/x/text v0.13.0 // indirect - golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac // indirect + golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.13.0 // indirect google.golang.org/genproto v0.0.0-20210701191553-46259e63a0a9 // indirect google.golang.org/protobuf v1.28.0 // indirect - gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect - gopkg.in/ini.v1 v1.62.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) replace ( + cloud.google.com/go/compute/metadata => cloud.google.com/go/compute/metadata v0.1.0 + github.com/labstack/echo/v4 => github.com/labstack/echo/v4 v4.6.1 github.com/pingcap/log => github.com/pingcap/log v0.0.0-20191012051959-b742a5d432e9 github.com/pingcap/parser => github.com/sjjian/parser v0.0.0-20231122073510-03e191068cf1 google.golang.org/grpc => google.golang.org/grpc v1.29.0 diff --git a/go.sum b/go.sum index f03c2d3aca..1b5e8dd4e4 100644 --- a/go.sum +++ b/go.sum @@ -19,13 +19,8 @@ cloud.google.com/go/storage v1.10.0 h1:STgFzyU5/8miMl0//zKh2aQeTyeaUH3WN9bSUiJ09 dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/99designs/gqlgen v0.17.20 h1:O7WzccIhKB1dm+7g6dhQcULINftfiLSBg2l/mwbpJMw= -github.com/99designs/gqlgen v0.17.20/go.mod h1:Mja2HI23kWT1VRH09hvWshFgOzKswpO20o4ScpJIES4= -github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c h1:/IBSNwUN8+eKzUzbJPqhK839ygXJ82sde8x3ogr6R28= -github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= -github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= @@ -53,15 +48,16 @@ github.com/VividCortex/ewma v1.1.1 h1:MnEK4VOv6n0RSY4vtRe3h11qjxL3+t0B8yOL8iMXdc github.com/VividCortex/ewma v1.1.1/go.mod h1:2Tkkvm3sRDVXaiyucHiACn4cqf7DpdyLvmxzcbUokwA= github.com/acomagu/bufpipe v1.0.4 h1:e3H4WUzM3npvo5uv95QuJM3cQspFNtFBzvJ2oNjKIDQ= github.com/acomagu/bufpipe v1.0.4/go.mod h1:mxdxdup/WdsKVreO5GpW4+M/1CE2sMG4jeGJ2sYmHc4= +github.com/actiontech/dms v0.0.0-20231129060158-ff9d70a10557 h1:eeJqVzkX5X5gMfaN67X2wCFbqoVfbDgIsoSYeJJfCzs= +github.com/actiontech/dms v0.0.0-20231129060158-ff9d70a10557/go.mod h1:jG8WjxiSBcUccweOqRPONDx95j88FwZytoa1/PI8I44= +github.com/actiontech/dms v0.0.0-20231129083427-a97a77db08e0 h1:BZlpGNWg6aJhFcWZc17VHlOLWHvuxJZIKFY5ePlY5ZQ= +github.com/actiontech/dms v0.0.0-20231129083427-a97a77db08e0/go.mod h1:jG8WjxiSBcUccweOqRPONDx95j88FwZytoa1/PI8I44= github.com/actiontech/java-sql-extractor v0.0.0-20231103015812-cdd5fc040f62 h1:JM7WnLzlvXOGE90KKd+aigi+qUDS+U5dLwQMNpTKZxE= github.com/actiontech/java-sql-extractor v0.0.0-20231103015812-cdd5fc040f62/go.mod h1:adDZHhAf2LRMx2h0JzofPXn12x2XlyQjVE116KXquwo= github.com/actiontech/mybatis-mapper-2-sql v0.5.0 h1:TGovwZpLT+DUE5W0ZeSNE//LQLpVuQx8ghx0r8rPVBY= github.com/actiontech/mybatis-mapper-2-sql v0.5.0/go.mod h1:ZMmUEDfbjm8oWxSAZkejqeOzlXa1BWNCfhNIxCMu7lw= github.com/agiledragon/gomonkey v2.0.2+incompatible h1:eXKi9/piiC3cjJD1658mEE2o3NjkJ5vDLgYjCQu0Xlw= github.com/agiledragon/gomonkey v2.0.2+incompatible/go.mod h1:2NGfXu1a80LLr2cmWXGBDaHEjb1idR6+FVlX5T3D9hw= -github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM= -github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8= -github.com/agnivade/levenshtein v1.1.1/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= @@ -102,8 +98,6 @@ github.com/alibabacloud-go/tea-xml v1.1.2 h1:oLxa7JUXm2EDFzMg+7oRsYc+kutgCVwm+bZ github.com/alibabacloud-go/tea-xml v1.1.2/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8= github.com/aliyun/credentials-go v1.1.2 h1:qU1vwGIBb3UJ8BwunHDRFtAhS6jnQLnde/yk0+Ih2GY= github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw= -github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= -github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q= @@ -111,13 +105,13 @@ github.com/antlr4-go/antlr/v4 v4.13.0 h1:lxCg3LAv+EUK6t1i0y1V6/SLeUi0eKEKdhQAlS8 github.com/antlr4-go/antlr/v4 v4.13.0/go.mod h1:pfChB/xh/Unjila75QW7+VU4TSnWnnk9UTnmpPaOR2g= github.com/appleboy/gin-jwt/v2 v2.6.3/go.mod h1:MfPYA4ogzvOcVkRwAxT7quHOtQmVKDpTwxyUrC2DNw0= github.com/appleboy/gofight/v2 v2.1.2/go.mod h1:frW+U1QZEdDgixycTj4CygQ48yLTUhplt43+Wczp3rw= -github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q= -github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/aws/aws-sdk-go v1.26.1/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.30.24/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= github.com/aws/aws-sdk-go v1.34.2 h1:9vCknCdTAmmV4ht7lPuda7aJXzllXwEQyCMZKJHjBrM= @@ -139,8 +133,6 @@ github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chanxuehong/util v0.0.0-20200304121633-ca8141845b13 h1:c1vUDbnwvu5d2ucfzXvMzBWzeu5IxPvtESOFPl3CieA= -github.com/chanxuehong/util v0.0.0-20200304121633-ca8141845b13/go.mod h1:XEYt99iTxMqkv+gW85JX/DdUINHUe43Sbe5AtqSaDAQ= github.com/cheggaaa/pb/v3 v3.0.1/go.mod h1:SqqeMF/pMOIu3xgGoxtPYhMNQP258xE4x/XRTYua+KU= github.com/cheggaaa/pb/v3 v3.0.4 h1:QZEPYOj2ix6d5oEg63fbHmpolrnNiwjUsk+h74Yt4bM= github.com/cheggaaa/pb/v3 v3.0.4/go.mod h1:7rgWxLrAUcFMkvJuv09+DYi7mMUYi8nO9iOWcvGJPfw= @@ -177,8 +169,8 @@ github.com/corona10/goimagehash v1.0.2/go.mod h1:/l9umBhvcHQXVtQO1V6Gp1yD20STawk github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= -github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg= @@ -214,8 +206,6 @@ github.com/dgryski/go-farm v0.0.0-20190104051053-3adb47b1fb0f/go.mod h1:SqUrOPUn github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48 h1:fRzb/w+pyskVMQ+UbP35JkH8yB7MYb4q/qhBarqZE6g= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v0.0.0-20180421182945-02af3965c54e/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= @@ -241,13 +231,16 @@ github.com/facebookgo/stack v0.0.0-20160209184415-751773369052/go.mod h1:UbMTZqL github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 h1:7HZCaLC5+BZpmbhCOZJ293Lz68O7PYrF2EzeiFMwCLk= github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4/go.mod h1:5tD+neXqOorC30/tWg0LCSkrqj/AR6gu8yY8/fpw1q0= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= +github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsouza/fake-gcs-server v1.15.0/go.mod h1:HNxAJ/+FY/XSsxuwz8iIYdp2GtMmPbJ8WQjjGMxd6Qk= github.com/fsouza/fake-gcs-server v1.17.0/go.mod h1:D1rTE4YCyHFNa99oyJJ5HyclvN/0uQR+pM/VdlL83bw= +github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32 h1:Mn26/9ZMNWSw9C9ERFA1PUxfmGpolnw2v0bKOREu5ew= github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= @@ -261,8 +254,6 @@ github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmC github.com/github/gh-ost v1.1.3-0.20210727153850-e484824bbd68 h1:0ExfTwWAmfgQ2IAwMJp3Xagm1hkMgy9wdwvApGCY388= github.com/github/gh-ost v1.1.3-0.20210727153850-e484824bbd68/go.mod h1:KapUFjHOhrrWRyXCV7iZXfL3FGhTfe8Z6UQupU1MxoU= github.com/gliderlabs/ssh v0.3.5 h1:OcaySEmAQJgyYcArR+gGGTHCyE7nvhEMTlYY+Dp8CpY= -github.com/go-asn1-ber/asn1-ber v1.5.1 h1:pDbRAunXzIUXfx4CB2QJFv5IuPiuoW+sWvr/Us009o8= -github.com/go-asn1-ber/asn1-ber v1.5.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= github.com/go-bindata/go-bindata/v3 v3.1.3/go.mod h1:1/zrpXsLD8YDIbhZRqXzm1Ghc7NhEvIN9+Z6R5/xH4I= github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= @@ -280,8 +271,6 @@ github.com/go-ini/ini v1.63.2/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3I github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= -github.com/go-ldap/ldap/v3 v3.4.1 h1:fU/0xli6HY02ocbMuozHAYsaHLcnkLjvho2r5a34BUU= -github.com/go-ldap/ldap/v3 v3.4.1/go.mod h1:iYS1MdmrmceOJ1QOTnRXrIs7i3kloqtmGQjRvjKpyMg= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= @@ -291,6 +280,8 @@ github.com/go-mysql-org/go-mysql v1.3.0/go.mod h1:3lFZKf7l95Qo70+3XB2WpiSf9wu2s3 github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI= github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM= +github.com/go-openapi/errors v0.20.3 h1:rz6kiC84sqNQoqrtulzaL/VERgkoCyB6WdEkc2ujzUc= +github.com/go-openapi/errors v0.20.3/go.mod h1:Z3FlZ4I8jEGxjUK+bugx3on2mIAk4txuAOhlsB1FSgk= github.com/go-openapi/jsonpointer v0.17.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M= github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= github.com/go-openapi/jsonpointer v0.19.3 h1:gihV7YNZK1iK6Tgwwsxo2rJbD1GTbdm72325Bq8FI3w= @@ -306,30 +297,32 @@ github.com/go-openapi/spec v0.19.4/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8 github.com/go-openapi/spec v0.19.7/go.mod h1:Hm2Jr4jv8G1ciIAo+frC/Ft+rR2kQDh8JHKHb3gWUSk= github.com/go-openapi/spec v0.19.8 h1:qAdZLh1r6QF/hI/gTq+TJTvsQUodZsM7KLqkAJdiJNg= github.com/go-openapi/spec v0.19.8/go.mod h1:Hm2Jr4jv8G1ciIAo+frC/Ft+rR2kQDh8JHKHb3gWUSk= +github.com/go-openapi/strfmt v0.21.7 h1:rspiXgNWgeUzhjo1YU01do6qsahtJNByjLVbPLNHb8k= +github.com/go-openapi/strfmt v0.21.7/go.mod h1:adeGTkxE44sPyLk0JV235VQAO/ZXUr8KAzYjclFs3ew= github.com/go-openapi/swag v0.17.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.8/go.mod h1:ao+8BpOPyKdpQz3AOJfbeEVpLmWAvlT1IfTe5McPyhY= github.com/go-openapi/swag v0.19.9 h1:1IxuqvBUU3S2Bi4YC7tlP9SJF1gVpCvqN0T2Qof4azE= github.com/go-openapi/swag v0.19.9/go.mod h1:ao+8BpOPyKdpQz3AOJfbeEVpLmWAvlT1IfTe5McPyhY= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU= -github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/overalls v0.0.0-20180201144345-22ec1a223b7c/go.mod h1:UqxAgEOt89sCiXlrc/ycnx00LVvUO/eS8tMUkWX4R7w= github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY= github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= -github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= -github.com/go-playground/validator/v10 v10.9.0 h1:NgTtmN58D0m8+UuxtYmGztBJB7VnPgjj221I1QHci2A= -github.com/go-playground/validator/v10 v10.9.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSGrTK4nAUsbPlLADvpJkos= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.14.1 h1:9c50NUPC30zyuKprjL3vNZ0m5oG+jU0zvx4AqHGnv4k= +github.com/go-playground/validator/v10 v10.14.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= github.com/go-sql-driver/mysql v0.0.0-20170715192408-3955978caca4/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/goccy/go-graphviz v0.0.5/go.mod h1:wXVsXxmyMQU6TN3zGRttjNn3h+iCAS7xQFC6TlNvLhk= github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw= @@ -343,6 +336,8 @@ github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXP github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= +github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= @@ -364,6 +359,12 @@ github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= @@ -379,6 +380,7 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -392,12 +394,11 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4 github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf/go.mod h1:RpwtwJQFrIEPstU94h88MWPXP2ektJZ8cZ0YntAmXiE= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 h1:l5lAOZEym3oK3SQ2HBHWsJUfbNBiTXJDeW2QDxw9AQ0= github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= @@ -409,8 +410,6 @@ github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= -github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.1.0 h1:THDBEeQ9xZ8JEaCLyLQqXMMdRqNr0QAUJTIkQAUtFjg= @@ -442,8 +441,6 @@ github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/b github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= -github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= @@ -452,9 +449,12 @@ github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/J github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb h1:b5rjCoWHc7eqmAS4/qyk21ZsHyb6Mxv/jykxvNTkU4M= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/huaweicloud/huaweicloud-sdk-go-v3 v0.1.69 h1:gPBExK6wtglcrZmQ4yhjuR/oPMvB+k1RmXDXQEHUzLM= +github.com/huaweicloud/huaweicloud-sdk-go-v3 v0.1.69/go.mod h1:AZT3IyeViMA1qIoo6lM2eDobcTXORpqIQzSqdodah7E= github.com/hypnoglow/gormzap v0.3.0/go.mod h1:5Wom8B7Jl2oK0Im9hs6KQ+Kl92w4Y7gKCrj66rhyvw0= -github.com/iancoleman/strcase v0.0.0-20191112232945-16388991a334 h1:VHgatEHNcBFEB7inlalqfNqw65aNkM1lGX2yt3NmbS8= github.com/iancoleman/strcase v0.0.0-20191112232945-16388991a334/go.mod h1:SK73tn/9oHe+/Y0h39VT4UCxmurVJkR5NA7kMEAOgSE= +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= @@ -514,8 +514,7 @@ github.com/jinzhu/gorm v1.9.15/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBef github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= -github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E= -github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -530,12 +529,11 @@ github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCV github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.11 h1:uVUAXhF2To8cbw/3xN3pxj6kk7TYKs98NIrTqPlMWAQ= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/juju/ratelimit v1.0.1 h1:+7AIFJVQ0EQgq/K9+0Krm7m530Du7tIz0METWzN0RgY= github.com/juju/ratelimit v1.0.1/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk= @@ -543,10 +541,10 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V github.com/kevinburke/go-bindata v3.18.0+incompatible/go.mod h1:/pEEZ72flUW2p0yi30bslSp9YqD9pysLxunQDdb2CPM= github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4= github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= -github.com/kevinmbeaulieu/eq-go v1.0.0/go.mod h1:G3S8ajA56gKBZm4UB9AOyoOS37JO3roToPzKNM8dtdM= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/cpuid v1.2.0 h1:NMpwD2G9JSFOE1/TJjGSo5zG7Yb2bTe7eq1jH+irmeE= github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= @@ -556,7 +554,6 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxv github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pty v1.0.0/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -565,25 +562,23 @@ github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/labstack/echo/v4 v4.0.0/go.mod h1:tZv7nai5buKSg5h/8E6zz4LsD/Dqh9/91Mvs7Z5Zyno= github.com/labstack/echo/v4 v4.6.1 h1:OMVsrnNFzYlGSdaiYGHbgWQnr+JM7NG+B9suCPie14M= github.com/labstack/echo/v4 v4.6.1/go.mod h1:RnjgMWNDB9g/HucVWhQYNQP9PvbYf6adqftqryo7s9k= -github.com/labstack/gommon v0.2.8/go.mod h1:/tj9csK2iPSBvn+3NLM9e52usepMtrd5ilFYA+wQNJ4= -github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0= github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= -github.com/larksuite/oapi-sdk-go/v3 v3.0.18 h1:I91VJQMC2dpwIDMfF7RO0kQ+bg6X4+2RMMLrg/z6m5E= -github.com/larksuite/oapi-sdk-go/v3 v3.0.18/go.mod h1:FKi8vBgtkBt/xNRQUwdWvoDmsPh7/wP75Sn5IBIBQLk= +github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= +github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= +github.com/larksuite/oapi-sdk-go/v3 v3.0.23 h1:mn4pD4JXgzYbpc9TT0grGHPcYppYEmisKMHeTwULu5Q= +github.com/larksuite/oapi-sdk-go/v3 v3.0.23/go.mod h1:FKi8vBgtkBt/xNRQUwdWvoDmsPh7/wP75Sn5IBIBQLk= github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= -github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.10.2 h1:AqzbZs4ZoCBp+GtejcpCpcxM3zlSMx29dXbUSeVtJb8= github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/logrusorgru/aurora/v3 v3.0.0/go.mod h1:vsR12bk5grlLvLXAYrBsb5Oc/N+LxAlxggSjiwMnCUc= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= @@ -594,7 +589,6 @@ github.com/mailru/easyjson v0.7.1 h1:mdxE1MF9o53iCb2Ghj1VfWvh7ZOwHpnVG/xwXrV90U8 github.com/mailru/easyjson v0.7.1/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= -github.com/matryer/moq v0.2.7/go.mod h1:kITsx543GOENm48TUAQyJ9+SAvFSr7iGQXPoth/VUBk= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.0/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= @@ -602,6 +596,8 @@ github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVc github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= @@ -614,12 +610,14 @@ github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcME github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= +github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= @@ -643,15 +641,17 @@ github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS4 github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.3.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/montanaflynn/stats v0.0.0-20151014174947-eeaced052adb/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= github.com/montanaflynn/stats v0.0.0-20180911141734-db72e6cae808/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= github.com/montanaflynn/stats v0.5.0/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= @@ -664,6 +664,7 @@ github.com/nicksnyder/go-i18n v1.10.0/go.mod h1:HrK7VCrbOvQoUAQ7Vpy7i87N7JZZZ7R2 github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA= @@ -754,7 +755,6 @@ github.com/pingcap/tipb v0.0.0-20200522051215-f31a15d98fce h1:LDyY6Xh/Z/SHVQ10er github.com/pingcap/tipb v0.0.0-20200522051215-f31a15d98fce/go.mod h1:RtkHW8WbcNxj8lsbzjaILci01CtYnYbIkQhjyZWrWVI= github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4= github.com/pjbgf/sha1cd v0.3.0/go.mod h1:nZ1rrWOcGJ5uZgEEVL1VUM9iRQiZvWdbZjkKyFzPPsI= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -798,8 +798,6 @@ github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzG github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= @@ -848,9 +846,7 @@ github.com/sjjian/parser v0.0.0-20231122073510-03e191068cf1/go.mod h1:Qq2tnreUXw github.com/skeema/knownhosts v1.2.0 h1:h9r9cf0+u7wSE+M183ZtMGgOJKiL96brpaz5ekfJCpM= github.com/skeema/knownhosts v1.2.0/go.mod h1:g4fPeYpque7P0xefxtGzV81ihjC8sX2IqpAoNkjxbMo= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/assertions v1.1.0 h1:MkTeG1DMwsrdH7QtLXy5W+fUxWq+vmb6cLmyJ7aRtF0= github.com/smartystreets/assertions v1.1.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ= @@ -873,14 +869,19 @@ github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5q github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/struCoder/pidusage v0.1.2/go.mod h1:pWBlW3YuSwRl6h7R5KbvA4N8oOqe9LjaKW5CwT1SPjI= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/swaggo/echo-swagger v1.0.0 h1:ppQFt6Am3/MHIUmTpZOwi4gggMZ/W9zmKP4Z9ahTe5c= @@ -904,8 +905,9 @@ github.com/tiancaiamao/appdash v0.0.0-20181126055449-889f96f722a2/go.mod h1:2PfK github.com/tidwall/gjson v1.3.5/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls= github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= -github.com/tjfoc/gmsm v1.3.2 h1:7JVkAn5bvUJ7HtU08iW6UiD+UTmJTIToHCfeFzkcCxM= github.com/tjfoc/gmsm v1.3.2/go.mod h1:HaUcFuY0auTiaHB9MHFGCPx5IaLhTUd2atbCFBQXn9w= +github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho= +github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20171017195756-830351dc03c6/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -938,26 +940,27 @@ github.com/urfave/cli/v2 v2.8.1/go.mod h1:Z41J9TPoffeoqP0Iza0YbAhGvymRdZAd2uPmZ5 github.com/urfave/negroni v0.3.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasttemplate v0.0.0-20170224212429-dcecefd839c4/go.mod h1:50wTf68f99/Zt14pr046Tgt3Lp2vLyFZKzbFXTOabXw= github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= -github.com/valyala/fasttemplate v1.2.1 h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4= github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/vektah/gqlparser/v2 v2.5.1 h1:ZGu+bquAY23jsxDRcYpWjttRZrUz07LbiY77gUOHcr4= -github.com/vektah/gqlparser/v2 v2.5.1/go.mod h1:mPgqFBu/woKTVYWyNk8cO3kh4S/f4aRFZrvOnp3hmCs= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 h1:eY9dn8+vbi4tKz5Qo6v2eYzo7kUS51QINcR5jNpbZS8= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= github.com/yookoala/realpath v1.0.0/go.mod h1:gJJMA9wuX7AcqLy1+ffPatSCySA1FQ2S8Ya9AIoYBpE= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= @@ -967,6 +970,8 @@ go.etcd.io/etcd v0.0.0-20190320044326-77d4b742cdbf/go.mod h1:KSGwdbiFchh5KIC9My2 go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= go.etcd.io/etcd v0.5.0-alpha.5.0.20191023171146-3cf2f69b5738 h1:lWF4f9Nypl1ZqSb4gLeh/DGvBYVaUYHuiB93teOmwgc= go.etcd.io/etcd v0.5.0-alpha.5.0.20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= +go.mongodb.org/mongo-driver v1.12.0 h1:aPx33jmn/rQuJXPQLZQ8NtfPQG8CaqgLThFtqRb0PiE= +go.mongodb.org/mongo-driver v1.12.0/go.mod h1:AZkxhPnFJUoH7kZlFkVKucV20K387miPfm7oimrSmK0= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -1002,7 +1007,6 @@ golang.org/x/crypto v0.0.0-20180608092829-8ac0e0d97ce4/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190130090550-b01c7a725664/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= @@ -1017,8 +1021,8 @@ golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20191219195013-becbf705a915/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200204104054-c9f3fb736b72/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= @@ -1028,6 +1032,7 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -1059,7 +1064,6 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= @@ -1096,17 +1100,18 @@ golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210224082022-3d97a244fca7/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210913180222-943fd674d43e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -1134,7 +1139,6 @@ golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181228144115-9a3f9b0469bb/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1168,9 +1172,9 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210910150752-751e447fb3d0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1179,6 +1183,8 @@ golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= @@ -1187,6 +1193,8 @@ golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuX golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo= golang.org/x/term v0.12.0 h1:/ZfYdc3zq+q02Rv9vGqTeSItdzZTSNDmfTi0mBAuidU= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1196,17 +1204,20 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs= -golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -1251,7 +1262,6 @@ golang.org/x/tools v0.0.0-20200325203130-f53864d0dba1/go.mod h1:Sl4aGygMT6LrqrWc golang.org/x/tools v0.0.0-20200509030707-2212a7e161a5/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20201125231158-b5590deeca9b/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= @@ -1297,6 +1307,12 @@ google.golang.org/genproto v0.0.0-20210701191553-46259e63a0a9 h1:HBPuvo39L0DgfVn google.golang.org/genproto v0.0.0-20210701191553-46259e63a0a9/go.mod h1:yiaVoXHpRzHGyxV3o4DktVWY4mSUErTKaeEOq6C3t3U= google.golang.org/grpc v1.29.0 h1:2pJjwYOdkZ9HlN4sWRYBg9ttH5bCOlsueaM+b/oYjwo= google.golang.org/grpc v1.29.0/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= @@ -1306,10 +1322,6 @@ gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4 gopkg.in/alecthomas/gometalinter.v2 v2.0.12/go.mod h1:NDRytsqEZyolNuAgTzJkZMkSQM7FIKyzVzGhjB/qfYo= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c/go.mod h1:3HH7i1SgMqlzxCcBmUHW657sD4Kvv9sC3HpL3YukzwA= -gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= -gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= -gopkg.in/chanxuehong/wechat.v1 v1.0.0-20171118020122-aad7e298d1e7 h1:VqKldcu82X3eGPRiJ0M3ewTxCYpvKBxExGQJhmycwpU= -gopkg.in/chanxuehong/wechat.v1 v1.0.0-20171118020122-aad7e298d1e7/go.mod h1:k8z0IA51BPvL3wX1QPXAVtBY2JQ7mEQwSBu+EJ0+4fI= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -1324,13 +1336,12 @@ gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8 gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ= gopkg.in/go-playground/validator.v9 v9.31.0/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ= -gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= -gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.56.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= diff --git a/image.png b/image.png new file mode 100644 index 0000000000..0f862b4949 Binary files /dev/null and b/image.png differ diff --git a/scripts/init_start.sh b/scripts/init_start.sh new file mode 100644 index 0000000000..c03e1ef308 --- /dev/null +++ b/scripts/init_start.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +# 本脚本用于在rpm安装完成后,启动dms服务和sqled服务 + +detectSystemServiceStatus() { + detectedRunningTimes=0 + for i in {1..30}; do + sleep 1 + if systemctl status "$1" &>/dev/null; then + ((detectedRunningTimes++)) + if [[ $detectedRunningTimes == 3 ]]; then + return 0 + fi + else + detectedRunningTimes=0 + fi + done + + return 1 +} + +systemctl daemon-reload +systemctl start dms.service + +# 10秒dms还没有启动成功退出 +if detectSystemServiceStatus "dms.service"; then + echo "init and start dms success!" +else + echo "duration 30 seconds; start dms failed" + exit 3 +fi + +systemctl start sqled.service + +# 10秒sqle还没有启动成功退出 +if detectSystemServiceStatus "sqled.service"; then + echo "init and start sqled success!" +else + echo "duration 30 seconds; start sqled failed" +fi \ No newline at end of file diff --git a/spelling_dict.txt b/spelling_dict.txt index 1e18e11a62..e6e13d7864 100644 --- a/spelling_dict.txt +++ b/spelling_dict.txt @@ -21,6 +21,7 @@ bigint binlog blkid btree +brazil chinese cidr cardinalities @@ -88,6 +89,8 @@ gracenet grpc gtids gzipped +huawei +huaweicloud hashicorp hclog hostname @@ -128,6 +131,7 @@ longtext looper maxvalue mdriver +mexico mediumblob mediumint mediumtext diff --git a/sqle/api/app.go b/sqle/api/app.go index 4544435294..c995568c5c 100644 --- a/sqle/api/app.go +++ b/sqle/api/app.go @@ -5,7 +5,9 @@ import ( "fmt" "net/http" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper" + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + + // "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper" "github.com/actiontech/sqle/sqle/api/controller" v1 "github.com/actiontech/sqle/sqle/api/controller/v1" v2 "github.com/actiontech/sqle/sqle/api/controller/v2" @@ -14,8 +16,6 @@ import ( _ "github.com/actiontech/sqle/sqle/docs" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" - "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/utils" "github.com/facebookgo/grace/gracenet" "github.com/labstack/echo/v4" @@ -73,11 +73,11 @@ func addCustomApis(e *echo.Group, apis []restApi) error { // @in header // @name Authorization // @BasePath / -func StartApi(net *gracenet.Net, exitChan chan struct{}, config config.SqleConfig) { +func StartApi(net *gracenet.Net, exitChan chan struct{}, config *config.SqleOptions) { defer close(exitChan) e := echo.New() - output := log.NewRotateFile(config.LogPath, "/api.log", config.LogMaxSizeMB /*MB*/, config.LogMaxBackupNumber) + output := log.NewRotateFile(config.Service.LogPath, "/api.log", config.Service.LogMaxSizeMB /*MB*/, config.Service.LogMaxBackupNumber) defer output.Close() e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ @@ -99,343 +99,261 @@ func StartApi(net *gracenet.Net, exitChan chan struct{}, config config.SqleConfi e.GET("/swagger/*", echoSwagger.WrapHandler) - e.POST("/v1/login", v1.LoginV1) - e.POST("/v2/login", v2.LoginV2) - - // the operation of obtaining the basic information of the platform should be for all users, not the users who log in to the platform - e.GET("/v1/basic_info", v1.GetSQLEInfo) - e.GET("/v1/static/logo", v1.GetLogo) - - // oauth2 interface does not require login authentication - e.GET("/v1/configurations/oauth2/tips", v1.GetOauth2Tips) - e.GET("/v1/oauth2/link", v1.Oauth2Link) - e.GET("/v1/oauth2/callback", v1.Oauth2Callback) - e.POST("/v1/oauth2/user/bind", v1.BindOauth2User) - v1Router := e.Group(apiV1) - v1Router.Use(sqleMiddleware.JWTTokenAdapter(), sqleMiddleware.JWTWithConfig(utils.JWTSecretKey), sqleMiddleware.VerifyUserIsDisabled(), sqleMiddleware.LicenseAdapter(), sqleMiddleware.OperationLogRecord()) + v1Router.Use(sqleMiddleware.JWTTokenAdapter(), sqleMiddleware.JWTWithConfig(dmsV1.JwtSigningKey), sqleMiddleware.VerifyUserIsDisabled(), sqleMiddleware.OperationLogRecord()) v2Router := e.Group(apiV2) - v2Router.Use(sqleMiddleware.JWTTokenAdapter(), sqleMiddleware.JWTWithConfig(utils.JWTSecretKey), sqleMiddleware.VerifyUserIsDisabled(), sqleMiddleware.LicenseAdapter(), sqleMiddleware.OperationLogRecord()) + v2Router.Use(sqleMiddleware.JWTTokenAdapter(), sqleMiddleware.JWTWithConfig(dmsV1.JwtSigningKey), sqleMiddleware.VerifyUserIsDisabled(), sqleMiddleware.OperationLogRecord()) // v1 admin api, just admin user can access. { - // user - v1Router.GET("/users", v1.GetUsers, AdminUserAllowed()) - v1Router.POST("/users", v1.CreateUser, AdminUserAllowed()) - v1Router.GET("/users/:user_name/", v1.GetUser, AdminUserAllowed()) - v1Router.PATCH("/users/:user_name/", v1.UpdateUser, AdminUserAllowed()) - v1Router.DELETE("/users/:user_name/", v1.DeleteUser, AdminUserAllowed()) - v1Router.PATCH("/users/:user_name/password", v1.UpdateOtherUserPassword, AdminUserAllowed()) - - // user_group - v1Router.POST("/user_groups", v1.CreateUserGroup, AdminUserAllowed()) - v1Router.GET("/user_groups", v1.GetUserGroups, AdminUserAllowed()) - v1Router.DELETE("/user_groups/:user_group_name/", v1.DeleteUserGroup, AdminUserAllowed()) - v1Router.PATCH("/user_groups/:user_group_name/", v1.UpdateUserGroup, AdminUserAllowed()) - - // role - v1Router.GET("/roles", v1.GetRoles, AdminUserAllowed()) - v1Router.POST("/roles", v1.CreateRole, AdminUserAllowed()) - v1Router.PATCH("/roles/:role_name/", v1.UpdateRole, AdminUserAllowed()) - v1Router.DELETE("/roles/:role_name/", v1.DeleteRole, AdminUserAllowed()) - // rule template - v1Router.POST("/rule_templates", v1.CreateRuleTemplate, AdminUserAllowed()) - v1Router.POST("/rule_templates/:rule_template_name/clone", v1.CloneRuleTemplate, AdminUserAllowed()) - v1Router.PATCH("/rule_templates/:rule_template_name/", v1.UpdateRuleTemplate, AdminUserAllowed()) - v1Router.DELETE("/rule_templates/:rule_template_name/", v1.DeleteRuleTemplate, AdminUserAllowed()) - v1Router.GET("/rule_templates/:rule_template_name/export", v1.ExportRuleTemplateFile, AdminUserAllowed()) - v1Router.DELETE("/custom_rules/:rule_id", v1.DeleteCustomRule, AdminUserAllowed()) - v1Router.POST("/custom_rules", v1.CreateCustomRule, AdminUserAllowed()) - v1Router.PATCH("/custom_rules/:rule_id", v1.UpdateCustomRule, AdminUserAllowed()) - v1Router.PATCH("/rule_knowledge/db_types/:db_type/rules/:rule_name/", v1.UpdateRuleKnowledgeV1, AdminUserAllowed()) - v1Router.PATCH("/rule_knowledge/db_types/:db_type/custom_rules/:rule_name/", v1.UpdateCustomRuleKnowledgeV1, AdminUserAllowed()) - + v1Router.POST("/rule_templates", v1.CreateRuleTemplate, sqleMiddleware.AdminUserAllowed()) + v1Router.POST("/rule_templates/:rule_template_name/clone", v1.CloneRuleTemplate, sqleMiddleware.AdminUserAllowed()) + v1Router.PATCH("/rule_templates/:rule_template_name/", v1.UpdateRuleTemplate, sqleMiddleware.AdminUserAllowed()) + v1Router.DELETE("/rule_templates/:rule_template_name/", v1.DeleteRuleTemplate, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/rule_templates/:rule_template_name/export", v1.ExportRuleTemplateFile, sqleMiddleware.AdminUserAllowed()) + v1Router.DELETE("/custom_rules/:rule_id", v1.DeleteCustomRule, sqleMiddleware.AdminUserAllowed()) + v1Router.POST("/custom_rules", v1.CreateCustomRule, sqleMiddleware.AdminUserAllowed()) + v1Router.PATCH("/custom_rules/:rule_id", v1.UpdateCustomRule, sqleMiddleware.AdminUserAllowed()) + v1Router.PATCH("/rule_knowledge/db_types/:db_type/rules/:rule_name/", v1.UpdateRuleKnowledgeV1, sqleMiddleware.AdminUserAllowed()) + v1Router.PATCH("/rule_knowledge/db_types/:db_type/custom_rules/:rule_name/", v1.UpdateCustomRuleKnowledgeV1, sqleMiddleware.AdminUserAllowed()) // configurations - v1Router.GET("/configurations/ldap", v1.GetLDAPConfiguration, AdminUserAllowed()) - v1Router.PATCH("/configurations/ldap", v1.UpdateLDAPConfiguration, AdminUserAllowed()) - v1Router.GET("/configurations/smtp", v1.GetSMTPConfiguration, AdminUserAllowed()) - v1Router.POST("/configurations/smtp/test", v1.TestSMTPConfigurationV1, AdminUserAllowed()) - v1Router.PATCH("/configurations/smtp", v1.UpdateSMTPConfiguration, AdminUserAllowed()) - v1Router.GET("/configurations/wechat", v1.GetWeChatConfiguration, AdminUserAllowed()) - v1Router.PATCH("/configurations/wechat", v1.UpdateWeChatConfigurationV1, AdminUserAllowed()) - v1Router.POST("/configurations/wechat/test", v1.TestWeChatConfigurationV1, AdminUserAllowed()) - v1Router.GET("/configurations/ding_talk", v1.GetDingTalkConfigurationV1, AdminUserAllowed()) - v1Router.PATCH("/configurations/ding_talk", v1.UpdateDingTalkConfigurationV1, AdminUserAllowed()) - v1Router.POST("/configurations/ding_talk/test", v1.TestDingTalkConfigV1, AdminUserAllowed()) - v1Router.GET("/configurations/feishu", v1.GetFeishuConfigurationV1, AdminUserAllowed()) - v1Router.PATCH("/configurations/feishu", v1.UpdateFeishuConfigurationV1, AdminUserAllowed()) - v1Router.POST("/configurations/feishu/test", v1.TestFeishuConfigV1, AdminUserAllowed()) - v1Router.PATCH("/configurations/feishu_audit", v1.UpdateFeishuAuditConfigurationV1, AdminUserAllowed()) - v1Router.GET("/configurations/feishu_audit", v1.GetFeishuAuditConfigurationV1, AdminUserAllowed()) - v1Router.POST("/configurations/feishu_audit/test", v1.TestFeishuAuditConfigV1, AdminUserAllowed()) - v1Router.GET("/configurations/system_variables", v1.GetSystemVariables, AdminUserAllowed()) - v1Router.PATCH("/configurations/system_variables", v1.UpdateSystemVariables, AdminUserAllowed()) - v1Router.GET("/configurations/license", v1.GetLicense, AdminUserAllowed()) - v1Router.POST("/configurations/license", v1.SetLicense, AdminUserAllowed()) - v1Router.GET("/configurations/license/info", v1.GetSQLELicenseInfo, AdminUserAllowed()) - v1Router.POST("/configurations/license/check", v1.CheckLicense, AdminUserAllowed()) - v1Router.GET("/configurations/oauth2", v1.GetOauth2Configuration, AdminUserAllowed()) - v1Router.PATCH("/configurations/oauth2", v1.UpdateOauth2Configuration, AdminUserAllowed()) - v1Router.POST("/configurations/personalise/logo", v1.UploadLogo, AdminUserAllowed()) - v1Router.PATCH("/configurations/personalise", v1.UpdatePersonaliseConfig, AdminUserAllowed()) - v1Router.PATCH("/configurations/webhook", v1.UpdateWorkflowWebHookConfig, AdminUserAllowed()) - v1Router.GET("/configurations/webhook", v1.GetWorkflowWebHookConfig, AdminUserAllowed()) - v1Router.POST("/configurations/webhook/test", v1.TestWorkflowWebHookConfig, AdminUserAllowed()) + v1Router.GET("/configurations/ding_talk", v1.GetDingTalkConfigurationV1, sqleMiddleware.AdminUserAllowed()) + v1Router.PATCH("/configurations/ding_talk", v1.UpdateDingTalkConfigurationV1, sqleMiddleware.AdminUserAllowed()) + v1Router.POST("/configurations/ding_talk/test", v1.TestDingTalkConfigV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/configurations/system_variables", v1.GetSystemVariables, sqleMiddleware.AdminUserAllowed()) + v1Router.PATCH("/configurations/system_variables", v1.UpdateSystemVariables, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/configurations/license", v1.GetLicense, sqleMiddleware.AdminUserAllowed()) + v1Router.POST("/configurations/license", v1.SetLicense, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/configurations/license/info", v1.GetSQLELicenseInfo, sqleMiddleware.AdminUserAllowed()) + v1Router.POST("/configurations/license/check", v1.CheckLicense, sqleMiddleware.AdminUserAllowed()) + v1Router.PATCH("/configurations/feishu_audit", v1.UpdateFeishuAuditConfigurationV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/configurations/feishu_audit", v1.GetFeishuAuditConfigurationV1, sqleMiddleware.AdminUserAllowed()) + v1Router.POST("/configurations/feishu_audit/test", v1.TestFeishuAuditConfigV1, sqleMiddleware.AdminUserAllowed()) // statistic - v1Router.GET("/statistic/instances/type_percent", v1.GetInstancesTypePercentV1, AdminUserAllowed()) - v1Router.GET("/statistic/instances/sql_average_execution_time", v1.GetSqlAverageExecutionTimeV1, AdminUserAllowed()) - v1Router.GET("/statistic/instances/sql_execution_fail_percent", v1.GetSqlExecutionFailPercentV1, AdminUserAllowed()) - v1Router.GET("/statistic/license/usage", v1.GetLicenseUsageV1, AdminUserAllowed()) - v1Router.GET("/statistic/workflows/rejected_percent_group_by_creator", v1.GetWorkflowRejectedPercentGroupByCreatorV1, AdminUserAllowed()) - //v1Router.GET("/statistic/workflows/rejected_percent_group_by_instance", v1.GetWorkflowRejectedPercentGroupByInstanceV1, AdminUserAllowed()) - v1Router.GET("/statistic/workflows/counts", v1.GetWorkflowCountsV1, AdminUserAllowed()) - v1Router.GET("/statistic/workflows/duration_of_waiting_for_audit", v1.GetWorkflowDurationOfWaitingForAuditV1, AdminUserAllowed()) - //v1Router.GET("/statistic/workflows/duration_of_waiting_for_execution", v1.GetWorkflowDurationOfWaitingForExecutionV1, AdminUserAllowed()) - //v1Router.GET("/statistic/workflows/pass_percent", v1.GetWorkflowPassPercentV1, AdminUserAllowed()) - v1Router.GET("/statistic/workflows/audit_pass_percent", v1.GetWorkflowAuditPassPercentV1, AdminUserAllowed()) - v1Router.GET("/statistic/workflows/each_day_counts", v1.GetWorkflowCreatedCountsEachDayV1, AdminUserAllowed()) - v1Router.GET("/statistic/workflows/status_count", v1.GetWorkflowStatusCountV1, AdminUserAllowed()) - v1Router.GET("/statistic/workflows/instance_type_percent", v1.GetWorkflowPercentCountedByInstanceTypeV1, AdminUserAllowed()) - - // sync instance - v1Router.POST("/sync_instances", v1.CreateSyncInstanceTask, AdminUserAllowed()) - v1Router.GET("/sync_instances", v1.GetSyncInstanceTaskList, AdminUserAllowed()) - v1Router.GET("/sync_instances/:task_id/", v1.GetSyncInstanceTask, AdminUserAllowed()) - v1Router.PATCH("/sync_instances/:task_id/", v1.UpdateSyncInstanceTask, AdminUserAllowed()) - v1Router.GET("/sync_instances/source_tips", v1.GetSyncTaskSourceTips, AdminUserAllowed()) - v1Router.DELETE("/sync_instances/:task_id/", v1.DeleteSyncInstanceTask, AdminUserAllowed()) - v1Router.POST("/sync_instances/:task_id/trigger", v1.TriggerSyncInstance, AdminUserAllowed()) + v1Router.GET("/statistic/instances/type_percent", v1.GetInstancesTypePercentV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/instances/sql_average_execution_time", v1.GetSqlAverageExecutionTimeV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/license/usage", v1.GetLicenseUsageV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/workflows/rejected_percent_group_by_creator", v1.GetWorkflowRejectedPercentGroupByCreatorV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/workflows/counts", v1.GetWorkflowCountsV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/workflows/duration_of_waiting_for_audit", v1.GetWorkflowDurationOfWaitingForAuditV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/workflows/audit_pass_percent", v1.GetWorkflowAuditPassPercentV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/workflows/each_day_counts", v1.GetWorkflowCreatedCountsEachDayV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/workflows/status_count", v1.GetWorkflowStatusCountV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/statistic/workflows/instance_type_percent", v1.GetWorkflowPercentCountedByInstanceTypeV1, sqleMiddleware.AdminUserAllowed()) // operation record - v1Router.GET("/operation_records/operation_type_names", v1.GetOperationTypeNameList, AdminUserAllowed()) - v1Router.GET("/operation_records/operation_actions", v1.GetOperationActionList, AdminUserAllowed()) - v1Router.GET("/operation_records", v1.GetOperationRecordListV1, AdminUserAllowed()) - v1Router.GET("/operation_records/exports", v1.GetExportOperationRecordListV1, AdminUserAllowed()) - - // other - v1Router.GET("/management_permissions", v1.GetManagementPermissions, AdminUserAllowed()) + v1Router.GET("/operation_records/operation_type_names", v1.GetOperationTypeNameList, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/operation_records/operation_actions", v1.GetOperationActionList, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/operation_records", v1.GetOperationRecordListV1, sqleMiddleware.AdminUserAllowed()) + v1Router.GET("/operation_records/exports", v1.GetExportOperationRecordListV1, sqleMiddleware.AdminUserAllowed()) // 企业公告 - v1Router.PATCH("/company_notice", v1.UpdateCompanyNotice, AdminUserAllowed()) + v1Router.PATCH("/company_notice", v1.UpdateCompanyNotice, sqleMiddleware.AdminUserAllowed()) + + // 内部调用 + v1Router.POST("/data_resource/handle", v1.OperateDataResourceHandle, sqleMiddleware.AdminUserAllowed()) + v1Router.POST(fmt.Sprintf("%s/connection", dmsV1.InternalDBServiceRouterGroup), v1.CheckInstanceIsConnectable, sqleMiddleware.AdminUserAllowed()) } - // auth - v1Router.POST("/logout", v1.LogoutV1) - - // statistic - v1Router.GET("/projects/:project_name/statistics", v1.GetProjectStatisticsV1) - v1Router.GET("/projects/:project_name/statistic/audited_sqls", v1.StatisticsAuditedSQLV1) - v1Router.GET("/projects/:project_name/statistic/workflow_status", v1.StatisticWorkflowStatusV1) - v1Router.GET("/projects/:project_name/statistic/risk_workflow", v1.StatisticRiskWorkflowV1) - v1Router.GET("/projects/:project_name/statistic/audit_plans", v1.StatisticAuditPlanV1) - v1Router.GET("/projects/:project_name/statistic/risk_audit_plans", v1.GetRiskAuditPlanV1) - v1Router.GET("/projects/:project_name/statistic/role_user", v1.GetRoleUserCountV1) - v1Router.GET("/projects/:project_name/statistic/project_score", v1.GetProjectScoreV1) - v1Router.GET("/projects/:project_name/statistic/instance_health", v1.GetInstanceHealthV1) - - // audit whitelist - v1Router.GET("/projects/:project_name/audit_whitelist", v1.GetSqlWhitelist) - v1Router.POST("/projects/:project_name/audit_whitelist", v1.CreateAuditWhitelist) - v1Router.PATCH("/projects/:project_name/audit_whitelist/:audit_whitelist_id/", v1.UpdateAuditWhitelistById) - v1Router.DELETE("/projects/:project_name/audit_whitelist/:audit_whitelist_id/", v1.DeleteAuditWhitelistById) - - // project - v1Router.PATCH("/projects/:project_name/", v1.UpdateProjectV1) - v1Router.DELETE("/projects/:project_name/", v1.DeleteProjectV1) - v1Router.POST("/projects", v1.CreateProjectV1) - v1Router.POST("/projects/:project_name/archive", v1.ArchiveProjectV1) - v1Router.POST("/projects/:project_name/unarchive", v1.UnarchiveProjectV1) - v1Router.GET("/projects", v1.GetProjectListV1) - v1Router.GET("/projects/:project_name/", v1.GetProjectDetailV1) - v1Router.GET("/project_tips", v1.GetProjectTipsV1) - - // role - v1Router.GET("/role_tips", v1.GetRoleTips) - - // user - v1Router.GET("/user", v1.GetCurrentUser) - v1Router.PATCH("/user", v1.UpdateCurrentUser) - v1Router.GET("/user_tips", v1.GetUserTips) - v1Router.PUT("/user/password", v1.UpdateCurrentUserPassword) - v1Router.POST("/projects/:project_name/members", v1.AddMember) - v1Router.PATCH("/projects/:project_name/members/:user_name/", v1.UpdateMember) - v1Router.DELETE("/projects/:project_name/members/:user_name/", v1.DeleteMember) - v1Router.GET("/projects/:project_name/members", v1.GetMembers) - v1Router.GET("/projects/:project_name/members/:user_name/", v1.GetMember) - v1Router.GET("/projects/:project_name/member_tips", v1.GetMemberTips) - - // user group - v1Router.POST("/projects/:project_name/member_groups", v1.AddMemberGroup) - v1Router.PATCH("/projects/:project_name/member_groups/:user_group_name/", v1.UpdateMemberGroup) - v1Router.DELETE("/projects/:project_name/member_groups/:user_group_name/", v1.DeleteMemberGroup) - v1Router.GET("/projects/:project_name/member_groups", v1.GetMemberGroups) - v1Router.GET("/projects/:project_name/member_groups/:user_group_name/", v1.GetMemberGroup) - v1Router.GET("/user_group_tips", v1.GetUserGroupTips) - - // operations - v1Router.GET("/operations", v1.GetOperations) - - // instance - v1Router.GET("/projects/:project_name/instances", v1.GetInstances) - v2Router.GET("/projects/:project_name/instances", v2.GetInstances) - v1Router.GET("/projects/:project_name/instances/:instance_name/", v1.GetInstance) - v2Router.GET("/projects/:project_name/instances/:instance_name/", v2.GetInstance) - v1Router.GET("/projects/:project_name/instances/:instance_name/connection", v1.CheckInstanceIsConnectableByName) - v1Router.POST("/instance_connection", v1.CheckInstanceIsConnectable) - v1Router.POST("/projects/:project_name/instances/connections", v1.BatchCheckInstanceConnections) - v1Router.GET("/projects/:project_name/instances/:instance_name/schemas", v1.GetInstanceSchemas) - v1Router.GET("/projects/:project_name/instance_tips", v1.GetInstanceTips) - v1Router.GET("/projects/:project_name/instances/:instance_name/rules", v1.GetInstanceRules) - v1Router.GET("/projects/:project_name/instances/:instance_name/schemas/:schema_name/tables", v1.ListTableBySchema) - v1Router.GET("/projects/:project_name/instances/:instance_name/schemas/:schema_name/tables/:table_name/metadata", v1.GetTableMetadata) - v1Router.POST("/projects/:project_name/instances", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/instances", v2.CreateInstance) - v1Router.GET("/instance_additional_metas", v1.GetInstanceAdditionalMetas) - v1Router.DELETE("/projects/:project_name/instances/:instance_name/", v1.DeleteInstance) - v1Router.PATCH("/projects/:project_name/instances/:instance_name/", v1.UpdateInstance) - v1Router.GET("/static/instance_logo", v1.GetInstanceTypeLogo) - - // rule template - v1Router.GET("/rule_templates", v1.GetRuleTemplates) - v1Router.GET("/rule_template_tips", v1.GetRuleTemplateTips) - v1Router.GET("/rule_templates/:rule_template_name/", v1.GetRuleTemplate) - v1Router.POST("/projects/:project_name/rule_templates", v1.CreateProjectRuleTemplate) - v1Router.PATCH("/projects/:project_name/rule_templates/:rule_template_name/", v1.UpdateProjectRuleTemplate) - v1Router.GET("/projects/:project_name/rule_templates/:rule_template_name/", v1.GetProjectRuleTemplate) - v1Router.DELETE("/projects/:project_name/rule_templates/:rule_template_name/", v1.DeleteProjectRuleTemplate) - v1Router.GET("/projects/:project_name/rule_templates", v1.GetProjectRuleTemplates) - v1Router.POST("/projects/:project_name/rule_templates/:rule_template_name/clone", v1.CloneProjectRuleTemplate) - v1Router.GET("/projects/:project_name/rule_template_tips", v1.GetProjectRuleTemplateTips) - v1Router.POST("/rule_templates/parse", v1.ParseProjectRuleTemplateFile) - v1Router.GET("/projects/:project_name/rule_templates/:rule_template_name/export", v1.ExportProjectRuleTemplateFile) - v1Router.GET("/rule_knowledge/db_types/:db_type/rules/:rule_name/", v1.GetRuleKnowledge) - v1Router.GET("/rule_knowledge/db_types/:db_type/custom_rules/:rule_name/", v1.GetCustomRuleKnowledge) - - //rule - v1Router.GET("/rules", v1.GetRules) - v1Router.GET("/custom_rules", v1.GetCustomRules) - v1Router.GET("/custom_rules/:rule_id", v1.GetCustomRule) - v1Router.GET("/custom_rules/:db_type/rule_types", v1.GetRuleTypeByDBType) - - // workflow template - v1Router.GET("/projects/:project_name/workflow_template", v1.GetWorkflowTemplate) - v1Router.PATCH("/projects/:project_name/workflow_template", v1.UpdateWorkflowTemplate) - - // workflow - v1Router.POST("/projects/:project_name/workflows", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/workflows", v2.CreateWorkflowV2) - v1Router.GET("/projects/:project_name/workflows/:workflow_name/", DeprecatedBy(apiV2)) - v2Router.GET("/projects/:project_name/workflows/:workflow_id/", v2.GetWorkflowV2) - v1Router.GET("/workflows", v1.GetGlobalWorkflowsV1) - v1Router.GET("/projects/:project_name/workflows", v1.GetWorkflowsV1) - v1Router.POST("/projects/:project_name/workflows/:workflow_name/steps/:workflow_step_id/approve", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/workflows/:workflow_id/steps/:workflow_step_id/approve", v2.ApproveWorkflowV2) - v1Router.POST("/projects/:project_name/workflows/:workflow_name/steps/:workflow_step_id/reject", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/workflows/:workflow_id/steps/:workflow_step_id/reject", v2.RejectWorkflowV2) - v1Router.POST("/projects/:project_name/workflows/:workflow_name/cancel", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/workflows/:workflow_id/cancel", v2.CancelWorkflowV2) - v1Router.POST("/projects/:project_name/workflows/cancel", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/workflows/cancel", v2.BatchCancelWorkflowsV2) - v1Router.POST("/projects/:project_name/workflows/complete", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/workflows/complete", v2.BatchCompleteWorkflowsV2) - v1Router.POST("/projects/:project_name/workflows/:workflow_name/tasks/:task_id/execute", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/workflows/:workflow_id/tasks/:task_id/execute", v2.ExecuteOneTaskOnWorkflowV2) - v1Router.POST("/projects/:project_name/workflows/:workflow_id/tasks/:task_id/terminate", v1.TerminateSingleTaskByWorkflowV1) - v1Router.GET("/projects/:project_name/workflows/:workflow_name/tasks", DeprecatedBy(apiV2)) - v2Router.GET("/projects/:project_name/workflows/:workflow_id/tasks", v2.GetSummaryOfWorkflowTasksV2) - v1Router.POST("/projects/:project_name/workflows/:workflow_name/tasks/execute", DeprecatedBy(apiV2)) - v2Router.POST("/projects/:project_name/workflows/:workflow_id/tasks/execute", v2.ExecuteTasksOnWorkflowV2) - v1Router.POST("/projects/:project_name/workflows/:workflow_id/tasks/terminate", v1.TerminateMultipleTaskByWorkflowV1) - v1Router.PUT("/projects/:project_name/workflows/:workflow_name/tasks/:task_id/schedule", DeprecatedBy(apiV2)) - v2Router.PUT("/projects/:project_name/workflows/:workflow_id/tasks/:task_id/schedule", v2.UpdateWorkflowScheduleV2) - v1Router.PATCH("/projects/:project_name/workflows/:workflow_name/", DeprecatedBy(apiV2)) - v2Router.PATCH("/projects/:project_name/workflows/:workflow_id/", v2.UpdateWorkflowV2) - v1Router.GET("/projects/:project_name/workflows/exports", v1.ExportWorkflowV1) - - // task - v1Router.POST("/projects/:project_name/tasks/audits", v1.CreateAndAuditTask) - v1Router.GET("/tasks/audits/:task_id/", v1.GetTask) - v1Router.GET("/tasks/audits/:task_id/sqls", v1.GetTaskSQLs) - v2Router.GET("/tasks/audits/:task_id/sqls", v2.GetTaskSQLs) - v1Router.GET("/tasks/audits/:task_id/sql_report", v1.DownloadTaskSQLReportFile) - v1Router.GET("/tasks/audits/:task_id/sql_file", v1.DownloadTaskSQLFile) - v1Router.GET("/tasks/audits/:task_id/sql_content", v1.GetAuditTaskSQLContent) - v1Router.PATCH("/tasks/audits/:task_id/sqls/:number", v1.UpdateAuditTaskSQLs) - v1Router.GET("/tasks/audits/:task_id/sqls/:number/analysis", v1.GetTaskAnalysisData) - v2Router.GET("/tasks/audits/:task_id/sqls/:number/analysis", v2.GetTaskAnalysisData) - v1Router.POST("/projects/:project_name/task_groups", v1.CreateAuditTasksGroupV1) - v1Router.POST("/task_groups/audit", v1.AuditTaskGroupV1) - - // dashboard - v1Router.GET("/dashboard", v1.Dashboard) - v1Router.GET("/dashboard/project_tips", v1.DashboardProjectTipsV1) - - // configurations - v1Router.GET("/configurations/drivers", v1.GetDrivers) - v2Router.GET("/configurations/drivers", v2.GetDrivers) - v1Router.GET("/configurations/sql_query", v1.GetSQLQueryConfiguration) - - // audit plan - v1Router.GET("/audit_plan_metas", v1.GetAuditPlanMetas) - v1Router.GET("/audit_plan_types", v1.GetAuditPlanTypes) - - // project - audit plan - v1Router.POST("/projects/:project_name/audit_plans", v1.CreateAuditPlan) - v1Router.GET("/projects/:project_name/audit_plans", v1.GetAuditPlans) - v2Router.GET("/projects/:project_name/audit_plans", v2.GetAuditPlans) - v1Router.DELETE("/projects/:project_name/audit_plans/:audit_plan_name/", v1.DeleteAuditPlan) - v1Router.PATCH("/projects/:project_name/audit_plans/:audit_plan_name/", v1.UpdateAuditPlan) - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/", v1.GetAuditPlan) - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/reports", v1.GetAuditPlanReports) - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/", v1.GetAuditPlanReport) - - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/sqls", v1.GetAuditPlanSQLs) - v1Router.POST("/projects/:project_name/audit_plans/:audit_plan_name/sqls/full", v1.FullSyncAuditPlanSQLs, sqleMiddleware.ScannerVerifier()) - v2Router.POST("/projects/:project_name/audit_plans/:audit_plan_name/sqls/full", v2.FullSyncAuditPlanSQLs, sqleMiddleware.ScannerVerifier()) - v1Router.POST("/projects/:project_name/audit_plans/:audit_plan_name/sqls/partial", v1.PartialSyncAuditPlanSQLs, sqleMiddleware.ScannerVerifier()) - v2Router.POST("/projects/:project_name/audit_plans/:audit_plan_name/sqls/partial", v2.PartialSyncAuditPlanSQLs, sqleMiddleware.ScannerVerifier()) - v1Router.POST("/projects/:project_name/audit_plans/:audit_plan_name/trigger", v1.TriggerAuditPlan) - v1Router.PATCH("/projects/:project_name/audit_plans/:audit_plan_name/notify_config", v1.UpdateAuditPlanNotifyConfig) - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/notify_config", v1.GetAuditPlanNotifyConfig) - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/notify_config/test", v1.TestAuditPlanNotifyConfig) - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/sqls/:number/analysis", v1.GetAuditPlanAnalysisData) - v2Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/sqls/:number/analysis", v2.GetAuditPlanAnalysisData) - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/sqls", v1.GetAuditPlanReportSQLsV1) - v2Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/sqls", v2.GetAuditPlanReportSQLs) - v1Router.GET("/projects/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/export", v1.ExportAuditPlanReportV1) - - // sql manager - v1Router.GET("/projects/:project_name/sql_manages", v1.GetSqlManageList) - v2Router.GET("/projects/:project_name/sql_manages", v2.GetSqlManageList) - v1Router.PATCH("/projects/:project_name/sql_manages/batch", v1.BatchUpdateSqlManage) - v1Router.GET("/projects/:project_name/sql_manages/exports", v1.ExportSqlManagesV1) - v1Router.GET("/projects/:project_name/sql_manages/rule_tips", v1.GetSqlManageRuleTips) - v1Router.GET("/projects/:project_name/sql_manages/:sql_manage_id/sql_analysis", v1.GetSqlManageSqlAnalysisV1) - - // sql audit record - v1Router.POST("/projects/:project_name/sql_audit_records", v1.CreateSQLAuditRecord) - v1Router.GET("/projects/:project_name/sql_audit_records", v1.GetSQLAuditRecordsV1) - v1Router.GET("/projects/:project_name/sql_audit_records/:sql_audit_record_id/", v1.GetSQLAuditRecordV1) - v1Router.PATCH("/projects/:project_name/sql_audit_records/:sql_audit_record_id/", v1.UpdateSQLAuditRecordV1) - v1Router.GET("/projects/:project_name/sql_audit_records/tag_tips", v1.GetSQLAuditRecordTagTipsV1) - - // 企业公告 - v1Router.GET("/company_notice", v1.GetCompanyNotice) - - // sql query - if err := cloudbeaver_wrapper.StartApp(e); err != nil { - log.Logger().Errorf("CloudBeaver wrapper configuration failed: %v", err) - } else { - log.Logger().Info("CloudBeaver wrapper is configured") + // project admin router + v1ProjectAdminRouter := v1Router.Group("/projects", sqleMiddleware.ProjectAdminUserAllowed()) + { + // audit whitelist + v1ProjectAdminRouter.POST("/:project_name/audit_whitelist", v1.CreateAuditWhitelist) + v1ProjectAdminRouter.PATCH("/:project_name/audit_whitelist/:audit_whitelist_id/", v1.UpdateAuditWhitelistById) + v1ProjectAdminRouter.DELETE("/:project_name/audit_whitelist/:audit_whitelist_id/", v1.DeleteAuditWhitelistById) + + // rule template + v1ProjectAdminRouter.POST("/:project_name/rule_templates", v1.CreateProjectRuleTemplate) + v1ProjectAdminRouter.PATCH("/:project_name/rule_templates/:rule_template_name/", v1.UpdateProjectRuleTemplate) + v1ProjectAdminRouter.DELETE("/:project_name/rule_templates/:rule_template_name/", v1.DeleteProjectRuleTemplate) + v1ProjectAdminRouter.POST("/:project_name/rule_templates/:rule_template_name/clone", v1.CloneProjectRuleTemplate) + + // workflow template + v1ProjectAdminRouter.PATCH("/:project_name/workflow_template", v1.UpdateWorkflowTemplate) + } + + // project member router + v1ProjectRouter := v1Router.Group("/projects", sqleMiddleware.ProjectMemberAllowed()) + { + // statistic + v1ProjectRouter.GET("/:project_name/statistics", v1.GetProjectStatisticsV1) + v1ProjectRouter.GET("/:project_name/statistics", v1.GetProjectStatisticsV1) + v1ProjectRouter.GET("/:project_name/statistic/workflow_status", v1.StatisticWorkflowStatusV1) + v1ProjectRouter.GET("/:project_name/statistic/risk_workflow", v1.StatisticRiskWorkflowV1) + v1ProjectRouter.GET("/:project_name/statistic/audit_plans", v1.StatisticAuditPlanV1) + v1ProjectRouter.GET("/:project_name/statistic/risk_audit_plans", v1.GetRiskAuditPlanV1) + v1ProjectRouter.GET("/:project_name/statistic/role_user", v1.GetRoleUserCountV1) + v1ProjectRouter.GET("/:project_name/statistic/project_score", v1.GetProjectScoreV1) + v1ProjectRouter.GET("/:project_name/statistic/instance_health", v1.GetInstanceHealthV1) + v1ProjectRouter.GET("/:project_name/statistic/audited_sqls", v1.StatisticsAuditedSQLV1) + + // audit whitelist + v1ProjectRouter.GET("/:project_name/audit_whitelist", v1.GetSqlWhitelist) + + // instance + v1ProjectRouter.GET("/:project_name/instances/:instance_name/connection", v1.CheckInstanceIsConnectableByName) + v1ProjectRouter.POST("/:project_name/instances/connections", v1.BatchCheckInstanceConnections) + v1ProjectRouter.GET("/:project_name/instances/:instance_name/schemas", v1.GetInstanceSchemas) + v1ProjectRouter.GET("/:project_name/instance_tips", v1.GetInstanceTips) + v1ProjectRouter.GET("/:project_name/instances/:instance_name/rules", v1.GetInstanceRules) + v1ProjectRouter.GET("/:project_name/instances/:instance_name/schemas/:schema_name/tables", v1.ListTableBySchema) + v1ProjectRouter.GET("/:project_name/instances/:instance_name/schemas/:schema_name/tables/:table_name/metadata", v1.GetTableMetadata) + + // rule template + v1ProjectRouter.GET("/:project_name/rule_templates/:rule_template_name/", v1.GetProjectRuleTemplate) + v1ProjectRouter.GET("/:project_name/rule_templates", v1.GetProjectRuleTemplates) + v1ProjectRouter.GET("/:project_name/rule_template_tips", v1.GetProjectRuleTemplateTips) + v1ProjectRouter.GET("/:project_name/rule_templates/:rule_template_name/export", v1.ExportProjectRuleTemplateFile) + + // workflow template + v1ProjectRouter.GET("/:project_name/workflow_template", v1.GetWorkflowTemplate) + + // workflow + v1ProjectRouter.POST("/:project_name/workflows", DeprecatedBy(apiV2)) + v1ProjectRouter.GET("/:project_name/workflows/:workflow_name/", DeprecatedBy(apiV2)) + v1ProjectRouter.GET("/:project_name/workflows", v1.GetWorkflowsV1) + v1ProjectRouter.POST("/:project_name/workflows/:workflow_name/steps/:workflow_step_id/approve", DeprecatedBy(apiV2)) + v1ProjectRouter.POST("/:project_name/workflows/:workflow_name/steps/:workflow_step_id/reject", DeprecatedBy(apiV2)) + v1ProjectRouter.POST("/:project_name/workflows/:workflow_name/cancel", DeprecatedBy(apiV2)) + v1ProjectRouter.POST("/:project_name/workflows/cancel", DeprecatedBy(apiV2)) + v1ProjectRouter.POST("/:project_name/workflows/complete", DeprecatedBy(apiV2)) + v1ProjectRouter.POST("/:project_name/workflows/:workflow_name/tasks/:task_id/execute", DeprecatedBy(apiV2)) + v1ProjectRouter.POST("/:project_name/workflows/:workflow_id/tasks/:task_id/terminate", v1.TerminateSingleTaskByWorkflowV1) + v1ProjectRouter.GET("/:project_name/workflows/:workflow_name/tasks", DeprecatedBy(apiV2)) + v1ProjectRouter.POST("/:project_name/workflows/:workflow_name/tasks/execute", DeprecatedBy(apiV2)) + v1ProjectRouter.POST("/:project_name/workflows/:workflow_id/tasks/terminate", v1.TerminateMultipleTaskByWorkflowV1) + v1ProjectRouter.PUT("/:project_name/workflows/:workflow_name/tasks/:task_id/schedule", DeprecatedBy(apiV2)) + v1ProjectRouter.PATCH("/:project_name/workflows/:workflow_name/", DeprecatedBy(apiV2)) + v1ProjectRouter.GET("/:project_name/workflows/exports", v1.ExportWorkflowV1) + + // audit plan; 智能扫描任务 + v1ProjectRouter.POST("/:project_name/audit_plans", v1.CreateAuditPlan) + v1ProjectRouter.GET("/:project_name/audit_plans", v1.GetAuditPlans) + v1ProjectRouter.DELETE("/:project_name/audit_plans/:audit_plan_name/", v1.DeleteAuditPlan) + v1ProjectRouter.PATCH("/:project_name/audit_plans/:audit_plan_name/", v1.UpdateAuditPlan) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/", v1.GetAuditPlan) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/reports", v1.GetAuditPlanReports) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/", v1.GetAuditPlanReport) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/sqls", v1.GetAuditPlanSQLs) + v1ProjectRouter.POST("/:project_name/audit_plans/:audit_plan_name/trigger", v1.TriggerAuditPlan) + v1ProjectRouter.PATCH("/:project_name/audit_plans/:audit_plan_name/notify_config", v1.UpdateAuditPlanNotifyConfig) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/notify_config", v1.GetAuditPlanNotifyConfig) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/notify_config/test", v1.TestAuditPlanNotifyConfig) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/sqls/:number/analysis", v1.GetAuditPlanAnalysisData) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/sqls", v1.GetAuditPlanReportSQLsV1) + v1ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/export", v1.ExportAuditPlanReportV1) + + // scanner token auth + v1ProjectRouter.POST("/:project_name/audit_plans/:audit_plan_name/sqls/full", v1.FullSyncAuditPlanSQLs, sqleMiddleware.ScannerVerifier()) + v1ProjectRouter.POST("/:project_name/audit_plans/:audit_plan_name/sqls/partial", v1.PartialSyncAuditPlanSQLs, sqleMiddleware.ScannerVerifier()) + + // sql manager + v1ProjectRouter.GET("/:project_name/sql_manages", v1.GetSqlManageList) + v1ProjectRouter.PATCH("/:project_name/sql_manages/batch", v1.BatchUpdateSqlManage) + v1ProjectRouter.GET("/:project_name/sql_manages/exports", v1.ExportSqlManagesV1) + v1ProjectRouter.GET("/:project_name/sql_manages/rule_tips", v1.GetSqlManageRuleTips) + v1ProjectRouter.GET("/:project_name/sql_manages/:sql_manage_id/sql_analysis", v1.GetSqlManageSqlAnalysisV1) + + // sql audit record + v1ProjectRouter.POST("/:project_name/sql_audit_records", v1.CreateSQLAuditRecord) + v1ProjectRouter.GET("/:project_name/sql_audit_records", v1.GetSQLAuditRecordsV1) + v1ProjectRouter.GET("/:project_name/sql_audit_records/:sql_audit_record_id/", v1.GetSQLAuditRecordV1) + v1ProjectRouter.PATCH("/:project_name/sql_audit_records/:sql_audit_record_id/", v1.UpdateSQLAuditRecordV1) + v1ProjectRouter.GET("/:project_name/sql_audit_records/tag_tips", v1.GetSQLAuditRecordTagTipsV1) + + // task + v1ProjectRouter.POST("/:project_name/tasks/audits", v1.CreateAndAuditTask) } - // sql audit - v1Router.POST("/sql_audit", v1.DirectAudit) - v1Router.POST("/audit_files", v1.DirectAuditFiles) - v2Router.POST("/audit_files", v2.DirectAuditFiles) - v1Router.GET("/sql_analysis", v1.DirectGetSQLAnalysis) + // project member router + v2ProjectRouter := v2Router.Group("/projects", sqleMiddleware.ProjectMemberAllowed()) + { + // workflow + v2ProjectRouter.POST("/:project_name/workflows", v2.CreateWorkflowV2) + v2ProjectRouter.GET("/:project_name/workflows/:workflow_id/", v2.GetWorkflowV2) + v2ProjectRouter.POST("/:project_name/workflows/:workflow_id/steps/:workflow_step_id/approve", v2.ApproveWorkflowV2) + v2ProjectRouter.POST("/:project_name/workflows/:workflow_id/steps/:workflow_step_id/reject", v2.RejectWorkflowV2) + v2ProjectRouter.POST("/:project_name/workflows/:workflow_id/cancel", v2.CancelWorkflowV2) + v2ProjectRouter.POST("/:project_name/workflows/cancel", v2.BatchCancelWorkflowsV2) + v2ProjectRouter.POST("/:project_name/workflows/complete", v2.BatchCompleteWorkflowsV2) + v2ProjectRouter.POST("/:project_name/workflows/:workflow_id/tasks/:task_id/execute", v2.ExecuteOneTaskOnWorkflowV2) + v2ProjectRouter.GET("/:project_name/workflows/:workflow_id/tasks", v2.GetSummaryOfWorkflowTasksV2) + v2ProjectRouter.POST("/:project_name/workflows/:workflow_id/tasks/execute", v2.ExecuteTasksOnWorkflowV2) + v2ProjectRouter.PUT("/:project_name/workflows/:workflow_id/tasks/:task_id/schedule", v2.UpdateWorkflowScheduleV2) + v2ProjectRouter.PATCH("/:project_name/workflows/:workflow_id/", v2.UpdateWorkflowV2) + + // instance + v2ProjectRouter.GET("/:project_name/instances/:instance_name/", v2.GetInstance) + // audit plan; 智能扫描任务 + v2ProjectRouter.GET("/:project_name/audit_plans", v2.GetAuditPlans) + v2ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/sqls/:number/analysis", v2.GetAuditPlanAnalysisData) + v2ProjectRouter.GET("/:project_name/audit_plans/:audit_plan_name/reports/:audit_plan_report_id/sqls", v2.GetAuditPlanReportSQLs) + // sql managers + v2ProjectRouter.GET("/:project_name/sql_manages", v2.GetSqlManageList) + + // scanner token auth + v2ProjectRouter.POST("/:project_name/audit_plans/:audit_plan_name/sqls/full", v2.FullSyncAuditPlanSQLs, sqleMiddleware.ScannerVerifier()) + v2ProjectRouter.POST("/:project_name/audit_plans/:audit_plan_name/sqls/partial", v2.PartialSyncAuditPlanSQLs, sqleMiddleware.ScannerVerifier()) + + } + + { + v1Router.GET("/user_tips", v1.GetUserTips) + + // 全局 rule template + v1Router.GET("/rule_templates", v1.GetRuleTemplates) + v1Router.GET("/rule_template_tips", v1.GetRuleTemplateTips) + v1Router.GET("/rule_templates/:rule_template_name/", v1.GetRuleTemplate) + + v1Router.POST("/rule_templates/parse", v1.ParseProjectRuleTemplateFile) + + // 全局 workflow + v1Router.GET("/workflows", v1.GetGlobalWorkflowsV1) + v1Router.GET("/rule_knowledge/db_types/:db_type/rules/:rule_name/", v1.GetRuleKnowledge) + v1Router.GET("/rule_knowledge/db_types/:db_type/custom_rules/:rule_name/", v1.GetCustomRuleKnowledge) + + //rule + v1Router.GET("/rules", v1.GetRules) + v1Router.GET("/custom_rules", v1.GetCustomRules) + v1Router.GET("/custom_rules/:rule_id", v1.GetCustomRule) + v1Router.GET("/custom_rules/:db_type/rule_types", v1.GetRuleTypeByDBType) + + // task + v1Router.GET("/tasks/audits/:task_id/", v1.GetTask) + v1Router.GET("/tasks/audits/:task_id/sqls", v1.GetTaskSQLs) + v2Router.GET("/tasks/audits/:task_id/sqls", v2.GetTaskSQLs) + v1Router.GET("/tasks/audits/:task_id/sql_report", v1.DownloadTaskSQLReportFile) + v1Router.GET("/tasks/audits/:task_id/sql_file", v1.DownloadTaskSQLFile) + v1Router.GET("/tasks/audits/:task_id/sql_content", v1.GetAuditTaskSQLContent) + v1Router.PATCH("/tasks/audits/:task_id/sqls/:number", v1.UpdateAuditTaskSQLs) + v1Router.GET("/tasks/audits/:task_id/sqls/:number/analysis", v1.GetTaskAnalysisData) + v2Router.GET("/tasks/audits/:task_id/sqls/:number/analysis", v2.GetTaskAnalysisData) + v1Router.POST("/projects/:project_name/task_groups", v1.CreateAuditTasksGroupV1) + v1Router.POST("/task_groups/audit", v1.AuditTaskGroupV1) + + // dashboard + v1Router.GET("/dashboard", v1.Dashboard) + + // configurations + v1Router.GET("/configurations/drivers", v1.GetDrivers) + v2Router.GET("/configurations/drivers", v2.GetDrivers) + + // audit plan + v1Router.GET("/audit_plan_metas", v1.GetAuditPlanMetas) + v1Router.GET("/audit_plan_types", v1.GetAuditPlanTypes) + + // sql audit + v1Router.POST("/sql_audit", v1.DirectAudit) + v2Router.POST("/sql_audit", v2.DirectAudit) + v1Router.POST("/audit_files", v1.DirectAuditFiles) + v2Router.POST("/audit_files", v2.DirectAuditFiles) + v1Router.GET("/sql_analysis", v1.DirectGetSQLAnalysis) + // 企业公告 + v1Router.GET("/company_notice", v1.GetCompanyNotice) + } // enterprise customized apis err := addCustomApis(v1Router, restApis) @@ -451,7 +369,7 @@ func StartApi(net *gracenet.Net, exitChan chan struct{}, config config.SqleConfi return c.File("ui/index.html") }) - address := fmt.Sprintf(":%v", config.SqleServerPort) + address := fmt.Sprintf(":%v", config.APIServiceOpts.Port) log.Logger().Infof("starting http server on %s", address) // start http server @@ -460,16 +378,17 @@ func StartApi(net *gracenet.Net, exitChan chan struct{}, config config.SqleConfi log.Logger().Fatal(err) return } - if config.EnableHttps { + + if config.APIServiceOpts.EnableHttps { // Usually, it is easier to create an tls server using echo#StartTLS; // but I need create a graceful listener. - if config.CertFilePath == "" || config.KeyFilePath == "" { + if config.APIServiceOpts.CertFilePath == "" || config.APIServiceOpts.KeyFilePath == "" { log.Logger().Fatal("invalid tls configuration") return } tlsConfig := new(tls.Config) tlsConfig.Certificates = make([]tls.Certificate, 1) - tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(config.CertFilePath, config.KeyFilePath) + tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(config.APIServiceOpts.CertFilePath, config.APIServiceOpts.KeyFilePath) if err != nil { log.Logger().Fatal("load x509 key pair failed, error:", err) return @@ -484,18 +403,6 @@ func StartApi(net *gracenet.Net, exitChan chan struct{}, config config.SqleConfi } } -// AdminUserAllowed is a `echo` middleware, only allow admin user to access next. -func AdminUserAllowed() echo.MiddlewareFunc { - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if controller.GetUserName(c) == model.DefaultAdminUser { - return next(c) - } - return echo.NewHTTPError(http.StatusForbidden) - } - } -} - // DeprecatedBy is a controller used to mark deprecated and used to replace the original controller. func DeprecatedBy(version string) func(echo.Context) error { return func(ctx echo.Context) error { diff --git a/sqle/api/cloudbeaver_wrapper/app.go b/sqle/api/cloudbeaver_wrapper/app.go deleted file mode 100644 index f793122e4b..0000000000 --- a/sqle/api/cloudbeaver_wrapper/app.go +++ /dev/null @@ -1,347 +0,0 @@ -package cloudbeaver_wrapper - -import ( - "bufio" - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "path" - "strconv" - "sync" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/controller" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/resolver" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/service" - "github.com/actiontech/sqle/sqle/log" - sqleModel "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/utils" - - "github.com/99designs/gqlgen/graphql" - "github.com/99designs/gqlgen/graphql/executor" - "github.com/labstack/echo/v4" - "github.com/labstack/echo/v4/middleware" -) - -type gqlBehavior struct { - useLocalHandler bool - needModifyRemoteRes bool - disable bool - // 预处理主要用于在真正使用前处理前端传递的参数, 比如需要接收int, 但收到float, 则可以在此处调整参数类型 - preprocessing func(ctx echo.Context, params *graphql.RawParams) error -} - -var gqlHandlerRouters = map[string] /* gql operation name */ gqlBehavior{ - "asyncSqlExecuteQuery": { - useLocalHandler: true, - needModifyRemoteRes: false, - preprocessing: func(ctx echo.Context, params *graphql.RawParams) (err error) { - // json中没有int类型, 这将导致执行json.Unmarshal()时int会被当作float64, 从而导致后面出现类型错误的异常 - if filter, ok := params.Variables["filter"].(map[string]interface{}); ok { - if filter["limit"] != nil { - params.Variables["filter"].(map[string]interface{})["limit"], err = strconv.Atoi(fmt.Sprintf("%v", params.Variables["filter"].(map[string]interface{})["limit"])) - } - } - return err - }, - }, - "getActiveUser": { - useLocalHandler: true, - needModifyRemoteRes: true, - }, "authLogout": { - disable: true, - }, "authLogin": { - disable: true, - }, "configureServer": { - disable: true, - }, "createUser": { - disable: true, - }, "setUserCredentials": { - disable: true, - }, "enableUser": { - disable: true, - }, "grantUserRole": { - disable: true, - }, "setConnections": { - disable: true, - }, "saveUserMetaParameters": { - disable: true, - }, "deleteUser": { - disable: true, - }, "createRole": { - disable: true, - }, "updateRole": { - disable: true, - }, "deleteRole": { - disable: true, - }, "authChangeLocalPassword": { - disable: true, - }, -} - -func StartApp(e *echo.Echo) error { - if !service.IsCloudBeaverConfigured() { - return nil - } - cfg := service.GetSQLQueryConfig() - protocol := "http" - if cfg.EnableHttps { - protocol = "https" - } - url2, err := url.Parse(fmt.Sprintf("%v://%v:%v", protocol, cfg.CloudBeaverHost, cfg.CloudBeaverPort)) - if err != nil { - return err - } - targets := []*middleware.ProxyTarget{ - { - URL: url2, - }, - } - - err = service.InitGQLVersion() - if err != nil { - return err - } - - q := e.Group(service.CbRootUri) - - q.Use(TriggerLogin()) - q.Use(GraphqlDistributor()) - q.Use(middleware.ProxyWithConfig(middleware.ProxyConfig{ - Skipper: middleware.DefaultSkipper, - Balancer: middleware.NewRandomBalancer(targets), - })) - - return nil -} - -var ( - sqleTokenToCBSessionId = make(map[string]string) - tokenMapMutex = &sync.Mutex{} -) - -func getCBSessionIdBySqleToken(token string) string { - tokenMapMutex.Lock() - defer tokenMapMutex.Unlock() - return sqleTokenToCBSessionId[token] -} - -func setCBSessionIdBySqleToken(token, cbSessionId string) { - tokenMapMutex.Lock() - defer tokenMapMutex.Unlock() - sqleTokenToCBSessionId[token] = cbSessionId -} - -func UnbindCBSessionIdBySqleToken(token string) { - tokenMapMutex.Lock() - defer tokenMapMutex.Unlock() - delete(sqleTokenToCBSessionId, token) -} - -// 如果当前用户没有登录cloudbeaver,则登录 -func TriggerLogin() echo.MiddlewareFunc { - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - var sqleToken string - // 根据cookie中的sqle-token查找对应用户的cb-session-id - for _, c := range c.Cookies() { - if c.Name == "sqle-token" { - sqleToken = c.Value - break - } - } - if sqleToken == "" { - // 没有找到sqle-token,有可能是用户直接通过url访问cb页面,但没有登录sqle - return c.Redirect(http.StatusFound, "/login?target=/sqlQuery") - } - l := log.NewEntry().WithField("action", "trigger cloudbeaver login") - CBSessionId := getCBSessionIdBySqleToken(sqleToken) - if CBSessionId != "" { - c.Request().Header.Set("Cookie", "cb-session-id="+CBSessionId) - // 判断是否访问cb数据接口,在访问前发送测试请求验证session id是否过期 - if c.Request().RequestURI == "/sql_query/api/gql" { - activeUser, err := service.GetActiveUserQuery(c.Cookies()) - if err != nil { - l.Errorf("get active user failed: %v", err) - return err - } - if activeUser.User == nil { - goto LoginCb - } - } - c.Request().Header.Set("Cookie", "cb-session-id="+CBSessionId) - return next(c) - } - LoginCb: - // CBSessionId不存在认为当前用户没有登录cb,登录cb - userName, err := utils.GetUserNameFromJWTToken(sqleToken) - if err != nil { - l.Errorf("get user name from token failed: %v", err) - return errors.New("get user name to login failed") - } - s := sqleModel.GetStorage() - user, _, err := s.GetUserByName(userName) - if err != nil { - l.Errorf("get user info err: %v", err) - return err - } - - cbUser := service.GenerateCloudBeaverUserName(userName) - // 同步信息 - if err = service.SyncCurrentUser(cbUser); err != nil { - l.Errorf("sync cloudbeaver user %v info failed: %v", cbUser, err) - } - err = service.SyncUserBindInstance(cbUser) - if err != nil { - l.Errorf("sync cloudbeaver user %v bind instance failed: %v", cbUser, err) - } - cookies, err := service.LoginToCBServer(cbUser, user.Password) - if err != nil { - l.Errorf("login to cloudbeaver failed: %v", err) - return err - } - - // 添加sqle和cb的用户映射 - for _, ck := range cookies { - if ck.Name == "cb-session-id" { - setCBSessionIdBySqleToken(sqleToken, ck.Value) - CBSessionId = ck.Value - } - } - c.Request().Header.Set("Cookie", "cb-session-id="+CBSessionId) - return next(c) - } - } -} - -func GraphqlDistributor() echo.MiddlewareFunc { - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if c.Request().RequestURI != path.Join(service.CbRootUri, service.CbGqlApi) { - return next(c) - } - // copy request body - reqBody := []byte{} - if c.Request().Body != nil { // Read - reqBody, _ = ioutil.ReadAll(c.Request().Body) - } - c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(reqBody)) // Reset - - var params *graphql.RawParams - err := json.Unmarshal(reqBody, ¶ms) - if err != nil { - fmt.Println(err) - return err - } - - bh, ok := gqlHandlerRouters[params.OperationName] - if !ok { - return next(c) - } - - if bh.disable { - errMsg := "this feature is prohibited" - fmt.Printf("%v:%v", errMsg, params.OperationName) - return c.JSON(http.StatusOK, model.ServerError{ - Message: &errMsg, - }) - } - - if bh.preprocessing != nil { - err = bh.preprocessing(c, params) - if err != nil { - fmt.Println(err) - return err - } - } - - if bh.useLocalHandler { - params.ReadTime = graphql.TraceTiming{ - Start: graphql.Now(), - End: graphql.Now(), - } - ctx := graphql.StartOperationTrace(context.TODO()) - params.Headers = c.Request().Header.Clone() - - var n controller.Next - var resWrite *responseProcessWriter - if !bh.needModifyRemoteRes { - n = func(c echo.Context) ([]byte, error) { - return nil, next(c) - } - } else { - n = func(c echo.Context) ([]byte, error) { - resWrite = &responseProcessWriter{tmp: &bytes.Buffer{}, ResponseWriter: c.Response().Writer} - c.Response().Writer = resWrite - err := next(c) - if err != nil { - return nil, err - } - return resWrite.tmp.Bytes(), nil - } - } - - g := resolver.NewExecutableSchema(resolver.Config{ - Resolvers: &controller.ResolverImpl{ - Ctx: c, - Next: n, - }, - }) - - exec := executor.New(g) - - rc, err := exec.CreateOperationContext(ctx, params) - if err != nil { - return err - } - responses, ctx := exec.DispatchOperation(ctx, rc) - - res := responses(ctx) - if res.Errors.Error() != "" { - return res.Errors - } - if !bh.needModifyRemoteRes { - return nil - } else { - header := resWrite.ResponseWriter.Header() - b, err := json.Marshal(res) - if err != nil { - return err - } - header.Set("Content-Length", fmt.Sprintf("%d", len(b))) - _, err = resWrite.ResponseWriter.Write(b) - return err - } - } - return next(c) - } - } -} - -type responseProcessWriter struct { - tmp *bytes.Buffer - headerCode int - http.ResponseWriter -} - -func (w *responseProcessWriter) WriteHeader(code int) { - w.headerCode = code -} - -func (w *responseProcessWriter) Write(b []byte) (int, error) { - return w.tmp.Write(b) -} - -func (w *responseProcessWriter) Flush() { - w.ResponseWriter.(http.Flusher).Flush() -} - -func (w *responseProcessWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - return w.ResponseWriter.(http.Hijacker).Hijack() -} diff --git a/sqle/api/cloudbeaver_wrapper/controller/audit.go b/sqle/api/cloudbeaver_wrapper/controller/audit.go deleted file mode 100644 index 7e997d57ad..0000000000 --- a/sqle/api/cloudbeaver_wrapper/controller/audit.go +++ /dev/null @@ -1,47 +0,0 @@ -package controller - -import ( - "context" - "fmt" - "net/http" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/service" -) - -func (r *MutationResolverImpl) AsyncSQLExecuteQuery(ctx context.Context, projectID *string, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat, readLogs *bool) (*model.AsyncTaskInfo, error) { - success, result, err := service.AuditSQL(sql, connectionID) - if err != nil { - return nil, err - } - if !success { - name := "SQL Audit Failed" - msg := fmt.Sprintf("[SQLE] sql statements are not allowed to excute, caused by: \nthe highest error level in audit results is %v, which reaches the error level limit (%v) set in SQLE.", result.AuditLevel, result.LimitLevel) - return nil, r.Ctx.JSON(http.StatusOK, struct { - Data struct { - TaskInfo model.AsyncTaskInfo `json:"taskInfo"` - } `json:"data"` - }{ - struct { - TaskInfo model.AsyncTaskInfo `json:"taskInfo"` - }{ - TaskInfo: model.AsyncTaskInfo{ - Name: &name, - Running: false, - Status: &sql, - Error: &model.ServerError{ - Message: &msg, - StackTrace: &result.Result, - }, - }, - }, - }) - } - - _, err = r.Next(r.Ctx) - if err != nil { - return nil, err - } - - return nil, err -} diff --git a/sqle/api/cloudbeaver_wrapper/controller/base.go b/sqle/api/cloudbeaver_wrapper/controller/base.go deleted file mode 100644 index b86d702633..0000000000 --- a/sqle/api/cloudbeaver_wrapper/controller/base.go +++ /dev/null @@ -1,42 +0,0 @@ -package controller - -import ( - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/resolver" - - "github.com/labstack/echo/v4" -) - -type Next func(c echo.Context) ([]byte, error) - -type ResolverImpl struct { - *resolver.Resolver - Ctx echo.Context - Next Next -} - -func (r *ResolverImpl) Mutation() resolver.MutationResolver { - return &MutationResolverImpl{ - Ctx: r.Ctx, - Next: r.Next, - } -} - -// Query returns generated.QueryResolver implementation. -func (r *ResolverImpl) Query() resolver.QueryResolver { - return &QueryResolverImpl{ - Ctx: r.Ctx, - Next: r.Next, - } -} - -type MutationResolverImpl struct { - *resolver.MutationResolverImpl - Ctx echo.Context - Next Next -} - -type QueryResolverImpl struct { - *resolver.QueryResolverImpl - Ctx echo.Context - Next Next -} diff --git a/sqle/api/cloudbeaver_wrapper/controller/login.go b/sqle/api/cloudbeaver_wrapper/controller/login.go deleted file mode 100644 index 8878864787..0000000000 --- a/sqle/api/cloudbeaver_wrapper/controller/login.go +++ /dev/null @@ -1,34 +0,0 @@ -package controller - -import ( - "context" - "encoding/json" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/service" -) - -// ActiveUser is the resolver for the activeUser field. -func (r *QueryResolverImpl) ActiveUser(ctx context.Context) (*model.UserInfo, error) { - data, err := r.Next(r.Ctx) - if err != nil { - return nil, err - } - - resp := &struct { - Data struct { - User *model.UserInfo `json:"user"` - } `json:"data"` - }{} - - err = json.Unmarshal(data, resp) - if err != nil { - return nil, err - } - - if resp.Data.User != nil && resp.Data.User.DisplayName != nil { - *resp.Data.User.DisplayName = service.RestoreFromCloudBeaverUserName(*resp.Data.User.DisplayName) - } - - return resp.Data.User, err -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/client/client.go b/sqle/api/cloudbeaver_wrapper/graph/client/client.go deleted file mode 100644 index 5eacc178dc..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/client/client.go +++ /dev/null @@ -1,332 +0,0 @@ -package client - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "mime/multipart" - "net/http" - - "github.com/pkg/errors" -) - -// Client is a client for interacting with a GraphQL API. -type Client struct { - endpoint string - httpClient *http.Client - useMultipartForm bool - - cookies []*http.Cookie - - // closeReq will close the request body immediately allowing for reuse of client - closeReq bool - - // Log is called with various debug information. - // To log to standard out, use: - // client.Log = func(s string) { log.Println(s) } - Log func(s string) - - HttpResHandler func(res *http.Response) -} - -// NewClient makes a new Client capable of making GraphQL requests. -func NewClient(endpoint string, opts ...ClientOption) *Client { - c := &Client{ - endpoint: endpoint, - Log: func(string) {}, - } - for _, optionFunc := range opts { - optionFunc(c) - } - if c.httpClient == nil { - c.httpClient = http.DefaultClient - } - return c -} - -func (c *Client) logf(format string, args ...interface{}) { - c.Log(fmt.Sprintf(format, args...)) -} - -// Run executes the query and unmarshals the response from the data field -// into the response object. -// Pass in a nil response object to skip response parsing. -// If the request fails or the server returns an error, the first error -// will be returned. -func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error { - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - if len(req.files) > 0 && !c.useMultipartForm { - return errors.New("cannot send files with PostFields option") - } - if c.useMultipartForm { - return c.runWithPostFields(ctx, req, resp) - } - return c.runWithJSON(ctx, req, resp) -} - -func (c *Client) runWithJSON(ctx context.Context, req *Request, resp interface{}) error { - var requestBody bytes.Buffer - requestBodyObj := struct { - Query string `json:"query"` - Variables map[string]interface{} `json:"variables"` - OperationName string `json:"operationName"` - }{ - Query: req.q, - Variables: req.vars, - } - if req.operationName != "" { - requestBodyObj.OperationName = req.operationName - } - if err := json.NewEncoder(&requestBody).Encode(requestBodyObj); err != nil { - return errors.Wrap(err, "encode body") - } - c.logf(">> variables: %v", req.vars) - c.logf(">> query: %s", req.q) - gr := &graphResponse{ - Data: resp, - } - r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody) - if err != nil { - return err - } - r.Close = c.closeReq - r.Header.Set("Content-Type", "application/json; charset=utf-8") - r.Header.Set("Accept", "application/json; charset=utf-8") - for _, cookie := range c.cookies { - r.AddCookie(cookie) - } - for key, values := range req.Header { - for _, value := range values { - r.Header.Add(key, value) - } - } - c.logf(">> headers: %v", r.Header) - r = r.WithContext(ctx) - res, err := c.httpClient.Do(r) - if err != nil { - return err - } - if c.HttpResHandler != nil { - c.HttpResHandler(res) - } - - defer res.Body.Close() - var buf bytes.Buffer - if _, err := io.Copy(&buf, res.Body); err != nil { - return errors.Wrap(err, "reading body") - } - c.logf("<< %s", buf.String()) - if err := json.NewDecoder(&buf).Decode(&gr); err != nil { - if res.StatusCode != http.StatusOK { - return fmt.Errorf("graphql: server returned a non-200 status code: %v", res.StatusCode) - } - return errors.Wrap(err, "decoding response") - } - if len(gr.Errors) > 0 { - // return first error - return gr.Errors[0] - } - return nil -} - -func (c *Client) runWithPostFields(ctx context.Context, req *Request, resp interface{}) error { - var requestBody bytes.Buffer - writer := multipart.NewWriter(&requestBody) - if err := writer.WriteField("query", req.q); err != nil { - return errors.Wrap(err, "write query field") - } - var variablesBuf bytes.Buffer - if len(req.vars) > 0 { - variablesField, err := writer.CreateFormField("variables") - if err != nil { - return errors.Wrap(err, "create variables field") - } - if err := json.NewEncoder(io.MultiWriter(variablesField, &variablesBuf)).Encode(req.vars); err != nil { - return errors.Wrap(err, "encode variables") - } - } - for i := range req.files { - part, err := writer.CreateFormFile(req.files[i].Field, req.files[i].Name) - if err != nil { - return errors.Wrap(err, "create form file") - } - if _, err := io.Copy(part, req.files[i].R); err != nil { - return errors.Wrap(err, "preparing file") - } - } - if err := writer.Close(); err != nil { - return errors.Wrap(err, "close writer") - } - c.logf(">> variables: %s", variablesBuf.String()) - c.logf(">> files: %d", len(req.files)) - c.logf(">> query: %s", req.q) - gr := &graphResponse{ - Data: resp, - } - r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody) - if err != nil { - return err - } - r.Close = c.closeReq - r.Header.Set("Content-Type", writer.FormDataContentType()) - r.Header.Set("Accept", "application/json; charset=utf-8") - for _, cookie := range c.cookies { - r.AddCookie(cookie) - } - for key, values := range req.Header { - for _, value := range values { - r.Header.Add(key, value) - } - } - c.logf(">> headers: %v", r.Header) - r = r.WithContext(ctx) - res, err := c.httpClient.Do(r) - if err != nil { - return err - } - defer res.Body.Close() - var buf bytes.Buffer - if _, err := io.Copy(&buf, res.Body); err != nil { - return errors.Wrap(err, "reading body") - } - c.logf("<< %s", buf.String()) - if err := json.NewDecoder(&buf).Decode(&gr); err != nil { - if res.StatusCode != http.StatusOK { - return fmt.Errorf("graphql: server returned a non-200 status code: %v", res.StatusCode) - } - return errors.Wrap(err, "decoding response") - } - if len(gr.Errors) > 0 { - // return first error - return gr.Errors[0] - } - return nil -} - -// WithHTTPClient specifies the underlying http.Client to use when -// making requests. -// NewClient(endpoint, WithHTTPClient(specificHTTPClient)) -func WithHTTPClient(httpclient *http.Client) ClientOption { - return func(client *Client) { - client.httpClient = httpclient - } -} - -// UseMultipartForm uses multipart/form-data and activates support for -// files. -func UseMultipartForm() ClientOption { - return func(client *Client) { - client.useMultipartForm = true - } -} - -//ImmediatelyCloseReqBody will close the req body immediately after each request body is ready -func ImmediatelyCloseReqBody() ClientOption { - return func(client *Client) { - client.closeReq = true - } -} - -func WithHttpResHandler(fn func(response *http.Response)) ClientOption { - return func(client *Client) { - client.HttpResHandler = fn - } -} - -func WithCookie(cookie []*http.Cookie) ClientOption { - return func(client *Client) { - client.cookies = cookie - } -} - -// ClientOption are functions that are passed into NewClient to -// modify the behaviour of the Client. -type ClientOption func(*Client) - -type graphError struct { - Message string -} - -func (e graphError) Error() string { - return "graphql: " + e.Message -} - -type graphResponse struct { - Data interface{} - Errors []graphError -} - -// Request is a GraphQL request. -type Request struct { - q string - vars map[string]interface{} - operationName string - files []File - - // Header represent any request headers that will be set - // when the request is made. - Header http.Header -} - -// NewRequest makes a new Request with the specified string. -func NewRequest(q string, variables map[string]interface{}) *Request { - req := &Request{ - q: q, - Header: make(map[string][]string), - vars: variables, - } - return req -} - -// SetOperationName set operation name -// 发往SQLE的请求如果指定了OperationName, 请求会被SQLE拦截并通过对应逻辑处理, 不添加OperationName的请求会被SQLE直接转发 -func (req *Request) SetOperationName(operationName string) { - req.operationName = operationName -} - -// Var sets a variable. -func (req *Request) Var(key string, value interface{}) { - if req.vars == nil { - req.vars = make(map[string]interface{}) - } - req.vars[key] = value -} - -// Vars gets the variables for this Request. -func (req *Request) Vars() map[string]interface{} { - return req.vars -} - -// Files gets the files in this request. -func (req *Request) Files() []File { - return req.files -} - -// Query gets the query string of this request. -func (req *Request) Query() string { - return req.q -} - -// File sets a file to upload. -// Files are only supported with a Client that was created with -// the UseMultipartForm option. -func (req *Request) File(fieldname, filename string, r io.Reader) { - req.files = append(req.files, File{ - Field: fieldname, - Name: filename, - R: r, - }) -} - -// File represents a file to upload. -type File struct { - Field string - Name string - R io.Reader -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/gqlgen.yml b/sqle/api/cloudbeaver_wrapper/graph/gqlgen.yml deleted file mode 100644 index a0b7e9c647..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/gqlgen.yml +++ /dev/null @@ -1,39 +0,0 @@ -# Where are all the schema files located? globs are supported eg src/**/*.graphqls -schema: - - ./schema/*.graphqls - -exec: - filename: ./resolver/executor_gen.go - package: resolver - -model: - filename: ./model/models_gen.go - package: model - -resolver: - layout: follow-schema - filename_template: "{name}_gen.go" - dir: ./resolver - package: resolver - -models: - ID: - model: - - github.com/99designs/gqlgen/graphql.ID - - github.com/99designs/gqlgen/graphql.Int - - github.com/99designs/gqlgen/graphql.Int64 - - github.com/99designs/gqlgen/graphql.Int32 - Int: - model: - - github.com/99designs/gqlgen/graphql.Int - - github.com/99designs/gqlgen/graphql.Int64 - - github.com/99designs/gqlgen/graphql.Int32 - - Object: - model: - - github.com/99designs/gqlgen/graphql.Any - - DateTime: - model: - - github.com/99designs/gqlgen/graphql.Time - diff --git a/sqle/api/cloudbeaver_wrapper/graph/model/json.go b/sqle/api/cloudbeaver_wrapper/graph/model/json.go deleted file mode 100644 index 9b5bacfe0e..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/model/json.go +++ /dev/null @@ -1,34 +0,0 @@ -package model - -import ( - "encoding/json" - "io" -) - -type JSON map[string]interface{} - -// UnmarshalGQL implements the graphql.Unmarshaler interface -func (b *JSON) UnmarshalGQL(v interface{}) error { - *b = make(map[string]interface{}) - byteData, err := json.Marshal(v) - if err != nil { - panic("FAIL WHILE MARSHAL SCHEME") - } - tmp := make(map[string]interface{}) - err = json.Unmarshal(byteData, &tmp) - if err != nil { - panic("FAIL WHILE UNMARSHAL SCHEME") - //return fmt.Errorf("%v", err) - } - *b = tmp - return nil -} - -// MarshalGQL implements the graphql.Marshaler interface -func (b JSON) MarshalGQL(w io.Writer) { - byteData, err := json.Marshal(b) - if err != nil { - panic("FAIL WHILE MARSHAL SCHEME") - } - _, _ = w.Write(byteData) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/model/models_gen.go b/sqle/api/cloudbeaver_wrapper/graph/model/models_gen.go deleted file mode 100644 index 9dd0b67b45..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/model/models_gen.go +++ /dev/null @@ -1,993 +0,0 @@ -// Code generated by github.com/99designs/gqlgen, DO NOT EDIT. - -package model - -import ( - "fmt" - "io" - "strconv" - "time" -) - -type AdminAuthProviderConfiguration struct { - ProviderID string `json:"providerId"` - ID string `json:"id"` - DisplayName string `json:"displayName"` - Disabled bool `json:"disabled"` - IconURL *string `json:"iconURL"` - Description *string `json:"description"` - Parameters interface{} `json:"parameters"` - SignInLink *string `json:"signInLink"` - SignOutLink *string `json:"signOutLink"` - RedirectLink *string `json:"redirectLink"` - MetadataLink *string `json:"metadataLink"` -} - -type AdminConnectionGrantInfo struct { - ConnectionID string `json:"connectionId"` - DataSourceID string `json:"dataSourceId"` - SubjectID string `json:"subjectId"` - SubjectType AdminSubjectType `json:"subjectType"` -} - -type AdminConnectionSearchInfo struct { - DisplayName string `json:"displayName"` - Host string `json:"host"` - Port int `json:"port"` - PossibleDrivers []string `json:"possibleDrivers"` - DefaultDriver string `json:"defaultDriver"` -} - -type AdminPermissionInfo struct { - ID string `json:"id"` - Label *string `json:"label"` - Description *string `json:"description"` - Provider string `json:"provider"` - Category *string `json:"category"` -} - -type AdminRoleInfo struct { - RoleID string `json:"roleId"` - RoleName *string `json:"roleName"` - Description *string `json:"description"` - GrantedUsers []string `json:"grantedUsers"` - GrantedConnections []*AdminConnectionGrantInfo `json:"grantedConnections"` - RolePermissions []string `json:"rolePermissions"` -} - -type AdminUserInfo struct { - UserID string `json:"userId"` - MetaParameters interface{} `json:"metaParameters"` - ConfigurationParameters interface{} `json:"configurationParameters"` - GrantedRoles []string `json:"grantedRoles"` - GrantedConnections []*AdminConnectionGrantInfo `json:"grantedConnections"` - Origins []*ObjectOrigin `json:"origins"` - LinkedAuthProviders []string `json:"linkedAuthProviders"` - Enabled bool `json:"enabled"` -} - -type AsyncTaskInfo struct { - ID string `json:"id"` - Name *string `json:"name"` - Running bool `json:"running"` - Status *string `json:"status"` - Error *ServerError `json:"error"` - Result *SQLExecuteInfo `json:"result"` - TaskResult interface{} `json:"taskResult"` -} - -type AuthCredentialInfo struct { - ID string `json:"id"` - DisplayName string `json:"displayName"` - Description *string `json:"description"` - Admin bool `json:"admin"` - User bool `json:"user"` - Identifying bool `json:"identifying"` - PossibleValues []*string `json:"possibleValues"` - Encryption *AuthCredentialEncryption `json:"encryption"` -} - -type AuthInfo struct { - RedirectLink *string `json:"redirectLink"` - AuthID *string `json:"authId"` - AuthStatus AuthStatus `json:"authStatus"` - UserTokens []*UserAuthToken `json:"userTokens"` -} - -type AuthProviderConfiguration struct { - ID string `json:"id"` - DisplayName string `json:"displayName"` - Disabled bool `json:"disabled"` - IconURL *string `json:"iconURL"` - Description *string `json:"description"` - SignInLink *string `json:"signInLink"` - SignOutLink *string `json:"signOutLink"` - MetadataLink *string `json:"metadataLink"` -} - -type AuthProviderCredentialsProfile struct { - ID *string `json:"id"` - Label *string `json:"label"` - Description *string `json:"description"` - CredentialParameters []*AuthCredentialInfo `json:"credentialParameters"` -} - -type AuthProviderInfo struct { - ID string `json:"id"` - Label string `json:"label"` - Icon *string `json:"icon"` - Description *string `json:"description"` - DefaultProvider bool `json:"defaultProvider"` - Configurable bool `json:"configurable"` - Configurations []*AuthProviderConfiguration `json:"configurations"` - CredentialProfiles []*AuthProviderCredentialsProfile `json:"credentialProfiles"` - RequiredFeatures []string `json:"requiredFeatures"` -} - -type ConnectionConfig struct { - ConnectionID *string `json:"connectionId"` - Name *string `json:"name"` - Description *string `json:"description"` - TemplateID *string `json:"templateId"` - DriverID *string `json:"driverId"` - Host *string `json:"host"` - Port *string `json:"port"` - ServerName *string `json:"serverName"` - DatabaseName *string `json:"databaseName"` - URL *string `json:"url"` - Properties interface{} `json:"properties"` - Template *bool `json:"template"` - ReadOnly *bool `json:"readOnly"` - SaveCredentials *bool `json:"saveCredentials"` - AuthModelID *string `json:"authModelId"` - Credentials interface{} `json:"credentials"` - ProviderProperties interface{} `json:"providerProperties"` - NetworkHandlersConfig []*NetworkHandlerConfigInput `json:"networkHandlersConfig"` - DataSourceID *string `json:"dataSourceId"` - UserName *string `json:"userName"` - UserPassword *string `json:"userPassword"` - Folder *string `json:"folder"` -} - -type ConnectionFolderInfo struct { - ID string `json:"id"` - Description *string `json:"description"` -} - -type ConnectionInfo struct { - ID string `json:"id"` - DriverID string `json:"driverId"` - Name string `json:"name"` - Description *string `json:"description"` - Host *string `json:"host"` - Port *string `json:"port"` - ServerName *string `json:"serverName"` - DatabaseName *string `json:"databaseName"` - URL *string `json:"url"` - Properties interface{} `json:"properties"` - Template bool `json:"template"` - Connected bool `json:"connected"` - Provided bool `json:"provided"` - ReadOnly bool `json:"readOnly"` - UseURL bool `json:"useUrl"` - SaveCredentials bool `json:"saveCredentials"` - Folder *string `json:"folder"` - NodePath *string `json:"nodePath"` - ConnectTime *string `json:"connectTime"` - ConnectionError *ServerError `json:"connectionError"` - ServerVersion *string `json:"serverVersion"` - ClientVersion *string `json:"clientVersion"` - Origin *ObjectOrigin `json:"origin"` - AuthNeeded bool `json:"authNeeded"` - AuthModel *string `json:"authModel"` - AuthProperties []*ObjectPropertyInfo `json:"authProperties"` - ProviderProperties interface{} `json:"providerProperties"` - NetworkHandlersConfig []*NetworkHandlerConfig `json:"networkHandlersConfig"` - Features []string `json:"features"` - NavigatorSettings *NavigatorSettings `json:"navigatorSettings"` - SupportedDataFormats []ResultDataFormat `json:"supportedDataFormats"` -} - -type DataTransferParameters struct { - ProcessorID string `json:"processorId"` - Settings interface{} `json:"settings"` - ProcessorProperties interface{} `json:"processorProperties"` - Filter *SQLDataFilter `json:"filter"` -} - -type DataTransferProcessorInfo struct { - ID string `json:"id"` - Name *string `json:"name"` - Description *string `json:"description"` - FileExtension *string `json:"fileExtension"` - AppFileExtension *string `json:"appFileExtension"` - AppName *string `json:"appName"` - Order int `json:"order"` - Icon *string `json:"icon"` - Properties []*ObjectPropertyInfo `json:"properties"` - IsBinary *bool `json:"isBinary"` - IsHTML *bool `json:"isHTML"` -} - -type DataTypeLogicalOperation struct { - ID string `json:"id"` - Expression string `json:"expression"` - ArgumentCount *int `json:"argumentCount"` -} - -type DatabaseAuthModel struct { - ID string `json:"id"` - DisplayName string `json:"displayName"` - Description *string `json:"description"` - Icon *string `json:"icon"` - RequiresLocalConfiguration *bool `json:"requiresLocalConfiguration"` - Properties []*ObjectPropertyInfo `json:"properties"` -} - -type DatabaseCatalog struct { - Catalog *NavigatorNodeInfo `json:"catalog"` - SchemaList []*NavigatorNodeInfo `json:"schemaList"` -} - -type DatabaseDocument struct { - ID *string `json:"id"` - ContentType *string `json:"contentType"` - Properties interface{} `json:"properties"` - Data interface{} `json:"data"` -} - -type DatabaseObjectInfo struct { - Name *string `json:"name"` - Description *string `json:"description"` - Type *string `json:"type"` - Properties []*ObjectPropertyInfo `json:"properties"` - OrdinalPosition *int `json:"ordinalPosition"` - FullyQualifiedName *string `json:"fullyQualifiedName"` - OverloadedName *string `json:"overloadedName"` - UniqueName *string `json:"uniqueName"` - State *string `json:"state"` - Features []string `json:"features"` - Editors []string `json:"editors"` -} - -type DatabaseStructContainers struct { - CatalogList []*DatabaseCatalog `json:"catalogList"` - SchemaList []*NavigatorNodeInfo `json:"schemaList"` - SupportsCatalogChange bool `json:"supportsCatalogChange"` - SupportsSchemaChange bool `json:"supportsSchemaChange"` -} - -type DriverInfo struct { - ID string `json:"id"` - Name *string `json:"name"` - Description *string `json:"description"` - Icon *string `json:"icon"` - IconBig *string `json:"iconBig"` - ProviderID *string `json:"providerId"` - DriverClassName *string `json:"driverClassName"` - DefaultHost *string `json:"defaultHost"` - DefaultPort *string `json:"defaultPort"` - DefaultDatabase *string `json:"defaultDatabase"` - DefaultServer *string `json:"defaultServer"` - DefaultUser *string `json:"defaultUser"` - SampleURL *string `json:"sampleURL"` - DriverInfoURL *string `json:"driverInfoURL"` - DriverPropertiesURL *string `json:"driverPropertiesURL"` - Embedded *bool `json:"embedded"` - Enabled bool `json:"enabled"` - RequiresServerName *bool `json:"requiresServerName"` - AllowsEmptyPassword *bool `json:"allowsEmptyPassword"` - LicenseRequired *bool `json:"licenseRequired"` - License *string `json:"license"` - Custom *bool `json:"custom"` - PromotedScore *int `json:"promotedScore"` - DriverProperties []*ObjectPropertyInfo `json:"driverProperties"` - DriverParameters interface{} `json:"driverParameters"` - ProviderProperties []*ObjectPropertyInfo `json:"providerProperties"` - AnonymousAccess *bool `json:"anonymousAccess"` - DefaultAuthModel string `json:"defaultAuthModel"` - ApplicableAuthModels []string `json:"applicableAuthModels"` - ApplicableNetworkHandlers []*string `json:"applicableNetworkHandlers"` -} - -type LogEntry struct { - Time *time.Time `json:"time"` - Type string `json:"type"` - Message *string `json:"message"` - StackTrace *string `json:"stackTrace"` -} - -type NavigatorNodeInfo struct { - ID string `json:"id"` - Name *string `json:"name"` - FullName *string `json:"fullName"` - Icon *string `json:"icon"` - Description *string `json:"description"` - NodeType *string `json:"nodeType"` - HasChildren *bool `json:"hasChildren"` - Object *DatabaseObjectInfo `json:"object"` - Features []string `json:"features"` - NodeDetails []*ObjectPropertyInfo `json:"nodeDetails"` - Folder *bool `json:"folder"` - Inline *bool `json:"inline"` - Navigable *bool `json:"navigable"` -} - -type NavigatorSettings struct { - ShowSystemObjects bool `json:"showSystemObjects"` - ShowUtilityObjects bool `json:"showUtilityObjects"` - ShowOnlyEntities bool `json:"showOnlyEntities"` - MergeEntities bool `json:"mergeEntities"` - HideFolders bool `json:"hideFolders"` - HideSchemas bool `json:"hideSchemas"` - HideVirtualModel bool `json:"hideVirtualModel"` -} - -type NavigatorSettingsInput struct { - ShowSystemObjects bool `json:"showSystemObjects"` - ShowUtilityObjects bool `json:"showUtilityObjects"` - ShowOnlyEntities bool `json:"showOnlyEntities"` - MergeEntities bool `json:"mergeEntities"` - HideFolders bool `json:"hideFolders"` - HideSchemas bool `json:"hideSchemas"` - HideVirtualModel bool `json:"hideVirtualModel"` -} - -type NetworkEndpointInfo struct { - Message *string `json:"message"` - ClientVersion *string `json:"clientVersion"` - ServerVersion *string `json:"serverVersion"` -} - -type NetworkHandlerConfig struct { - ID string `json:"id"` - Enabled bool `json:"enabled"` - AuthType NetworkHandlerAuthType `json:"authType"` - UserName *string `json:"userName"` - Password *string `json:"password"` - Key *string `json:"key"` - SavePassword bool `json:"savePassword"` - Properties interface{} `json:"properties"` -} - -type NetworkHandlerConfigInput struct { - ID string `json:"id"` - Enabled *bool `json:"enabled"` - AuthType *NetworkHandlerAuthType `json:"authType"` - UserName *string `json:"userName"` - Password *string `json:"password"` - Key *string `json:"key"` - SavePassword *bool `json:"savePassword"` - Properties interface{} `json:"properties"` -} - -type NetworkHandlerDescriptor struct { - ID string `json:"id"` - CodeName string `json:"codeName"` - Label string `json:"label"` - Description *string `json:"description"` - Secured bool `json:"secured"` - Type *NetworkHandlerType `json:"type"` - Properties []*ObjectPropertyInfo `json:"properties"` -} - -type ObjectDescriptor struct { - ID *int `json:"id"` - DisplayName *string `json:"displayName"` - FullName *string `json:"fullName"` - UniqueName *string `json:"uniqueName"` - Description *string `json:"description"` - Value *string `json:"value"` -} - -type ObjectDetails struct { - ID *int `json:"id"` - DisplayName *string `json:"displayName"` - Description *string `json:"description"` - Value interface{} `json:"value"` -} - -type ObjectOrigin struct { - Type string `json:"type"` - SubType *string `json:"subType"` - DisplayName string `json:"displayName"` - Icon *string `json:"icon"` - Configuration interface{} `json:"configuration"` - Details []*ObjectPropertyInfo `json:"details"` -} - -type ObjectPropertyFilter struct { - Ids []string `json:"ids"` - Features []string `json:"features"` - Categories []string `json:"categories"` - DataTypes []string `json:"dataTypes"` -} - -type ObjectPropertyInfo struct { - ID *string `json:"id"` - DisplayName *string `json:"displayName"` - Description *string `json:"description"` - Category *string `json:"category"` - DataType *string `json:"dataType"` - Value interface{} `json:"value"` - ValidValues []interface{} `json:"validValues"` - DefaultValue interface{} `json:"defaultValue"` - Length ObjectPropertyLength `json:"length"` - Features []string `json:"features"` - Order int `json:"order"` -} - -type ProductInfo struct { - ID string `json:"id"` - Version string `json:"version"` - Name string `json:"name"` - Description *string `json:"description"` - BuildTime string `json:"buildTime"` - ReleaseTime string `json:"releaseTime"` - LicenseInfo *string `json:"licenseInfo"` - LatestVersionInfo *string `json:"latestVersionInfo"` -} - -type RMProject struct { - ID string `json:"id"` - Name string `json:"name"` - Description *string `json:"description"` - Shared bool `json:"shared"` - CreateTime time.Time `json:"createTime"` - Creator string `json:"creator"` -} - -type RMResource struct { - Name string `json:"name"` - Folder bool `json:"folder"` - Length int `json:"length"` -} - -type SQLCompletionProposal struct { - DisplayString string `json:"displayString"` - Type string `json:"type"` - Score *int `json:"score"` - ReplacementString string `json:"replacementString"` - ReplacementOffset int `json:"replacementOffset"` - ReplacementLength int `json:"replacementLength"` - CursorPosition *int `json:"cursorPosition"` - Icon *string `json:"icon"` - NodePath *string `json:"nodePath"` -} - -type SQLContextInfo struct { - ID string `json:"id"` - ConnectionID string `json:"connectionId"` - DefaultCatalog *string `json:"defaultCatalog"` - DefaultSchema *string `json:"defaultSchema"` -} - -type SQLDataFilter struct { - Offset *float64 `json:"offset"` - Limit *int `json:"limit"` - Constraints []*SQLDataFilterConstraint `json:"constraints"` - Where *string `json:"where"` - OrderBy *string `json:"orderBy"` -} - -type SQLDataFilterConstraint struct { - AttributePosition int `json:"attributePosition"` - OrderPosition *int `json:"orderPosition"` - OrderAsc *bool `json:"orderAsc"` - Criteria *string `json:"criteria"` - Operator *string `json:"operator"` - Value interface{} `json:"value"` -} - -type SQLDialectInfo struct { - Name string `json:"name"` - DataTypes []*string `json:"dataTypes"` - Functions []*string `json:"functions"` - ReservedWords []*string `json:"reservedWords"` - QuoteStrings [][]*string `json:"quoteStrings"` - SingleLineComments []*string `json:"singleLineComments"` - MultiLineComments [][]*string `json:"multiLineComments"` - CatalogSeparator *string `json:"catalogSeparator"` - StructSeparator *string `json:"structSeparator"` - ScriptDelimiter *string `json:"scriptDelimiter"` - SupportsExplainExecutionPlan bool `json:"supportsExplainExecutionPlan"` -} - -type SQLExecuteInfo struct { - StatusMessage *string `json:"statusMessage"` - Duration int `json:"duration"` - FilterText *string `json:"filterText"` - Results []*SQLQueryResults `json:"results"` -} - -type SQLExecutionPlan struct { - Query string `json:"query"` - Nodes []*SQLExecutionPlanNode `json:"nodes"` -} - -type SQLExecutionPlanNode struct { - ID string `json:"id"` - ParentID *string `json:"parentId"` - Kind string `json:"kind"` - Name *string `json:"name"` - Type string `json:"type"` - Condition *string `json:"condition"` - Description *string `json:"description"` - Properties []*ObjectPropertyInfo `json:"properties"` -} - -type SQLQueryGenerator struct { - ID string `json:"id"` - Label string `json:"label"` - Description *string `json:"description"` - Order int `json:"order"` - MultiObject bool `json:"multiObject"` -} - -type SQLQueryResults struct { - Title *string `json:"title"` - UpdateRowCount *float64 `json:"updateRowCount"` - SourceQuery *string `json:"sourceQuery"` - DataFormat *ResultDataFormat `json:"dataFormat"` - ResultSet *SQLResultSet `json:"resultSet"` -} - -type SQLResultColumn struct { - Position int `json:"position"` - Name *string `json:"name"` - Label *string `json:"label"` - Icon *string `json:"icon"` - EntityName *string `json:"entityName"` - DataKind *string `json:"dataKind"` - TypeName *string `json:"typeName"` - FullTypeName *string `json:"fullTypeName"` - MaxLength *float64 `json:"maxLength"` - Scale *int `json:"scale"` - Precision *int `json:"precision"` - Required bool `json:"required"` - ReadOnly bool `json:"readOnly"` - ReadOnlyStatus *string `json:"readOnlyStatus"` - SupportedOperations []*DataTypeLogicalOperation `json:"supportedOperations"` -} - -type SQLResultRow struct { - Data []interface{} `json:"data"` - UpdateValues interface{} `json:"updateValues"` -} - -type SQLResultSet struct { - ID string `json:"id"` - Columns []*SQLResultColumn `json:"columns"` - Rows [][]interface{} `json:"rows"` - SingleEntity bool `json:"singleEntity"` - HasMoreData bool `json:"hasMoreData"` - HasRowIdentifier bool `json:"hasRowIdentifier"` -} - -type SQLScriptInfo struct { - Queries []*SQLScriptQuery `json:"queries"` -} - -type SQLScriptQuery struct { - Start int `json:"start"` - End int `json:"end"` -} - -type ServerConfig struct { - Name string `json:"name"` - Version string `json:"version"` - WorkspaceID string `json:"workspaceId"` - ServerURL string `json:"serverURL"` - RootURI string `json:"rootURI"` - HostName string `json:"hostName"` - AnonymousAccessEnabled *bool `json:"anonymousAccessEnabled"` - AuthenticationEnabled *bool `json:"authenticationEnabled"` - SupportsCustomConnections *bool `json:"supportsCustomConnections"` - SupportsConnectionBrowser *bool `json:"supportsConnectionBrowser"` - SupportsWorkspaces *bool `json:"supportsWorkspaces"` - ResourceManagerEnabled *bool `json:"resourceManagerEnabled"` - PublicCredentialsSaveEnabled *bool `json:"publicCredentialsSaveEnabled"` - AdminCredentialsSaveEnabled *bool `json:"adminCredentialsSaveEnabled"` - LicenseRequired bool `json:"licenseRequired"` - LicenseValid bool `json:"licenseValid"` - SessionExpireTime *int `json:"sessionExpireTime"` - LocalHostAddress *string `json:"localHostAddress"` - ConfigurationMode *bool `json:"configurationMode"` - DevelopmentMode *bool `json:"developmentMode"` - RedirectOnFederatedAuth *bool `json:"redirectOnFederatedAuth"` - EnabledFeatures []string `json:"enabledFeatures"` - EnabledAuthProviders []string `json:"enabledAuthProviders"` - SupportedLanguages []*ServerLanguage `json:"supportedLanguages"` - Services []*WebServiceConfig `json:"services"` - ProductConfiguration interface{} `json:"productConfiguration"` - ProductInfo *ProductInfo `json:"productInfo"` - DefaultNavigatorSettings *NavigatorSettings `json:"defaultNavigatorSettings"` - DisabledDrivers []string `json:"disabledDrivers"` - ResourceQuotas interface{} `json:"resourceQuotas"` -} - -type ServerConfigInput struct { - ServerName *string `json:"serverName"` - ServerURL *string `json:"serverURL"` - AdminName *string `json:"adminName"` - AdminPassword *string `json:"adminPassword"` - AnonymousAccessEnabled *bool `json:"anonymousAccessEnabled"` - AuthenticationEnabled *bool `json:"authenticationEnabled"` - CustomConnectionsEnabled *bool `json:"customConnectionsEnabled"` - PublicCredentialsSaveEnabled *bool `json:"publicCredentialsSaveEnabled"` - AdminCredentialsSaveEnabled *bool `json:"adminCredentialsSaveEnabled"` - ResourceManagerEnabled *bool `json:"resourceManagerEnabled"` - EnabledFeatures []string `json:"enabledFeatures"` - EnabledAuthProviders []string `json:"enabledAuthProviders"` - DisabledDrivers []string `json:"disabledDrivers"` - SessionExpireTime *int `json:"sessionExpireTime"` -} - -type ServerError struct { - Message *string `json:"message"` - ErrorCode *string `json:"errorCode"` - ErrorType *string `json:"errorType"` - StackTrace *string `json:"stackTrace"` - CausedBy *ServerError `json:"causedBy"` -} - -type ServerLanguage struct { - IsoCode string `json:"isoCode"` - DisplayName *string `json:"displayName"` - NativeName *string `json:"nativeName"` -} - -type ServerMessage struct { - Time *string `json:"time"` - Message *string `json:"message"` -} - -type SessionInfo struct { - CreateTime string `json:"createTime"` - LastAccessTime string `json:"lastAccessTime"` - Locale string `json:"locale"` - CacheExpired bool `json:"cacheExpired"` - ServerMessages []*ServerMessage `json:"serverMessages"` - Connections []*ConnectionInfo `json:"connections"` - ActionParameters interface{} `json:"actionParameters"` -} - -type UserAuthToken struct { - AuthProvider string `json:"authProvider"` - AuthConfiguration *string `json:"authConfiguration"` - LoginTime time.Time `json:"loginTime"` - UserID string `json:"userId"` - DisplayName string `json:"displayName"` - Message *string `json:"message"` - Origin *ObjectOrigin `json:"origin"` -} - -type UserInfo struct { - UserID string `json:"userId"` - DisplayName *string `json:"displayName"` - AuthRole *string `json:"authRole"` - AuthTokens []*UserAuthToken `json:"authTokens"` - LinkedAuthProviders []string `json:"linkedAuthProviders"` - MetaParameters interface{} `json:"metaParameters"` - ConfigurationParameters interface{} `json:"configurationParameters"` -} - -type WebFeatureSet struct { - ID string `json:"id"` - Label string `json:"label"` - Description *string `json:"description"` - Icon *string `json:"icon"` - Enabled bool `json:"enabled"` -} - -type WebServiceConfig struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - BundleVersion string `json:"bundleVersion"` -} - -type AdminSubjectType string - -const ( - AdminSubjectTypeUser AdminSubjectType = "user" - AdminSubjectTypeRole AdminSubjectType = "role" -) - -var AllAdminSubjectType = []AdminSubjectType{ - AdminSubjectTypeUser, - AdminSubjectTypeRole, -} - -func (e AdminSubjectType) IsValid() bool { - switch e { - case AdminSubjectTypeUser, AdminSubjectTypeRole: - return true - } - return false -} - -func (e AdminSubjectType) String() string { - return string(e) -} - -func (e *AdminSubjectType) UnmarshalGQL(v interface{}) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = AdminSubjectType(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid AdminSubjectType", str) - } - return nil -} - -func (e AdminSubjectType) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} - -type AuthCredentialEncryption string - -const ( - AuthCredentialEncryptionNone AuthCredentialEncryption = "none" - AuthCredentialEncryptionPlain AuthCredentialEncryption = "plain" - AuthCredentialEncryptionHash AuthCredentialEncryption = "hash" -) - -var AllAuthCredentialEncryption = []AuthCredentialEncryption{ - AuthCredentialEncryptionNone, - AuthCredentialEncryptionPlain, - AuthCredentialEncryptionHash, -} - -func (e AuthCredentialEncryption) IsValid() bool { - switch e { - case AuthCredentialEncryptionNone, AuthCredentialEncryptionPlain, AuthCredentialEncryptionHash: - return true - } - return false -} - -func (e AuthCredentialEncryption) String() string { - return string(e) -} - -func (e *AuthCredentialEncryption) UnmarshalGQL(v interface{}) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = AuthCredentialEncryption(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid AuthCredentialEncryption", str) - } - return nil -} - -func (e AuthCredentialEncryption) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} - -type AuthStatus string - -const ( - AuthStatusSuccess AuthStatus = "SUCCESS" - AuthStatusInProgress AuthStatus = "IN_PROGRESS" - AuthStatusError AuthStatus = "ERROR" -) - -var AllAuthStatus = []AuthStatus{ - AuthStatusSuccess, - AuthStatusInProgress, - AuthStatusError, -} - -func (e AuthStatus) IsValid() bool { - switch e { - case AuthStatusSuccess, AuthStatusInProgress, AuthStatusError: - return true - } - return false -} - -func (e AuthStatus) String() string { - return string(e) -} - -func (e *AuthStatus) UnmarshalGQL(v interface{}) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = AuthStatus(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid AuthStatus", str) - } - return nil -} - -func (e AuthStatus) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} - -type NetworkHandlerAuthType string - -const ( - NetworkHandlerAuthTypePassword NetworkHandlerAuthType = "PASSWORD" - NetworkHandlerAuthTypePublicKey NetworkHandlerAuthType = "PUBLIC_KEY" - NetworkHandlerAuthTypeAgent NetworkHandlerAuthType = "AGENT" -) - -var AllNetworkHandlerAuthType = []NetworkHandlerAuthType{ - NetworkHandlerAuthTypePassword, - NetworkHandlerAuthTypePublicKey, - NetworkHandlerAuthTypeAgent, -} - -func (e NetworkHandlerAuthType) IsValid() bool { - switch e { - case NetworkHandlerAuthTypePassword, NetworkHandlerAuthTypePublicKey, NetworkHandlerAuthTypeAgent: - return true - } - return false -} - -func (e NetworkHandlerAuthType) String() string { - return string(e) -} - -func (e *NetworkHandlerAuthType) UnmarshalGQL(v interface{}) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = NetworkHandlerAuthType(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid NetworkHandlerAuthType", str) - } - return nil -} - -func (e NetworkHandlerAuthType) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} - -type NetworkHandlerType string - -const ( - NetworkHandlerTypeTunnel NetworkHandlerType = "TUNNEL" - NetworkHandlerTypeProxy NetworkHandlerType = "PROXY" - NetworkHandlerTypeConfig NetworkHandlerType = "CONFIG" -) - -var AllNetworkHandlerType = []NetworkHandlerType{ - NetworkHandlerTypeTunnel, - NetworkHandlerTypeProxy, - NetworkHandlerTypeConfig, -} - -func (e NetworkHandlerType) IsValid() bool { - switch e { - case NetworkHandlerTypeTunnel, NetworkHandlerTypeProxy, NetworkHandlerTypeConfig: - return true - } - return false -} - -func (e NetworkHandlerType) String() string { - return string(e) -} - -func (e *NetworkHandlerType) UnmarshalGQL(v interface{}) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = NetworkHandlerType(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid NetworkHandlerType", str) - } - return nil -} - -func (e NetworkHandlerType) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} - -type ObjectPropertyLength string - -const ( - ObjectPropertyLengthTiny ObjectPropertyLength = "TINY" - ObjectPropertyLengthShort ObjectPropertyLength = "SHORT" - ObjectPropertyLengthMedium ObjectPropertyLength = "MEDIUM" - ObjectPropertyLengthLong ObjectPropertyLength = "LONG" - ObjectPropertyLengthMultiline ObjectPropertyLength = "MULTILINE" -) - -var AllObjectPropertyLength = []ObjectPropertyLength{ - ObjectPropertyLengthTiny, - ObjectPropertyLengthShort, - ObjectPropertyLengthMedium, - ObjectPropertyLengthLong, - ObjectPropertyLengthMultiline, -} - -func (e ObjectPropertyLength) IsValid() bool { - switch e { - case ObjectPropertyLengthTiny, ObjectPropertyLengthShort, ObjectPropertyLengthMedium, ObjectPropertyLengthLong, ObjectPropertyLengthMultiline: - return true - } - return false -} - -func (e ObjectPropertyLength) String() string { - return string(e) -} - -func (e *ObjectPropertyLength) UnmarshalGQL(v interface{}) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = ObjectPropertyLength(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid ObjectPropertyLength", str) - } - return nil -} - -func (e ObjectPropertyLength) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} - -type ResultDataFormat string - -const ( - ResultDataFormatResultset ResultDataFormat = "resultset" - ResultDataFormatDocument ResultDataFormat = "document" - ResultDataFormatGraph ResultDataFormat = "graph" - ResultDataFormatTimeseries ResultDataFormat = "timeseries" -) - -var AllResultDataFormat = []ResultDataFormat{ - ResultDataFormatResultset, - ResultDataFormatDocument, - ResultDataFormatGraph, - ResultDataFormatTimeseries, -} - -func (e ResultDataFormat) IsValid() bool { - switch e { - case ResultDataFormatResultset, ResultDataFormatDocument, ResultDataFormatGraph, ResultDataFormatTimeseries: - return true - } - return false -} - -func (e ResultDataFormat) String() string { - return string(e) -} - -func (e *ResultDataFormat) UnmarshalGQL(v interface{}) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = ResultDataFormat(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid ResultDataFormat", str) - } - return nil -} - -func (e ResultDataFormat) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/executor_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/executor_gen.go deleted file mode 100644 index 314febe019..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/executor_gen.go +++ /dev/null @@ -1,47771 +0,0 @@ -// Code generated by github.com/99designs/gqlgen, DO NOT EDIT. - -package resolver - -import ( - "bytes" - "context" - "errors" - "fmt" - "strconv" - "sync" - "sync/atomic" - "time" - - "github.com/99designs/gqlgen/graphql" - "github.com/99designs/gqlgen/graphql/introspection" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" - gqlparser "github.com/vektah/gqlparser/v2" - "github.com/vektah/gqlparser/v2/ast" -) - -// region ************************** generated!.gotpl ************************** - -// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. -func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { - return &executableSchema{ - resolvers: cfg.Resolvers, - directives: cfg.Directives, - complexity: cfg.Complexity, - } -} - -type Config struct { - Resolvers ResolverRoot - Directives DirectiveRoot - Complexity ComplexityRoot -} - -type ResolverRoot interface { - Mutation() MutationResolver - Query() QueryResolver -} - -type DirectiveRoot struct { -} - -type ComplexityRoot struct { - AdminAuthProviderConfiguration struct { - Description func(childComplexity int) int - Disabled func(childComplexity int) int - DisplayName func(childComplexity int) int - ID func(childComplexity int) int - IconURL func(childComplexity int) int - MetadataLink func(childComplexity int) int - Parameters func(childComplexity int) int - ProviderID func(childComplexity int) int - RedirectLink func(childComplexity int) int - SignInLink func(childComplexity int) int - SignOutLink func(childComplexity int) int - } - - AdminConnectionGrantInfo struct { - ConnectionID func(childComplexity int) int - DataSourceID func(childComplexity int) int - SubjectID func(childComplexity int) int - SubjectType func(childComplexity int) int - } - - AdminConnectionSearchInfo struct { - DefaultDriver func(childComplexity int) int - DisplayName func(childComplexity int) int - Host func(childComplexity int) int - Port func(childComplexity int) int - PossibleDrivers func(childComplexity int) int - } - - AdminPermissionInfo struct { - Category func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Label func(childComplexity int) int - Provider func(childComplexity int) int - } - - AdminRoleInfo struct { - Description func(childComplexity int) int - GrantedConnections func(childComplexity int) int - GrantedUsers func(childComplexity int) int - RoleID func(childComplexity int) int - RoleName func(childComplexity int) int - RolePermissions func(childComplexity int) int - } - - AdminUserInfo struct { - ConfigurationParameters func(childComplexity int) int - Enabled func(childComplexity int) int - GrantedConnections func(childComplexity int) int - GrantedRoles func(childComplexity int) int - LinkedAuthProviders func(childComplexity int) int - MetaParameters func(childComplexity int) int - Origins func(childComplexity int) int - UserID func(childComplexity int) int - } - - AsyncTaskInfo struct { - Error func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - Result func(childComplexity int) int - Running func(childComplexity int) int - Status func(childComplexity int) int - TaskResult func(childComplexity int) int - } - - AuthCredentialInfo struct { - Admin func(childComplexity int) int - Description func(childComplexity int) int - DisplayName func(childComplexity int) int - Encryption func(childComplexity int) int - ID func(childComplexity int) int - Identifying func(childComplexity int) int - PossibleValues func(childComplexity int) int - User func(childComplexity int) int - } - - AuthInfo struct { - AuthID func(childComplexity int) int - AuthStatus func(childComplexity int) int - RedirectLink func(childComplexity int) int - UserTokens func(childComplexity int) int - } - - AuthProviderConfiguration struct { - Description func(childComplexity int) int - Disabled func(childComplexity int) int - DisplayName func(childComplexity int) int - ID func(childComplexity int) int - IconURL func(childComplexity int) int - MetadataLink func(childComplexity int) int - SignInLink func(childComplexity int) int - SignOutLink func(childComplexity int) int - } - - AuthProviderCredentialsProfile struct { - CredentialParameters func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Label func(childComplexity int) int - } - - AuthProviderInfo struct { - Configurable func(childComplexity int) int - Configurations func(childComplexity int) int - CredentialProfiles func(childComplexity int) int - DefaultProvider func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Icon func(childComplexity int) int - Label func(childComplexity int) int - RequiredFeatures func(childComplexity int) int - } - - ConnectionFolderInfo struct { - Description func(childComplexity int) int - ID func(childComplexity int) int - } - - ConnectionInfo struct { - AuthModel func(childComplexity int) int - AuthNeeded func(childComplexity int) int - AuthProperties func(childComplexity int) int - ClientVersion func(childComplexity int) int - ConnectTime func(childComplexity int) int - Connected func(childComplexity int) int - ConnectionError func(childComplexity int) int - DatabaseName func(childComplexity int) int - Description func(childComplexity int) int - DriverID func(childComplexity int) int - Features func(childComplexity int) int - Folder func(childComplexity int) int - Host func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - NavigatorSettings func(childComplexity int) int - NetworkHandlersConfig func(childComplexity int) int - NodePath func(childComplexity int) int - Origin func(childComplexity int) int - Port func(childComplexity int) int - Properties func(childComplexity int) int - Provided func(childComplexity int) int - ProviderProperties func(childComplexity int) int - ReadOnly func(childComplexity int) int - SaveCredentials func(childComplexity int) int - ServerName func(childComplexity int) int - ServerVersion func(childComplexity int) int - SupportedDataFormats func(childComplexity int) int - Template func(childComplexity int) int - URL func(childComplexity int) int - UseURL func(childComplexity int) int - } - - DataTransferProcessorInfo struct { - AppFileExtension func(childComplexity int) int - AppName func(childComplexity int) int - Description func(childComplexity int) int - FileExtension func(childComplexity int) int - ID func(childComplexity int) int - Icon func(childComplexity int) int - IsBinary func(childComplexity int) int - IsHTML func(childComplexity int) int - Name func(childComplexity int) int - Order func(childComplexity int) int - Properties func(childComplexity int) int - } - - DataTypeLogicalOperation struct { - ArgumentCount func(childComplexity int) int - Expression func(childComplexity int) int - ID func(childComplexity int) int - } - - DatabaseAuthModel struct { - Description func(childComplexity int) int - DisplayName func(childComplexity int) int - ID func(childComplexity int) int - Icon func(childComplexity int) int - Properties func(childComplexity int) int - RequiresLocalConfiguration func(childComplexity int) int - } - - DatabaseCatalog struct { - Catalog func(childComplexity int) int - SchemaList func(childComplexity int) int - } - - DatabaseDocument struct { - ContentType func(childComplexity int) int - Data func(childComplexity int) int - ID func(childComplexity int) int - Properties func(childComplexity int) int - } - - DatabaseObjectInfo struct { - Description func(childComplexity int) int - Editors func(childComplexity int) int - Features func(childComplexity int) int - FullyQualifiedName func(childComplexity int) int - Name func(childComplexity int) int - OrdinalPosition func(childComplexity int) int - OverloadedName func(childComplexity int) int - Properties func(childComplexity int, filter *model.ObjectPropertyFilter) int - State func(childComplexity int) int - Type func(childComplexity int) int - UniqueName func(childComplexity int) int - } - - DatabaseStructContainers struct { - CatalogList func(childComplexity int) int - SchemaList func(childComplexity int) int - SupportsCatalogChange func(childComplexity int) int - SupportsSchemaChange func(childComplexity int) int - } - - DriverInfo struct { - AllowsEmptyPassword func(childComplexity int) int - AnonymousAccess func(childComplexity int) int - ApplicableAuthModels func(childComplexity int) int - ApplicableNetworkHandlers func(childComplexity int) int - Custom func(childComplexity int) int - DefaultAuthModel func(childComplexity int) int - DefaultDatabase func(childComplexity int) int - DefaultHost func(childComplexity int) int - DefaultPort func(childComplexity int) int - DefaultServer func(childComplexity int) int - DefaultUser func(childComplexity int) int - Description func(childComplexity int) int - DriverClassName func(childComplexity int) int - DriverInfoURL func(childComplexity int) int - DriverParameters func(childComplexity int) int - DriverProperties func(childComplexity int) int - DriverPropertiesURL func(childComplexity int) int - Embedded func(childComplexity int) int - Enabled func(childComplexity int) int - ID func(childComplexity int) int - Icon func(childComplexity int) int - IconBig func(childComplexity int) int - License func(childComplexity int) int - LicenseRequired func(childComplexity int) int - Name func(childComplexity int) int - PromotedScore func(childComplexity int) int - ProviderID func(childComplexity int) int - ProviderProperties func(childComplexity int) int - RequiresServerName func(childComplexity int) int - SampleURL func(childComplexity int) int - } - - LogEntry struct { - Message func(childComplexity int) int - StackTrace func(childComplexity int) int - Time func(childComplexity int) int - Type func(childComplexity int) int - } - - Mutation struct { - AsyncReadDataFromContainer func(childComplexity int, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) int - AsyncSQLExecuteQuery func(childComplexity int, projectID *string, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat, readLogs *bool) int - AsyncSQLExecuteResults func(childComplexity int, taskID string) int - AsyncSQLExplainExecutionPlan func(childComplexity int, connectionID string, contextID string, query string, configuration interface{}) int - AsyncSQLExplainExecutionPlanResult func(childComplexity int, taskID string) int - AsyncTaskCancel func(childComplexity int, id string) int - AsyncTaskInfo func(childComplexity int, id string, removeOnFinish bool) int - AsyncTaskStatus func(childComplexity int, id string) int - ChangeSessionLanguage func(childComplexity int, locale *string) int - CloseConnection func(childComplexity int, id string) int - CloseSession func(childComplexity int) int - CopyConnectionFromNode func(childComplexity int, nodePath string, config *model.ConnectionConfig) int - CreateConnection func(childComplexity int, config model.ConnectionConfig) int - CreateConnectionFolder func(childComplexity int, parentFolderPath *string, folderName string) int - CreateConnectionFromTemplate func(childComplexity int, templateID string, connectionName *string) int - DeleteConnection func(childComplexity int, id string) int - DeleteConnectionFolder func(childComplexity int, folderPath string) int - InitConnection func(childComplexity int, id string, credentials interface{}, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool) int - NavDeleteNodes func(childComplexity int, nodePaths []string) int - NavMoveNodesToFolder func(childComplexity int, nodePaths []string, folderPath string) int - NavRenameNode func(childComplexity int, nodePath string, newName string) int - OpenConnection func(childComplexity int, config model.ConnectionConfig) int - OpenSession func(childComplexity int, defaultLocale *string) int - ReadLobValue func(childComplexity int, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) int - RefreshSessionConnections func(childComplexity int) int - RmCreateResource func(childComplexity int, projectID string, resourcePath string, isFolder bool) int - RmDeleteResource func(childComplexity int, projectID string, resourcePath string, recursive bool) int - RmMoveResource func(childComplexity int, projectID string, oldResourcePath string, newResourcePath *string) int - RmWriteResourceStringContent func(childComplexity int, projectID string, resourcePath string, data string) int - SQLContextCreate func(childComplexity int, connectionID string, defaultCatalog *string, defaultSchema *string) int - SQLContextDestroy func(childComplexity int, connectionID string, contextID string) int - SQLContextSetDefaults func(childComplexity int, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) int - SQLResultClose func(childComplexity int, connectionID string, contextID string, resultID string) int - SetConnectionNavigatorSettings func(childComplexity int, id string, settings model.NavigatorSettingsInput) int - SetUserConfigurationParameter func(childComplexity int, name string, value interface{}) int - TestConnection func(childComplexity int, config model.ConnectionConfig) int - TestNetworkHandler func(childComplexity int, config model.NetworkHandlerConfigInput) int - TouchSession func(childComplexity int) int - UpdateConnection func(childComplexity int, config model.ConnectionConfig) int - UpdateResultsDataBatch func(childComplexity int, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) int - UpdateResultsDataBatchScript func(childComplexity int, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) int - } - - NavigatorNodeInfo struct { - Description func(childComplexity int) int - Features func(childComplexity int) int - Folder func(childComplexity int) int - FullName func(childComplexity int) int - HasChildren func(childComplexity int) int - ID func(childComplexity int) int - Icon func(childComplexity int) int - Inline func(childComplexity int) int - Name func(childComplexity int) int - Navigable func(childComplexity int) int - NodeDetails func(childComplexity int) int - NodeType func(childComplexity int) int - Object func(childComplexity int) int - } - - NavigatorSettings struct { - HideFolders func(childComplexity int) int - HideSchemas func(childComplexity int) int - HideVirtualModel func(childComplexity int) int - MergeEntities func(childComplexity int) int - ShowOnlyEntities func(childComplexity int) int - ShowSystemObjects func(childComplexity int) int - ShowUtilityObjects func(childComplexity int) int - } - - NetworkEndpointInfo struct { - ClientVersion func(childComplexity int) int - Message func(childComplexity int) int - ServerVersion func(childComplexity int) int - } - - NetworkHandlerConfig struct { - AuthType func(childComplexity int) int - Enabled func(childComplexity int) int - ID func(childComplexity int) int - Key func(childComplexity int) int - Password func(childComplexity int) int - Properties func(childComplexity int) int - SavePassword func(childComplexity int) int - UserName func(childComplexity int) int - } - - NetworkHandlerDescriptor struct { - CodeName func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Label func(childComplexity int) int - Properties func(childComplexity int) int - Secured func(childComplexity int) int - Type func(childComplexity int) int - } - - ObjectDescriptor struct { - Description func(childComplexity int) int - DisplayName func(childComplexity int) int - FullName func(childComplexity int) int - ID func(childComplexity int) int - UniqueName func(childComplexity int) int - Value func(childComplexity int) int - } - - ObjectDetails struct { - Description func(childComplexity int) int - DisplayName func(childComplexity int) int - ID func(childComplexity int) int - Value func(childComplexity int) int - } - - ObjectOrigin struct { - Configuration func(childComplexity int) int - Details func(childComplexity int) int - DisplayName func(childComplexity int) int - Icon func(childComplexity int) int - SubType func(childComplexity int) int - Type func(childComplexity int) int - } - - ObjectPropertyInfo struct { - Category func(childComplexity int) int - DataType func(childComplexity int) int - DefaultValue func(childComplexity int) int - Description func(childComplexity int) int - DisplayName func(childComplexity int) int - Features func(childComplexity int) int - ID func(childComplexity int) int - Length func(childComplexity int) int - Order func(childComplexity int) int - ValidValues func(childComplexity int) int - Value func(childComplexity int) int - } - - ProductInfo struct { - BuildTime func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - LatestVersionInfo func(childComplexity int) int - LicenseInfo func(childComplexity int) int - Name func(childComplexity int) int - ReleaseTime func(childComplexity int) int - Version func(childComplexity int) int - } - - Query struct { - ActiveUser func(childComplexity int) int - AllConnections func(childComplexity int, id *string) int - AuthChangeLocalPassword func(childComplexity int, oldPassword string, newPassword string) int - AuthLogin func(childComplexity int, provider string, configuration *string, credentials interface{}, linkUser *bool) int - AuthLogout func(childComplexity int, provider *string, configuration *string) int - AuthModels func(childComplexity int) int - AuthProviders func(childComplexity int) int - AuthUpdateStatus func(childComplexity int, authID string, linkUser *bool) int - ConfigureServer func(childComplexity int, configuration model.ServerConfigInput) int - ConnectionFolders func(childComplexity int, path *string) int - ConnectionInfo func(childComplexity int, id string) int - ConnectionState func(childComplexity int, id string) int - CopyConnectionConfiguration func(childComplexity int, nodePath string, config *model.ConnectionConfig) int - CreateConnectionConfiguration func(childComplexity int, config model.ConnectionConfig) int - CreateRole func(childComplexity int, roleID string, roleName *string, description *string) int - CreateUser func(childComplexity int, userID string) int - DataTransferAvailableStreamProcessors func(childComplexity int) int - DataTransferExportDataFromContainer func(childComplexity int, connectionID string, containerNodePath string, parameters model.DataTransferParameters) int - DataTransferExportDataFromResults func(childComplexity int, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) int - DataTransferRemoveDataFile func(childComplexity int, dataFileID string) int - DeleteAuthProviderConfiguration func(childComplexity int, id string) int - DeleteConnectionConfiguration func(childComplexity int, id string) int - DeleteRole func(childComplexity int, roleID string) int - DeleteUser func(childComplexity int, userID string) int - DeleteUserMetaParameter func(childComplexity int, id string) int - DriverList func(childComplexity int, id *string) int - EnableUser func(childComplexity int, userID string, enabled bool) int - GetConnectionSubjectAccess func(childComplexity int, connectionID *string) int - GetSubjectConnectionAccess func(childComplexity int, subjectID *string) int - GrantUserRole func(childComplexity int, userID string, roleID string) int - ListAuthProviderConfigurationParameters func(childComplexity int, providerID string) int - ListAuthProviderConfigurations func(childComplexity int, providerID *string) int - ListFeatureSets func(childComplexity int) int - ListPermissions func(childComplexity int) int - ListRoles func(childComplexity int, roleID *string) int - ListUserProfileProperties func(childComplexity int) int - ListUsers func(childComplexity int, userID *string) int - MetadataGetNodeDdl func(childComplexity int, nodeID string, options interface{}) int - NavGetStructContainers func(childComplexity int, connectionID string, contextID *string, catalog *string) int - NavNodeChildren func(childComplexity int, parentPath string, offset *int, limit *int, onlyFolders *bool) int - NavNodeInfo func(childComplexity int, nodePath string) int - NavNodeParents func(childComplexity int, nodePath string) int - NavRefreshNode func(childComplexity int, nodePath string) int - NetworkHandlers func(childComplexity int) int - ReadSessionLog func(childComplexity int, maxEntries *int, clearEntries *bool) int - RevokeUserRole func(childComplexity int, userID string, roleID string) int - RmListProjects func(childComplexity int) int - RmListResources func(childComplexity int, projectID string, folder *string, nameMask *string, readProperties *bool, readHistory *bool) int - RmReadResourceAsString func(childComplexity int, projectID string, resourcePath string) int - SQLCompletionProposals func(childComplexity int, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) int - SQLDialectInfo func(childComplexity int, connectionID string) int - SQLEntityQueryGenerators func(childComplexity int, nodePathList []string) int - SQLFormatQuery func(childComplexity int, connectionID string, contextID string, query string) int - SQLGenerateEntityQuery func(childComplexity int, generatorID string, options interface{}, nodePathList []string) int - SQLListContexts func(childComplexity int, connectionID *string, contextID *string) int - SQLParseQuery func(childComplexity int, connectionID string, script string, position int) int - SQLParseScript func(childComplexity int, connectionID string, script string) int - SQLSupportedOperations func(childComplexity int, connectionID string, contextID string, resultsID string, attributeIndex int) int - SaveAuthProviderConfiguration func(childComplexity int, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters interface{}) int - SaveUserMetaParameter func(childComplexity int, id string, displayName string, description *string, required bool) int - SearchConnections func(childComplexity int, hostNames []string) int - ServerConfig func(childComplexity int) int - SessionPermissions func(childComplexity int) int - SessionState func(childComplexity int) int - SetConnectionSubjectAccess func(childComplexity int, connectionID string, subjects []string) int - SetDefaultNavigatorSettings func(childComplexity int, settings model.NavigatorSettingsInput) int - SetSubjectConnectionAccess func(childComplexity int, subjectID string, connections []string) int - SetSubjectPermissions func(childComplexity int, roleID string, permissions []string) int - SetUserCredentials func(childComplexity int, userID string, providerID string, credentials interface{}) int - SetUserMetaParameterValues func(childComplexity int, userID string, parameters interface{}) int - TemplateConnections func(childComplexity int) int - UpdateConnectionConfiguration func(childComplexity int, id string, config model.ConnectionConfig) int - UpdateRole func(childComplexity int, roleID string, roleName *string, description *string) int - UserConnections func(childComplexity int, id *string) int - } - - RMProject struct { - CreateTime func(childComplexity int) int - Creator func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - Shared func(childComplexity int) int - } - - RMResource struct { - Folder func(childComplexity int) int - Length func(childComplexity int) int - Name func(childComplexity int) int - } - - SQLCompletionProposal struct { - CursorPosition func(childComplexity int) int - DisplayString func(childComplexity int) int - Icon func(childComplexity int) int - NodePath func(childComplexity int) int - ReplacementLength func(childComplexity int) int - ReplacementOffset func(childComplexity int) int - ReplacementString func(childComplexity int) int - Score func(childComplexity int) int - Type func(childComplexity int) int - } - - SQLContextInfo struct { - ConnectionID func(childComplexity int) int - DefaultCatalog func(childComplexity int) int - DefaultSchema func(childComplexity int) int - ID func(childComplexity int) int - } - - SQLDialectInfo struct { - CatalogSeparator func(childComplexity int) int - DataTypes func(childComplexity int) int - Functions func(childComplexity int) int - MultiLineComments func(childComplexity int) int - Name func(childComplexity int) int - QuoteStrings func(childComplexity int) int - ReservedWords func(childComplexity int) int - ScriptDelimiter func(childComplexity int) int - SingleLineComments func(childComplexity int) int - StructSeparator func(childComplexity int) int - SupportsExplainExecutionPlan func(childComplexity int) int - } - - SQLExecuteInfo struct { - Duration func(childComplexity int) int - FilterText func(childComplexity int) int - Results func(childComplexity int) int - StatusMessage func(childComplexity int) int - } - - SQLExecutionPlan struct { - Nodes func(childComplexity int) int - Query func(childComplexity int) int - } - - SQLExecutionPlanNode struct { - Condition func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Kind func(childComplexity int) int - Name func(childComplexity int) int - ParentID func(childComplexity int) int - Properties func(childComplexity int) int - Type func(childComplexity int) int - } - - SQLQueryGenerator struct { - Description func(childComplexity int) int - ID func(childComplexity int) int - Label func(childComplexity int) int - MultiObject func(childComplexity int) int - Order func(childComplexity int) int - } - - SQLQueryResults struct { - DataFormat func(childComplexity int) int - ResultSet func(childComplexity int) int - SourceQuery func(childComplexity int) int - Title func(childComplexity int) int - UpdateRowCount func(childComplexity int) int - } - - SQLResultColumn struct { - DataKind func(childComplexity int) int - EntityName func(childComplexity int) int - FullTypeName func(childComplexity int) int - Icon func(childComplexity int) int - Label func(childComplexity int) int - MaxLength func(childComplexity int) int - Name func(childComplexity int) int - Position func(childComplexity int) int - Precision func(childComplexity int) int - ReadOnly func(childComplexity int) int - ReadOnlyStatus func(childComplexity int) int - Required func(childComplexity int) int - Scale func(childComplexity int) int - SupportedOperations func(childComplexity int) int - TypeName func(childComplexity int) int - } - - SQLResultSet struct { - Columns func(childComplexity int) int - HasMoreData func(childComplexity int) int - HasRowIdentifier func(childComplexity int) int - ID func(childComplexity int) int - Rows func(childComplexity int) int - SingleEntity func(childComplexity int) int - } - - SQLScriptInfo struct { - Queries func(childComplexity int) int - } - - SQLScriptQuery struct { - End func(childComplexity int) int - Start func(childComplexity int) int - } - - ServerConfig struct { - AdminCredentialsSaveEnabled func(childComplexity int) int - AnonymousAccessEnabled func(childComplexity int) int - AuthenticationEnabled func(childComplexity int) int - ConfigurationMode func(childComplexity int) int - DefaultNavigatorSettings func(childComplexity int) int - DevelopmentMode func(childComplexity int) int - DisabledDrivers func(childComplexity int) int - EnabledAuthProviders func(childComplexity int) int - EnabledFeatures func(childComplexity int) int - HostName func(childComplexity int) int - LicenseRequired func(childComplexity int) int - LicenseValid func(childComplexity int) int - LocalHostAddress func(childComplexity int) int - Name func(childComplexity int) int - ProductConfiguration func(childComplexity int) int - ProductInfo func(childComplexity int) int - PublicCredentialsSaveEnabled func(childComplexity int) int - RedirectOnFederatedAuth func(childComplexity int) int - ResourceManagerEnabled func(childComplexity int) int - ResourceQuotas func(childComplexity int) int - RootURI func(childComplexity int) int - ServerURL func(childComplexity int) int - Services func(childComplexity int) int - SessionExpireTime func(childComplexity int) int - SupportedLanguages func(childComplexity int) int - SupportsConnectionBrowser func(childComplexity int) int - SupportsCustomConnections func(childComplexity int) int - SupportsWorkspaces func(childComplexity int) int - Version func(childComplexity int) int - WorkspaceID func(childComplexity int) int - } - - ServerError struct { - CausedBy func(childComplexity int) int - ErrorCode func(childComplexity int) int - ErrorType func(childComplexity int) int - Message func(childComplexity int) int - StackTrace func(childComplexity int) int - } - - ServerLanguage struct { - DisplayName func(childComplexity int) int - IsoCode func(childComplexity int) int - NativeName func(childComplexity int) int - } - - ServerMessage struct { - Message func(childComplexity int) int - Time func(childComplexity int) int - } - - SessionInfo struct { - ActionParameters func(childComplexity int) int - CacheExpired func(childComplexity int) int - Connections func(childComplexity int) int - CreateTime func(childComplexity int) int - LastAccessTime func(childComplexity int) int - Locale func(childComplexity int) int - ServerMessages func(childComplexity int) int - } - - UserAuthToken struct { - AuthConfiguration func(childComplexity int) int - AuthProvider func(childComplexity int) int - DisplayName func(childComplexity int) int - LoginTime func(childComplexity int) int - Message func(childComplexity int) int - Origin func(childComplexity int) int - UserID func(childComplexity int) int - } - - UserInfo struct { - AuthRole func(childComplexity int) int - AuthTokens func(childComplexity int) int - ConfigurationParameters func(childComplexity int) int - DisplayName func(childComplexity int) int - LinkedAuthProviders func(childComplexity int) int - MetaParameters func(childComplexity int) int - UserID func(childComplexity int) int - } - - WebFeatureSet struct { - Description func(childComplexity int) int - Enabled func(childComplexity int) int - ID func(childComplexity int) int - Icon func(childComplexity int) int - Label func(childComplexity int) int - } - - WebServiceConfig struct { - BundleVersion func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - } -} - -type MutationResolver interface { - SetUserConfigurationParameter(ctx context.Context, name string, value interface{}) (bool, error) - OpenSession(ctx context.Context, defaultLocale *string) (*model.SessionInfo, error) - CloseSession(ctx context.Context) (*bool, error) - TouchSession(ctx context.Context) (*bool, error) - RefreshSessionConnections(ctx context.Context) (*bool, error) - ChangeSessionLanguage(ctx context.Context, locale *string) (*bool, error) - CreateConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - UpdateConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - DeleteConnection(ctx context.Context, id string) (bool, error) - CreateConnectionFromTemplate(ctx context.Context, templateID string, connectionName *string) (*model.ConnectionInfo, error) - CreateConnectionFolder(ctx context.Context, parentFolderPath *string, folderName string) (*model.ConnectionFolderInfo, error) - DeleteConnectionFolder(ctx context.Context, folderPath string) (bool, error) - CopyConnectionFromNode(ctx context.Context, nodePath string, config *model.ConnectionConfig) (*model.ConnectionInfo, error) - TestConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - TestNetworkHandler(ctx context.Context, config model.NetworkHandlerConfigInput) (*model.NetworkEndpointInfo, error) - InitConnection(ctx context.Context, id string, credentials interface{}, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool) (*model.ConnectionInfo, error) - CloseConnection(ctx context.Context, id string) (*model.ConnectionInfo, error) - SetConnectionNavigatorSettings(ctx context.Context, id string, settings model.NavigatorSettingsInput) (*model.ConnectionInfo, error) - AsyncTaskCancel(ctx context.Context, id string) (*bool, error) - AsyncTaskInfo(ctx context.Context, id string, removeOnFinish bool) (*model.AsyncTaskInfo, error) - OpenConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - AsyncTaskStatus(ctx context.Context, id string) (*model.AsyncTaskInfo, error) - NavRenameNode(ctx context.Context, nodePath string, newName string) (*string, error) - NavDeleteNodes(ctx context.Context, nodePaths []string) (*int, error) - NavMoveNodesToFolder(ctx context.Context, nodePaths []string, folderPath string) (*bool, error) - RmCreateResource(ctx context.Context, projectID string, resourcePath string, isFolder bool) (string, error) - RmMoveResource(ctx context.Context, projectID string, oldResourcePath string, newResourcePath *string) (string, error) - RmDeleteResource(ctx context.Context, projectID string, resourcePath string, recursive bool) (*bool, error) - RmWriteResourceStringContent(ctx context.Context, projectID string, resourcePath string, data string) (string, error) - SQLContextCreate(ctx context.Context, connectionID string, defaultCatalog *string, defaultSchema *string) (*model.SQLContextInfo, error) - SQLContextSetDefaults(ctx context.Context, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) (bool, error) - SQLContextDestroy(ctx context.Context, connectionID string, contextID string) (bool, error) - AsyncSQLExecuteQuery(ctx context.Context, projectID *string, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat, readLogs *bool) (*model.AsyncTaskInfo, error) - AsyncReadDataFromContainer(ctx context.Context, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) - SQLResultClose(ctx context.Context, connectionID string, contextID string, resultID string) (bool, error) - UpdateResultsDataBatch(ctx context.Context, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (*model.SQLExecuteInfo, error) - UpdateResultsDataBatchScript(ctx context.Context, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (string, error) - ReadLobValue(ctx context.Context, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) (string, error) - AsyncSQLExecuteResults(ctx context.Context, taskID string) (*model.SQLExecuteInfo, error) - AsyncSQLExplainExecutionPlan(ctx context.Context, connectionID string, contextID string, query string, configuration interface{}) (*model.AsyncTaskInfo, error) - AsyncSQLExplainExecutionPlanResult(ctx context.Context, taskID string) (*model.SQLExecutionPlan, error) -} -type QueryResolver interface { - ListUsers(ctx context.Context, userID *string) ([]*model.AdminUserInfo, error) - ListRoles(ctx context.Context, roleID *string) ([]*model.AdminRoleInfo, error) - ListPermissions(ctx context.Context) ([]*model.AdminPermissionInfo, error) - CreateUser(ctx context.Context, userID string) (*model.AdminUserInfo, error) - DeleteUser(ctx context.Context, userID string) (*bool, error) - CreateRole(ctx context.Context, roleID string, roleName *string, description *string) (*model.AdminRoleInfo, error) - UpdateRole(ctx context.Context, roleID string, roleName *string, description *string) (*model.AdminRoleInfo, error) - DeleteRole(ctx context.Context, roleID string) (*bool, error) - GrantUserRole(ctx context.Context, userID string, roleID string) (*bool, error) - RevokeUserRole(ctx context.Context, userID string, roleID string) (*bool, error) - SetSubjectPermissions(ctx context.Context, roleID string, permissions []string) ([]*model.AdminPermissionInfo, error) - SetUserCredentials(ctx context.Context, userID string, providerID string, credentials interface{}) (*bool, error) - EnableUser(ctx context.Context, userID string, enabled bool) (*bool, error) - AllConnections(ctx context.Context, id *string) ([]*model.ConnectionInfo, error) - SearchConnections(ctx context.Context, hostNames []string) ([]*model.AdminConnectionSearchInfo, error) - CreateConnectionConfiguration(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - CopyConnectionConfiguration(ctx context.Context, nodePath string, config *model.ConnectionConfig) (*model.ConnectionInfo, error) - UpdateConnectionConfiguration(ctx context.Context, id string, config model.ConnectionConfig) (*model.ConnectionInfo, error) - DeleteConnectionConfiguration(ctx context.Context, id string) (*bool, error) - GetConnectionSubjectAccess(ctx context.Context, connectionID *string) ([]*model.AdminConnectionGrantInfo, error) - SetConnectionSubjectAccess(ctx context.Context, connectionID string, subjects []string) (*bool, error) - GetSubjectConnectionAccess(ctx context.Context, subjectID *string) ([]*model.AdminConnectionGrantInfo, error) - SetSubjectConnectionAccess(ctx context.Context, subjectID string, connections []string) (*bool, error) - ListFeatureSets(ctx context.Context) ([]*model.WebFeatureSet, error) - ListAuthProviderConfigurationParameters(ctx context.Context, providerID string) ([]*model.ObjectPropertyInfo, error) - ListAuthProviderConfigurations(ctx context.Context, providerID *string) ([]*model.AdminAuthProviderConfiguration, error) - SaveAuthProviderConfiguration(ctx context.Context, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters interface{}) (*model.AdminAuthProviderConfiguration, error) - DeleteAuthProviderConfiguration(ctx context.Context, id string) (bool, error) - SaveUserMetaParameter(ctx context.Context, id string, displayName string, description *string, required bool) (*model.ObjectPropertyInfo, error) - DeleteUserMetaParameter(ctx context.Context, id string) (bool, error) - SetUserMetaParameterValues(ctx context.Context, userID string, parameters interface{}) (bool, error) - ConfigureServer(ctx context.Context, configuration model.ServerConfigInput) (bool, error) - SetDefaultNavigatorSettings(ctx context.Context, settings model.NavigatorSettingsInput) (bool, error) - AuthLogin(ctx context.Context, provider string, configuration *string, credentials interface{}, linkUser *bool) (*model.AuthInfo, error) - AuthUpdateStatus(ctx context.Context, authID string, linkUser *bool) (*model.AuthInfo, error) - AuthLogout(ctx context.Context, provider *string, configuration *string) (*bool, error) - ActiveUser(ctx context.Context) (*model.UserInfo, error) - AuthProviders(ctx context.Context) ([]*model.AuthProviderInfo, error) - AuthChangeLocalPassword(ctx context.Context, oldPassword string, newPassword string) (bool, error) - ListUserProfileProperties(ctx context.Context) ([]*model.ObjectPropertyInfo, error) - ServerConfig(ctx context.Context) (*model.ServerConfig, error) - SessionState(ctx context.Context) (*model.SessionInfo, error) - SessionPermissions(ctx context.Context) ([]*string, error) - DriverList(ctx context.Context, id *string) ([]*model.DriverInfo, error) - AuthModels(ctx context.Context) ([]*model.DatabaseAuthModel, error) - NetworkHandlers(ctx context.Context) ([]*model.NetworkHandlerDescriptor, error) - UserConnections(ctx context.Context, id *string) ([]*model.ConnectionInfo, error) - TemplateConnections(ctx context.Context) ([]*model.ConnectionInfo, error) - ConnectionFolders(ctx context.Context, path *string) ([]*model.ConnectionFolderInfo, error) - ConnectionState(ctx context.Context, id string) (*model.ConnectionInfo, error) - ConnectionInfo(ctx context.Context, id string) (*model.ConnectionInfo, error) - ReadSessionLog(ctx context.Context, maxEntries *int, clearEntries *bool) ([]*model.LogEntry, error) - DataTransferAvailableStreamProcessors(ctx context.Context) ([]*model.DataTransferProcessorInfo, error) - DataTransferExportDataFromContainer(ctx context.Context, connectionID string, containerNodePath string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) - DataTransferExportDataFromResults(ctx context.Context, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) - DataTransferRemoveDataFile(ctx context.Context, dataFileID string) (*bool, error) - MetadataGetNodeDdl(ctx context.Context, nodeID string, options interface{}) (*string, error) - NavNodeChildren(ctx context.Context, parentPath string, offset *int, limit *int, onlyFolders *bool) ([]*model.NavigatorNodeInfo, error) - NavNodeParents(ctx context.Context, nodePath string) ([]*model.NavigatorNodeInfo, error) - NavNodeInfo(ctx context.Context, nodePath string) (*model.NavigatorNodeInfo, error) - NavRefreshNode(ctx context.Context, nodePath string) (*bool, error) - NavGetStructContainers(ctx context.Context, connectionID string, contextID *string, catalog *string) (*model.DatabaseStructContainers, error) - RmListProjects(ctx context.Context) ([]*model.RMProject, error) - RmListResources(ctx context.Context, projectID string, folder *string, nameMask *string, readProperties *bool, readHistory *bool) ([]*model.RMResource, error) - RmReadResourceAsString(ctx context.Context, projectID string, resourcePath string) (string, error) - SQLDialectInfo(ctx context.Context, connectionID string) (*model.SQLDialectInfo, error) - SQLListContexts(ctx context.Context, connectionID *string, contextID *string) ([]*model.SQLContextInfo, error) - SQLCompletionProposals(ctx context.Context, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) ([]*model.SQLCompletionProposal, error) - SQLFormatQuery(ctx context.Context, connectionID string, contextID string, query string) (string, error) - SQLSupportedOperations(ctx context.Context, connectionID string, contextID string, resultsID string, attributeIndex int) ([]*model.DataTypeLogicalOperation, error) - SQLEntityQueryGenerators(ctx context.Context, nodePathList []string) ([]*model.SQLQueryGenerator, error) - SQLGenerateEntityQuery(ctx context.Context, generatorID string, options interface{}, nodePathList []string) (string, error) - SQLParseScript(ctx context.Context, connectionID string, script string) (*model.SQLScriptInfo, error) - SQLParseQuery(ctx context.Context, connectionID string, script string, position int) (*model.SQLScriptQuery, error) -} - -type executableSchema struct { - resolvers ResolverRoot - directives DirectiveRoot - complexity ComplexityRoot -} - -func (e *executableSchema) Schema() *ast.Schema { - return parsedSchema -} - -func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { - ec := executionContext{nil, e} - _ = ec - switch typeName + "." + field { - - case "AdminAuthProviderConfiguration.description": - if e.complexity.AdminAuthProviderConfiguration.Description == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.Description(childComplexity), true - - case "AdminAuthProviderConfiguration.disabled": - if e.complexity.AdminAuthProviderConfiguration.Disabled == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.Disabled(childComplexity), true - - case "AdminAuthProviderConfiguration.displayName": - if e.complexity.AdminAuthProviderConfiguration.DisplayName == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.DisplayName(childComplexity), true - - case "AdminAuthProviderConfiguration.id": - if e.complexity.AdminAuthProviderConfiguration.ID == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.ID(childComplexity), true - - case "AdminAuthProviderConfiguration.iconURL": - if e.complexity.AdminAuthProviderConfiguration.IconURL == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.IconURL(childComplexity), true - - case "AdminAuthProviderConfiguration.metadataLink": - if e.complexity.AdminAuthProviderConfiguration.MetadataLink == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.MetadataLink(childComplexity), true - - case "AdminAuthProviderConfiguration.parameters": - if e.complexity.AdminAuthProviderConfiguration.Parameters == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.Parameters(childComplexity), true - - case "AdminAuthProviderConfiguration.providerId": - if e.complexity.AdminAuthProviderConfiguration.ProviderID == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.ProviderID(childComplexity), true - - case "AdminAuthProviderConfiguration.redirectLink": - if e.complexity.AdminAuthProviderConfiguration.RedirectLink == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.RedirectLink(childComplexity), true - - case "AdminAuthProviderConfiguration.signInLink": - if e.complexity.AdminAuthProviderConfiguration.SignInLink == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.SignInLink(childComplexity), true - - case "AdminAuthProviderConfiguration.signOutLink": - if e.complexity.AdminAuthProviderConfiguration.SignOutLink == nil { - break - } - - return e.complexity.AdminAuthProviderConfiguration.SignOutLink(childComplexity), true - - case "AdminConnectionGrantInfo.connectionId": - if e.complexity.AdminConnectionGrantInfo.ConnectionID == nil { - break - } - - return e.complexity.AdminConnectionGrantInfo.ConnectionID(childComplexity), true - - case "AdminConnectionGrantInfo.dataSourceId": - if e.complexity.AdminConnectionGrantInfo.DataSourceID == nil { - break - } - - return e.complexity.AdminConnectionGrantInfo.DataSourceID(childComplexity), true - - case "AdminConnectionGrantInfo.subjectId": - if e.complexity.AdminConnectionGrantInfo.SubjectID == nil { - break - } - - return e.complexity.AdminConnectionGrantInfo.SubjectID(childComplexity), true - - case "AdminConnectionGrantInfo.subjectType": - if e.complexity.AdminConnectionGrantInfo.SubjectType == nil { - break - } - - return e.complexity.AdminConnectionGrantInfo.SubjectType(childComplexity), true - - case "AdminConnectionSearchInfo.defaultDriver": - if e.complexity.AdminConnectionSearchInfo.DefaultDriver == nil { - break - } - - return e.complexity.AdminConnectionSearchInfo.DefaultDriver(childComplexity), true - - case "AdminConnectionSearchInfo.displayName": - if e.complexity.AdminConnectionSearchInfo.DisplayName == nil { - break - } - - return e.complexity.AdminConnectionSearchInfo.DisplayName(childComplexity), true - - case "AdminConnectionSearchInfo.host": - if e.complexity.AdminConnectionSearchInfo.Host == nil { - break - } - - return e.complexity.AdminConnectionSearchInfo.Host(childComplexity), true - - case "AdminConnectionSearchInfo.port": - if e.complexity.AdminConnectionSearchInfo.Port == nil { - break - } - - return e.complexity.AdminConnectionSearchInfo.Port(childComplexity), true - - case "AdminConnectionSearchInfo.possibleDrivers": - if e.complexity.AdminConnectionSearchInfo.PossibleDrivers == nil { - break - } - - return e.complexity.AdminConnectionSearchInfo.PossibleDrivers(childComplexity), true - - case "AdminPermissionInfo.category": - if e.complexity.AdminPermissionInfo.Category == nil { - break - } - - return e.complexity.AdminPermissionInfo.Category(childComplexity), true - - case "AdminPermissionInfo.description": - if e.complexity.AdminPermissionInfo.Description == nil { - break - } - - return e.complexity.AdminPermissionInfo.Description(childComplexity), true - - case "AdminPermissionInfo.id": - if e.complexity.AdminPermissionInfo.ID == nil { - break - } - - return e.complexity.AdminPermissionInfo.ID(childComplexity), true - - case "AdminPermissionInfo.label": - if e.complexity.AdminPermissionInfo.Label == nil { - break - } - - return e.complexity.AdminPermissionInfo.Label(childComplexity), true - - case "AdminPermissionInfo.provider": - if e.complexity.AdminPermissionInfo.Provider == nil { - break - } - - return e.complexity.AdminPermissionInfo.Provider(childComplexity), true - - case "AdminRoleInfo.description": - if e.complexity.AdminRoleInfo.Description == nil { - break - } - - return e.complexity.AdminRoleInfo.Description(childComplexity), true - - case "AdminRoleInfo.grantedConnections": - if e.complexity.AdminRoleInfo.GrantedConnections == nil { - break - } - - return e.complexity.AdminRoleInfo.GrantedConnections(childComplexity), true - - case "AdminRoleInfo.grantedUsers": - if e.complexity.AdminRoleInfo.GrantedUsers == nil { - break - } - - return e.complexity.AdminRoleInfo.GrantedUsers(childComplexity), true - - case "AdminRoleInfo.roleId": - if e.complexity.AdminRoleInfo.RoleID == nil { - break - } - - return e.complexity.AdminRoleInfo.RoleID(childComplexity), true - - case "AdminRoleInfo.roleName": - if e.complexity.AdminRoleInfo.RoleName == nil { - break - } - - return e.complexity.AdminRoleInfo.RoleName(childComplexity), true - - case "AdminRoleInfo.rolePermissions": - if e.complexity.AdminRoleInfo.RolePermissions == nil { - break - } - - return e.complexity.AdminRoleInfo.RolePermissions(childComplexity), true - - case "AdminUserInfo.configurationParameters": - if e.complexity.AdminUserInfo.ConfigurationParameters == nil { - break - } - - return e.complexity.AdminUserInfo.ConfigurationParameters(childComplexity), true - - case "AdminUserInfo.enabled": - if e.complexity.AdminUserInfo.Enabled == nil { - break - } - - return e.complexity.AdminUserInfo.Enabled(childComplexity), true - - case "AdminUserInfo.grantedConnections": - if e.complexity.AdminUserInfo.GrantedConnections == nil { - break - } - - return e.complexity.AdminUserInfo.GrantedConnections(childComplexity), true - - case "AdminUserInfo.grantedRoles": - if e.complexity.AdminUserInfo.GrantedRoles == nil { - break - } - - return e.complexity.AdminUserInfo.GrantedRoles(childComplexity), true - - case "AdminUserInfo.linkedAuthProviders": - if e.complexity.AdminUserInfo.LinkedAuthProviders == nil { - break - } - - return e.complexity.AdminUserInfo.LinkedAuthProviders(childComplexity), true - - case "AdminUserInfo.metaParameters": - if e.complexity.AdminUserInfo.MetaParameters == nil { - break - } - - return e.complexity.AdminUserInfo.MetaParameters(childComplexity), true - - case "AdminUserInfo.origins": - if e.complexity.AdminUserInfo.Origins == nil { - break - } - - return e.complexity.AdminUserInfo.Origins(childComplexity), true - - case "AdminUserInfo.userId": - if e.complexity.AdminUserInfo.UserID == nil { - break - } - - return e.complexity.AdminUserInfo.UserID(childComplexity), true - - case "AsyncTaskInfo.error": - if e.complexity.AsyncTaskInfo.Error == nil { - break - } - - return e.complexity.AsyncTaskInfo.Error(childComplexity), true - - case "AsyncTaskInfo.id": - if e.complexity.AsyncTaskInfo.ID == nil { - break - } - - return e.complexity.AsyncTaskInfo.ID(childComplexity), true - - case "AsyncTaskInfo.name": - if e.complexity.AsyncTaskInfo.Name == nil { - break - } - - return e.complexity.AsyncTaskInfo.Name(childComplexity), true - - case "AsyncTaskInfo.result": - if e.complexity.AsyncTaskInfo.Result == nil { - break - } - - return e.complexity.AsyncTaskInfo.Result(childComplexity), true - - case "AsyncTaskInfo.running": - if e.complexity.AsyncTaskInfo.Running == nil { - break - } - - return e.complexity.AsyncTaskInfo.Running(childComplexity), true - - case "AsyncTaskInfo.status": - if e.complexity.AsyncTaskInfo.Status == nil { - break - } - - return e.complexity.AsyncTaskInfo.Status(childComplexity), true - - case "AsyncTaskInfo.taskResult": - if e.complexity.AsyncTaskInfo.TaskResult == nil { - break - } - - return e.complexity.AsyncTaskInfo.TaskResult(childComplexity), true - - case "AuthCredentialInfo.admin": - if e.complexity.AuthCredentialInfo.Admin == nil { - break - } - - return e.complexity.AuthCredentialInfo.Admin(childComplexity), true - - case "AuthCredentialInfo.description": - if e.complexity.AuthCredentialInfo.Description == nil { - break - } - - return e.complexity.AuthCredentialInfo.Description(childComplexity), true - - case "AuthCredentialInfo.displayName": - if e.complexity.AuthCredentialInfo.DisplayName == nil { - break - } - - return e.complexity.AuthCredentialInfo.DisplayName(childComplexity), true - - case "AuthCredentialInfo.encryption": - if e.complexity.AuthCredentialInfo.Encryption == nil { - break - } - - return e.complexity.AuthCredentialInfo.Encryption(childComplexity), true - - case "AuthCredentialInfo.id": - if e.complexity.AuthCredentialInfo.ID == nil { - break - } - - return e.complexity.AuthCredentialInfo.ID(childComplexity), true - - case "AuthCredentialInfo.identifying": - if e.complexity.AuthCredentialInfo.Identifying == nil { - break - } - - return e.complexity.AuthCredentialInfo.Identifying(childComplexity), true - - case "AuthCredentialInfo.possibleValues": - if e.complexity.AuthCredentialInfo.PossibleValues == nil { - break - } - - return e.complexity.AuthCredentialInfo.PossibleValues(childComplexity), true - - case "AuthCredentialInfo.user": - if e.complexity.AuthCredentialInfo.User == nil { - break - } - - return e.complexity.AuthCredentialInfo.User(childComplexity), true - - case "AuthInfo.authId": - if e.complexity.AuthInfo.AuthID == nil { - break - } - - return e.complexity.AuthInfo.AuthID(childComplexity), true - - case "AuthInfo.authStatus": - if e.complexity.AuthInfo.AuthStatus == nil { - break - } - - return e.complexity.AuthInfo.AuthStatus(childComplexity), true - - case "AuthInfo.redirectLink": - if e.complexity.AuthInfo.RedirectLink == nil { - break - } - - return e.complexity.AuthInfo.RedirectLink(childComplexity), true - - case "AuthInfo.userTokens": - if e.complexity.AuthInfo.UserTokens == nil { - break - } - - return e.complexity.AuthInfo.UserTokens(childComplexity), true - - case "AuthProviderConfiguration.description": - if e.complexity.AuthProviderConfiguration.Description == nil { - break - } - - return e.complexity.AuthProviderConfiguration.Description(childComplexity), true - - case "AuthProviderConfiguration.disabled": - if e.complexity.AuthProviderConfiguration.Disabled == nil { - break - } - - return e.complexity.AuthProviderConfiguration.Disabled(childComplexity), true - - case "AuthProviderConfiguration.displayName": - if e.complexity.AuthProviderConfiguration.DisplayName == nil { - break - } - - return e.complexity.AuthProviderConfiguration.DisplayName(childComplexity), true - - case "AuthProviderConfiguration.id": - if e.complexity.AuthProviderConfiguration.ID == nil { - break - } - - return e.complexity.AuthProviderConfiguration.ID(childComplexity), true - - case "AuthProviderConfiguration.iconURL": - if e.complexity.AuthProviderConfiguration.IconURL == nil { - break - } - - return e.complexity.AuthProviderConfiguration.IconURL(childComplexity), true - - case "AuthProviderConfiguration.metadataLink": - if e.complexity.AuthProviderConfiguration.MetadataLink == nil { - break - } - - return e.complexity.AuthProviderConfiguration.MetadataLink(childComplexity), true - - case "AuthProviderConfiguration.signInLink": - if e.complexity.AuthProviderConfiguration.SignInLink == nil { - break - } - - return e.complexity.AuthProviderConfiguration.SignInLink(childComplexity), true - - case "AuthProviderConfiguration.signOutLink": - if e.complexity.AuthProviderConfiguration.SignOutLink == nil { - break - } - - return e.complexity.AuthProviderConfiguration.SignOutLink(childComplexity), true - - case "AuthProviderCredentialsProfile.credentialParameters": - if e.complexity.AuthProviderCredentialsProfile.CredentialParameters == nil { - break - } - - return e.complexity.AuthProviderCredentialsProfile.CredentialParameters(childComplexity), true - - case "AuthProviderCredentialsProfile.description": - if e.complexity.AuthProviderCredentialsProfile.Description == nil { - break - } - - return e.complexity.AuthProviderCredentialsProfile.Description(childComplexity), true - - case "AuthProviderCredentialsProfile.id": - if e.complexity.AuthProviderCredentialsProfile.ID == nil { - break - } - - return e.complexity.AuthProviderCredentialsProfile.ID(childComplexity), true - - case "AuthProviderCredentialsProfile.label": - if e.complexity.AuthProviderCredentialsProfile.Label == nil { - break - } - - return e.complexity.AuthProviderCredentialsProfile.Label(childComplexity), true - - case "AuthProviderInfo.configurable": - if e.complexity.AuthProviderInfo.Configurable == nil { - break - } - - return e.complexity.AuthProviderInfo.Configurable(childComplexity), true - - case "AuthProviderInfo.configurations": - if e.complexity.AuthProviderInfo.Configurations == nil { - break - } - - return e.complexity.AuthProviderInfo.Configurations(childComplexity), true - - case "AuthProviderInfo.credentialProfiles": - if e.complexity.AuthProviderInfo.CredentialProfiles == nil { - break - } - - return e.complexity.AuthProviderInfo.CredentialProfiles(childComplexity), true - - case "AuthProviderInfo.defaultProvider": - if e.complexity.AuthProviderInfo.DefaultProvider == nil { - break - } - - return e.complexity.AuthProviderInfo.DefaultProvider(childComplexity), true - - case "AuthProviderInfo.description": - if e.complexity.AuthProviderInfo.Description == nil { - break - } - - return e.complexity.AuthProviderInfo.Description(childComplexity), true - - case "AuthProviderInfo.id": - if e.complexity.AuthProviderInfo.ID == nil { - break - } - - return e.complexity.AuthProviderInfo.ID(childComplexity), true - - case "AuthProviderInfo.icon": - if e.complexity.AuthProviderInfo.Icon == nil { - break - } - - return e.complexity.AuthProviderInfo.Icon(childComplexity), true - - case "AuthProviderInfo.label": - if e.complexity.AuthProviderInfo.Label == nil { - break - } - - return e.complexity.AuthProviderInfo.Label(childComplexity), true - - case "AuthProviderInfo.requiredFeatures": - if e.complexity.AuthProviderInfo.RequiredFeatures == nil { - break - } - - return e.complexity.AuthProviderInfo.RequiredFeatures(childComplexity), true - - case "ConnectionFolderInfo.description": - if e.complexity.ConnectionFolderInfo.Description == nil { - break - } - - return e.complexity.ConnectionFolderInfo.Description(childComplexity), true - - case "ConnectionFolderInfo.id": - if e.complexity.ConnectionFolderInfo.ID == nil { - break - } - - return e.complexity.ConnectionFolderInfo.ID(childComplexity), true - - case "ConnectionInfo.authModel": - if e.complexity.ConnectionInfo.AuthModel == nil { - break - } - - return e.complexity.ConnectionInfo.AuthModel(childComplexity), true - - case "ConnectionInfo.authNeeded": - if e.complexity.ConnectionInfo.AuthNeeded == nil { - break - } - - return e.complexity.ConnectionInfo.AuthNeeded(childComplexity), true - - case "ConnectionInfo.authProperties": - if e.complexity.ConnectionInfo.AuthProperties == nil { - break - } - - return e.complexity.ConnectionInfo.AuthProperties(childComplexity), true - - case "ConnectionInfo.clientVersion": - if e.complexity.ConnectionInfo.ClientVersion == nil { - break - } - - return e.complexity.ConnectionInfo.ClientVersion(childComplexity), true - - case "ConnectionInfo.connectTime": - if e.complexity.ConnectionInfo.ConnectTime == nil { - break - } - - return e.complexity.ConnectionInfo.ConnectTime(childComplexity), true - - case "ConnectionInfo.connected": - if e.complexity.ConnectionInfo.Connected == nil { - break - } - - return e.complexity.ConnectionInfo.Connected(childComplexity), true - - case "ConnectionInfo.connectionError": - if e.complexity.ConnectionInfo.ConnectionError == nil { - break - } - - return e.complexity.ConnectionInfo.ConnectionError(childComplexity), true - - case "ConnectionInfo.databaseName": - if e.complexity.ConnectionInfo.DatabaseName == nil { - break - } - - return e.complexity.ConnectionInfo.DatabaseName(childComplexity), true - - case "ConnectionInfo.description": - if e.complexity.ConnectionInfo.Description == nil { - break - } - - return e.complexity.ConnectionInfo.Description(childComplexity), true - - case "ConnectionInfo.driverId": - if e.complexity.ConnectionInfo.DriverID == nil { - break - } - - return e.complexity.ConnectionInfo.DriverID(childComplexity), true - - case "ConnectionInfo.features": - if e.complexity.ConnectionInfo.Features == nil { - break - } - - return e.complexity.ConnectionInfo.Features(childComplexity), true - - case "ConnectionInfo.folder": - if e.complexity.ConnectionInfo.Folder == nil { - break - } - - return e.complexity.ConnectionInfo.Folder(childComplexity), true - - case "ConnectionInfo.host": - if e.complexity.ConnectionInfo.Host == nil { - break - } - - return e.complexity.ConnectionInfo.Host(childComplexity), true - - case "ConnectionInfo.id": - if e.complexity.ConnectionInfo.ID == nil { - break - } - - return e.complexity.ConnectionInfo.ID(childComplexity), true - - case "ConnectionInfo.name": - if e.complexity.ConnectionInfo.Name == nil { - break - } - - return e.complexity.ConnectionInfo.Name(childComplexity), true - - case "ConnectionInfo.navigatorSettings": - if e.complexity.ConnectionInfo.NavigatorSettings == nil { - break - } - - return e.complexity.ConnectionInfo.NavigatorSettings(childComplexity), true - - case "ConnectionInfo.networkHandlersConfig": - if e.complexity.ConnectionInfo.NetworkHandlersConfig == nil { - break - } - - return e.complexity.ConnectionInfo.NetworkHandlersConfig(childComplexity), true - - case "ConnectionInfo.nodePath": - if e.complexity.ConnectionInfo.NodePath == nil { - break - } - - return e.complexity.ConnectionInfo.NodePath(childComplexity), true - - case "ConnectionInfo.origin": - if e.complexity.ConnectionInfo.Origin == nil { - break - } - - return e.complexity.ConnectionInfo.Origin(childComplexity), true - - case "ConnectionInfo.port": - if e.complexity.ConnectionInfo.Port == nil { - break - } - - return e.complexity.ConnectionInfo.Port(childComplexity), true - - case "ConnectionInfo.properties": - if e.complexity.ConnectionInfo.Properties == nil { - break - } - - return e.complexity.ConnectionInfo.Properties(childComplexity), true - - case "ConnectionInfo.provided": - if e.complexity.ConnectionInfo.Provided == nil { - break - } - - return e.complexity.ConnectionInfo.Provided(childComplexity), true - - case "ConnectionInfo.providerProperties": - if e.complexity.ConnectionInfo.ProviderProperties == nil { - break - } - - return e.complexity.ConnectionInfo.ProviderProperties(childComplexity), true - - case "ConnectionInfo.readOnly": - if e.complexity.ConnectionInfo.ReadOnly == nil { - break - } - - return e.complexity.ConnectionInfo.ReadOnly(childComplexity), true - - case "ConnectionInfo.saveCredentials": - if e.complexity.ConnectionInfo.SaveCredentials == nil { - break - } - - return e.complexity.ConnectionInfo.SaveCredentials(childComplexity), true - - case "ConnectionInfo.serverName": - if e.complexity.ConnectionInfo.ServerName == nil { - break - } - - return e.complexity.ConnectionInfo.ServerName(childComplexity), true - - case "ConnectionInfo.serverVersion": - if e.complexity.ConnectionInfo.ServerVersion == nil { - break - } - - return e.complexity.ConnectionInfo.ServerVersion(childComplexity), true - - case "ConnectionInfo.supportedDataFormats": - if e.complexity.ConnectionInfo.SupportedDataFormats == nil { - break - } - - return e.complexity.ConnectionInfo.SupportedDataFormats(childComplexity), true - - case "ConnectionInfo.template": - if e.complexity.ConnectionInfo.Template == nil { - break - } - - return e.complexity.ConnectionInfo.Template(childComplexity), true - - case "ConnectionInfo.url": - if e.complexity.ConnectionInfo.URL == nil { - break - } - - return e.complexity.ConnectionInfo.URL(childComplexity), true - - case "ConnectionInfo.useUrl": - if e.complexity.ConnectionInfo.UseURL == nil { - break - } - - return e.complexity.ConnectionInfo.UseURL(childComplexity), true - - case "DataTransferProcessorInfo.appFileExtension": - if e.complexity.DataTransferProcessorInfo.AppFileExtension == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.AppFileExtension(childComplexity), true - - case "DataTransferProcessorInfo.appName": - if e.complexity.DataTransferProcessorInfo.AppName == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.AppName(childComplexity), true - - case "DataTransferProcessorInfo.description": - if e.complexity.DataTransferProcessorInfo.Description == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.Description(childComplexity), true - - case "DataTransferProcessorInfo.fileExtension": - if e.complexity.DataTransferProcessorInfo.FileExtension == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.FileExtension(childComplexity), true - - case "DataTransferProcessorInfo.id": - if e.complexity.DataTransferProcessorInfo.ID == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.ID(childComplexity), true - - case "DataTransferProcessorInfo.icon": - if e.complexity.DataTransferProcessorInfo.Icon == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.Icon(childComplexity), true - - case "DataTransferProcessorInfo.isBinary": - if e.complexity.DataTransferProcessorInfo.IsBinary == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.IsBinary(childComplexity), true - - case "DataTransferProcessorInfo.isHTML": - if e.complexity.DataTransferProcessorInfo.IsHTML == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.IsHTML(childComplexity), true - - case "DataTransferProcessorInfo.name": - if e.complexity.DataTransferProcessorInfo.Name == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.Name(childComplexity), true - - case "DataTransferProcessorInfo.order": - if e.complexity.DataTransferProcessorInfo.Order == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.Order(childComplexity), true - - case "DataTransferProcessorInfo.properties": - if e.complexity.DataTransferProcessorInfo.Properties == nil { - break - } - - return e.complexity.DataTransferProcessorInfo.Properties(childComplexity), true - - case "DataTypeLogicalOperation.argumentCount": - if e.complexity.DataTypeLogicalOperation.ArgumentCount == nil { - break - } - - return e.complexity.DataTypeLogicalOperation.ArgumentCount(childComplexity), true - - case "DataTypeLogicalOperation.expression": - if e.complexity.DataTypeLogicalOperation.Expression == nil { - break - } - - return e.complexity.DataTypeLogicalOperation.Expression(childComplexity), true - - case "DataTypeLogicalOperation.id": - if e.complexity.DataTypeLogicalOperation.ID == nil { - break - } - - return e.complexity.DataTypeLogicalOperation.ID(childComplexity), true - - case "DatabaseAuthModel.description": - if e.complexity.DatabaseAuthModel.Description == nil { - break - } - - return e.complexity.DatabaseAuthModel.Description(childComplexity), true - - case "DatabaseAuthModel.displayName": - if e.complexity.DatabaseAuthModel.DisplayName == nil { - break - } - - return e.complexity.DatabaseAuthModel.DisplayName(childComplexity), true - - case "DatabaseAuthModel.id": - if e.complexity.DatabaseAuthModel.ID == nil { - break - } - - return e.complexity.DatabaseAuthModel.ID(childComplexity), true - - case "DatabaseAuthModel.icon": - if e.complexity.DatabaseAuthModel.Icon == nil { - break - } - - return e.complexity.DatabaseAuthModel.Icon(childComplexity), true - - case "DatabaseAuthModel.properties": - if e.complexity.DatabaseAuthModel.Properties == nil { - break - } - - return e.complexity.DatabaseAuthModel.Properties(childComplexity), true - - case "DatabaseAuthModel.requiresLocalConfiguration": - if e.complexity.DatabaseAuthModel.RequiresLocalConfiguration == nil { - break - } - - return e.complexity.DatabaseAuthModel.RequiresLocalConfiguration(childComplexity), true - - case "DatabaseCatalog.catalog": - if e.complexity.DatabaseCatalog.Catalog == nil { - break - } - - return e.complexity.DatabaseCatalog.Catalog(childComplexity), true - - case "DatabaseCatalog.schemaList": - if e.complexity.DatabaseCatalog.SchemaList == nil { - break - } - - return e.complexity.DatabaseCatalog.SchemaList(childComplexity), true - - case "DatabaseDocument.contentType": - if e.complexity.DatabaseDocument.ContentType == nil { - break - } - - return e.complexity.DatabaseDocument.ContentType(childComplexity), true - - case "DatabaseDocument.data": - if e.complexity.DatabaseDocument.Data == nil { - break - } - - return e.complexity.DatabaseDocument.Data(childComplexity), true - - case "DatabaseDocument.id": - if e.complexity.DatabaseDocument.ID == nil { - break - } - - return e.complexity.DatabaseDocument.ID(childComplexity), true - - case "DatabaseDocument.properties": - if e.complexity.DatabaseDocument.Properties == nil { - break - } - - return e.complexity.DatabaseDocument.Properties(childComplexity), true - - case "DatabaseObjectInfo.description": - if e.complexity.DatabaseObjectInfo.Description == nil { - break - } - - return e.complexity.DatabaseObjectInfo.Description(childComplexity), true - - case "DatabaseObjectInfo.editors": - if e.complexity.DatabaseObjectInfo.Editors == nil { - break - } - - return e.complexity.DatabaseObjectInfo.Editors(childComplexity), true - - case "DatabaseObjectInfo.features": - if e.complexity.DatabaseObjectInfo.Features == nil { - break - } - - return e.complexity.DatabaseObjectInfo.Features(childComplexity), true - - case "DatabaseObjectInfo.fullyQualifiedName": - if e.complexity.DatabaseObjectInfo.FullyQualifiedName == nil { - break - } - - return e.complexity.DatabaseObjectInfo.FullyQualifiedName(childComplexity), true - - case "DatabaseObjectInfo.name": - if e.complexity.DatabaseObjectInfo.Name == nil { - break - } - - return e.complexity.DatabaseObjectInfo.Name(childComplexity), true - - case "DatabaseObjectInfo.ordinalPosition": - if e.complexity.DatabaseObjectInfo.OrdinalPosition == nil { - break - } - - return e.complexity.DatabaseObjectInfo.OrdinalPosition(childComplexity), true - - case "DatabaseObjectInfo.overloadedName": - if e.complexity.DatabaseObjectInfo.OverloadedName == nil { - break - } - - return e.complexity.DatabaseObjectInfo.OverloadedName(childComplexity), true - - case "DatabaseObjectInfo.properties": - if e.complexity.DatabaseObjectInfo.Properties == nil { - break - } - - args, err := ec.field_DatabaseObjectInfo_properties_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.DatabaseObjectInfo.Properties(childComplexity, args["filter"].(*model.ObjectPropertyFilter)), true - - case "DatabaseObjectInfo.state": - if e.complexity.DatabaseObjectInfo.State == nil { - break - } - - return e.complexity.DatabaseObjectInfo.State(childComplexity), true - - case "DatabaseObjectInfo.type": - if e.complexity.DatabaseObjectInfo.Type == nil { - break - } - - return e.complexity.DatabaseObjectInfo.Type(childComplexity), true - - case "DatabaseObjectInfo.uniqueName": - if e.complexity.DatabaseObjectInfo.UniqueName == nil { - break - } - - return e.complexity.DatabaseObjectInfo.UniqueName(childComplexity), true - - case "DatabaseStructContainers.catalogList": - if e.complexity.DatabaseStructContainers.CatalogList == nil { - break - } - - return e.complexity.DatabaseStructContainers.CatalogList(childComplexity), true - - case "DatabaseStructContainers.schemaList": - if e.complexity.DatabaseStructContainers.SchemaList == nil { - break - } - - return e.complexity.DatabaseStructContainers.SchemaList(childComplexity), true - - case "DatabaseStructContainers.supportsCatalogChange": - if e.complexity.DatabaseStructContainers.SupportsCatalogChange == nil { - break - } - - return e.complexity.DatabaseStructContainers.SupportsCatalogChange(childComplexity), true - - case "DatabaseStructContainers.supportsSchemaChange": - if e.complexity.DatabaseStructContainers.SupportsSchemaChange == nil { - break - } - - return e.complexity.DatabaseStructContainers.SupportsSchemaChange(childComplexity), true - - case "DriverInfo.allowsEmptyPassword": - if e.complexity.DriverInfo.AllowsEmptyPassword == nil { - break - } - - return e.complexity.DriverInfo.AllowsEmptyPassword(childComplexity), true - - case "DriverInfo.anonymousAccess": - if e.complexity.DriverInfo.AnonymousAccess == nil { - break - } - - return e.complexity.DriverInfo.AnonymousAccess(childComplexity), true - - case "DriverInfo.applicableAuthModels": - if e.complexity.DriverInfo.ApplicableAuthModels == nil { - break - } - - return e.complexity.DriverInfo.ApplicableAuthModels(childComplexity), true - - case "DriverInfo.applicableNetworkHandlers": - if e.complexity.DriverInfo.ApplicableNetworkHandlers == nil { - break - } - - return e.complexity.DriverInfo.ApplicableNetworkHandlers(childComplexity), true - - case "DriverInfo.custom": - if e.complexity.DriverInfo.Custom == nil { - break - } - - return e.complexity.DriverInfo.Custom(childComplexity), true - - case "DriverInfo.defaultAuthModel": - if e.complexity.DriverInfo.DefaultAuthModel == nil { - break - } - - return e.complexity.DriverInfo.DefaultAuthModel(childComplexity), true - - case "DriverInfo.defaultDatabase": - if e.complexity.DriverInfo.DefaultDatabase == nil { - break - } - - return e.complexity.DriverInfo.DefaultDatabase(childComplexity), true - - case "DriverInfo.defaultHost": - if e.complexity.DriverInfo.DefaultHost == nil { - break - } - - return e.complexity.DriverInfo.DefaultHost(childComplexity), true - - case "DriverInfo.defaultPort": - if e.complexity.DriverInfo.DefaultPort == nil { - break - } - - return e.complexity.DriverInfo.DefaultPort(childComplexity), true - - case "DriverInfo.defaultServer": - if e.complexity.DriverInfo.DefaultServer == nil { - break - } - - return e.complexity.DriverInfo.DefaultServer(childComplexity), true - - case "DriverInfo.defaultUser": - if e.complexity.DriverInfo.DefaultUser == nil { - break - } - - return e.complexity.DriverInfo.DefaultUser(childComplexity), true - - case "DriverInfo.description": - if e.complexity.DriverInfo.Description == nil { - break - } - - return e.complexity.DriverInfo.Description(childComplexity), true - - case "DriverInfo.driverClassName": - if e.complexity.DriverInfo.DriverClassName == nil { - break - } - - return e.complexity.DriverInfo.DriverClassName(childComplexity), true - - case "DriverInfo.driverInfoURL": - if e.complexity.DriverInfo.DriverInfoURL == nil { - break - } - - return e.complexity.DriverInfo.DriverInfoURL(childComplexity), true - - case "DriverInfo.driverParameters": - if e.complexity.DriverInfo.DriverParameters == nil { - break - } - - return e.complexity.DriverInfo.DriverParameters(childComplexity), true - - case "DriverInfo.driverProperties": - if e.complexity.DriverInfo.DriverProperties == nil { - break - } - - return e.complexity.DriverInfo.DriverProperties(childComplexity), true - - case "DriverInfo.driverPropertiesURL": - if e.complexity.DriverInfo.DriverPropertiesURL == nil { - break - } - - return e.complexity.DriverInfo.DriverPropertiesURL(childComplexity), true - - case "DriverInfo.embedded": - if e.complexity.DriverInfo.Embedded == nil { - break - } - - return e.complexity.DriverInfo.Embedded(childComplexity), true - - case "DriverInfo.enabled": - if e.complexity.DriverInfo.Enabled == nil { - break - } - - return e.complexity.DriverInfo.Enabled(childComplexity), true - - case "DriverInfo.id": - if e.complexity.DriverInfo.ID == nil { - break - } - - return e.complexity.DriverInfo.ID(childComplexity), true - - case "DriverInfo.icon": - if e.complexity.DriverInfo.Icon == nil { - break - } - - return e.complexity.DriverInfo.Icon(childComplexity), true - - case "DriverInfo.iconBig": - if e.complexity.DriverInfo.IconBig == nil { - break - } - - return e.complexity.DriverInfo.IconBig(childComplexity), true - - case "DriverInfo.license": - if e.complexity.DriverInfo.License == nil { - break - } - - return e.complexity.DriverInfo.License(childComplexity), true - - case "DriverInfo.licenseRequired": - if e.complexity.DriverInfo.LicenseRequired == nil { - break - } - - return e.complexity.DriverInfo.LicenseRequired(childComplexity), true - - case "DriverInfo.name": - if e.complexity.DriverInfo.Name == nil { - break - } - - return e.complexity.DriverInfo.Name(childComplexity), true - - case "DriverInfo.promotedScore": - if e.complexity.DriverInfo.PromotedScore == nil { - break - } - - return e.complexity.DriverInfo.PromotedScore(childComplexity), true - - case "DriverInfo.providerId": - if e.complexity.DriverInfo.ProviderID == nil { - break - } - - return e.complexity.DriverInfo.ProviderID(childComplexity), true - - case "DriverInfo.providerProperties": - if e.complexity.DriverInfo.ProviderProperties == nil { - break - } - - return e.complexity.DriverInfo.ProviderProperties(childComplexity), true - - case "DriverInfo.requiresServerName": - if e.complexity.DriverInfo.RequiresServerName == nil { - break - } - - return e.complexity.DriverInfo.RequiresServerName(childComplexity), true - - case "DriverInfo.sampleURL": - if e.complexity.DriverInfo.SampleURL == nil { - break - } - - return e.complexity.DriverInfo.SampleURL(childComplexity), true - - case "LogEntry.message": - if e.complexity.LogEntry.Message == nil { - break - } - - return e.complexity.LogEntry.Message(childComplexity), true - - case "LogEntry.stackTrace": - if e.complexity.LogEntry.StackTrace == nil { - break - } - - return e.complexity.LogEntry.StackTrace(childComplexity), true - - case "LogEntry.time": - if e.complexity.LogEntry.Time == nil { - break - } - - return e.complexity.LogEntry.Time(childComplexity), true - - case "LogEntry.type": - if e.complexity.LogEntry.Type == nil { - break - } - - return e.complexity.LogEntry.Type(childComplexity), true - - case "Mutation.asyncReadDataFromContainer": - if e.complexity.Mutation.AsyncReadDataFromContainer == nil { - break - } - - args, err := ec.field_Mutation_asyncReadDataFromContainer_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.AsyncReadDataFromContainer(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["containerNodePath"].(string), args["resultId"].(*string), args["filter"].(*model.SQLDataFilter), args["dataFormat"].(*model.ResultDataFormat)), true - - case "Mutation.asyncSqlExecuteQuery": - if e.complexity.Mutation.AsyncSQLExecuteQuery == nil { - break - } - - args, err := ec.field_Mutation_asyncSqlExecuteQuery_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.AsyncSQLExecuteQuery(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["sql"].(string), args["resultId"].(*string), args["filter"].(*model.SQLDataFilter), args["dataFormat"].(*model.ResultDataFormat), args["readLogs"].(*bool)), true - - case "Mutation.asyncSqlExecuteResults": - if e.complexity.Mutation.AsyncSQLExecuteResults == nil { - break - } - - args, err := ec.field_Mutation_asyncSqlExecuteResults_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.AsyncSQLExecuteResults(childComplexity, args["taskId"].(string)), true - - case "Mutation.asyncSqlExplainExecutionPlan": - if e.complexity.Mutation.AsyncSQLExplainExecutionPlan == nil { - break - } - - args, err := ec.field_Mutation_asyncSqlExplainExecutionPlan_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.AsyncSQLExplainExecutionPlan(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["query"].(string), args["configuration"].(interface{})), true - - case "Mutation.asyncSqlExplainExecutionPlanResult": - if e.complexity.Mutation.AsyncSQLExplainExecutionPlanResult == nil { - break - } - - args, err := ec.field_Mutation_asyncSqlExplainExecutionPlanResult_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.AsyncSQLExplainExecutionPlanResult(childComplexity, args["taskId"].(string)), true - - case "Mutation.asyncTaskCancel": - if e.complexity.Mutation.AsyncTaskCancel == nil { - break - } - - args, err := ec.field_Mutation_asyncTaskCancel_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.AsyncTaskCancel(childComplexity, args["id"].(string)), true - - case "Mutation.asyncTaskInfo": - if e.complexity.Mutation.AsyncTaskInfo == nil { - break - } - - args, err := ec.field_Mutation_asyncTaskInfo_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.AsyncTaskInfo(childComplexity, args["id"].(string), args["removeOnFinish"].(bool)), true - - case "Mutation.asyncTaskStatus": - if e.complexity.Mutation.AsyncTaskStatus == nil { - break - } - - args, err := ec.field_Mutation_asyncTaskStatus_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.AsyncTaskStatus(childComplexity, args["id"].(string)), true - - case "Mutation.changeSessionLanguage": - if e.complexity.Mutation.ChangeSessionLanguage == nil { - break - } - - args, err := ec.field_Mutation_changeSessionLanguage_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.ChangeSessionLanguage(childComplexity, args["locale"].(*string)), true - - case "Mutation.closeConnection": - if e.complexity.Mutation.CloseConnection == nil { - break - } - - args, err := ec.field_Mutation_closeConnection_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.CloseConnection(childComplexity, args["id"].(string)), true - - case "Mutation.closeSession": - if e.complexity.Mutation.CloseSession == nil { - break - } - - return e.complexity.Mutation.CloseSession(childComplexity), true - - case "Mutation.copyConnectionFromNode": - if e.complexity.Mutation.CopyConnectionFromNode == nil { - break - } - - args, err := ec.field_Mutation_copyConnectionFromNode_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.CopyConnectionFromNode(childComplexity, args["nodePath"].(string), args["config"].(*model.ConnectionConfig)), true - - case "Mutation.createConnection": - if e.complexity.Mutation.CreateConnection == nil { - break - } - - args, err := ec.field_Mutation_createConnection_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.CreateConnection(childComplexity, args["config"].(model.ConnectionConfig)), true - - case "Mutation.createConnectionFolder": - if e.complexity.Mutation.CreateConnectionFolder == nil { - break - } - - args, err := ec.field_Mutation_createConnectionFolder_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.CreateConnectionFolder(childComplexity, args["parentFolderPath"].(*string), args["folderName"].(string)), true - - case "Mutation.createConnectionFromTemplate": - if e.complexity.Mutation.CreateConnectionFromTemplate == nil { - break - } - - args, err := ec.field_Mutation_createConnectionFromTemplate_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.CreateConnectionFromTemplate(childComplexity, args["templateId"].(string), args["connectionName"].(*string)), true - - case "Mutation.deleteConnection": - if e.complexity.Mutation.DeleteConnection == nil { - break - } - - args, err := ec.field_Mutation_deleteConnection_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.DeleteConnection(childComplexity, args["id"].(string)), true - - case "Mutation.deleteConnectionFolder": - if e.complexity.Mutation.DeleteConnectionFolder == nil { - break - } - - args, err := ec.field_Mutation_deleteConnectionFolder_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.DeleteConnectionFolder(childComplexity, args["folderPath"].(string)), true - - case "Mutation.initConnection": - if e.complexity.Mutation.InitConnection == nil { - break - } - - args, err := ec.field_Mutation_initConnection_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.InitConnection(childComplexity, args["id"].(string), args["credentials"].(interface{}), args["networkCredentials"].([]*model.NetworkHandlerConfigInput), args["saveCredentials"].(*bool)), true - - case "Mutation.navDeleteNodes": - if e.complexity.Mutation.NavDeleteNodes == nil { - break - } - - args, err := ec.field_Mutation_navDeleteNodes_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.NavDeleteNodes(childComplexity, args["nodePaths"].([]string)), true - - case "Mutation.navMoveNodesToFolder": - if e.complexity.Mutation.NavMoveNodesToFolder == nil { - break - } - - args, err := ec.field_Mutation_navMoveNodesToFolder_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.NavMoveNodesToFolder(childComplexity, args["nodePaths"].([]string), args["folderPath"].(string)), true - - case "Mutation.navRenameNode": - if e.complexity.Mutation.NavRenameNode == nil { - break - } - - args, err := ec.field_Mutation_navRenameNode_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.NavRenameNode(childComplexity, args["nodePath"].(string), args["newName"].(string)), true - - case "Mutation.openConnection": - if e.complexity.Mutation.OpenConnection == nil { - break - } - - args, err := ec.field_Mutation_openConnection_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.OpenConnection(childComplexity, args["config"].(model.ConnectionConfig)), true - - case "Mutation.openSession": - if e.complexity.Mutation.OpenSession == nil { - break - } - - args, err := ec.field_Mutation_openSession_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.OpenSession(childComplexity, args["defaultLocale"].(*string)), true - - case "Mutation.readLobValue": - if e.complexity.Mutation.ReadLobValue == nil { - break - } - - args, err := ec.field_Mutation_readLobValue_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.ReadLobValue(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["lobColumnIndex"].(int), args["row"].([]*model.SQLResultRow)), true - - case "Mutation.refreshSessionConnections": - if e.complexity.Mutation.RefreshSessionConnections == nil { - break - } - - return e.complexity.Mutation.RefreshSessionConnections(childComplexity), true - - case "Mutation.rmCreateResource": - if e.complexity.Mutation.RmCreateResource == nil { - break - } - - args, err := ec.field_Mutation_rmCreateResource_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.RmCreateResource(childComplexity, args["projectId"].(string), args["resourcePath"].(string), args["isFolder"].(bool)), true - - case "Mutation.rmDeleteResource": - if e.complexity.Mutation.RmDeleteResource == nil { - break - } - - args, err := ec.field_Mutation_rmDeleteResource_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.RmDeleteResource(childComplexity, args["projectId"].(string), args["resourcePath"].(string), args["recursive"].(bool)), true - - case "Mutation.rmMoveResource": - if e.complexity.Mutation.RmMoveResource == nil { - break - } - - args, err := ec.field_Mutation_rmMoveResource_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.RmMoveResource(childComplexity, args["projectId"].(string), args["oldResourcePath"].(string), args["newResourcePath"].(*string)), true - - case "Mutation.rmWriteResourceStringContent": - if e.complexity.Mutation.RmWriteResourceStringContent == nil { - break - } - - args, err := ec.field_Mutation_rmWriteResourceStringContent_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.RmWriteResourceStringContent(childComplexity, args["projectId"].(string), args["resourcePath"].(string), args["data"].(string)), true - - case "Mutation.sqlContextCreate": - if e.complexity.Mutation.SQLContextCreate == nil { - break - } - - args, err := ec.field_Mutation_sqlContextCreate_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.SQLContextCreate(childComplexity, args["connectionId"].(string), args["defaultCatalog"].(*string), args["defaultSchema"].(*string)), true - - case "Mutation.sqlContextDestroy": - if e.complexity.Mutation.SQLContextDestroy == nil { - break - } - - args, err := ec.field_Mutation_sqlContextDestroy_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.SQLContextDestroy(childComplexity, args["connectionId"].(string), args["contextId"].(string)), true - - case "Mutation.sqlContextSetDefaults": - if e.complexity.Mutation.SQLContextSetDefaults == nil { - break - } - - args, err := ec.field_Mutation_sqlContextSetDefaults_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.SQLContextSetDefaults(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["defaultCatalog"].(*string), args["defaultSchema"].(*string)), true - - case "Mutation.sqlResultClose": - if e.complexity.Mutation.SQLResultClose == nil { - break - } - - args, err := ec.field_Mutation_sqlResultClose_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.SQLResultClose(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultId"].(string)), true - - case "Mutation.setConnectionNavigatorSettings": - if e.complexity.Mutation.SetConnectionNavigatorSettings == nil { - break - } - - args, err := ec.field_Mutation_setConnectionNavigatorSettings_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.SetConnectionNavigatorSettings(childComplexity, args["id"].(string), args["settings"].(model.NavigatorSettingsInput)), true - - case "Mutation.setUserConfigurationParameter": - if e.complexity.Mutation.SetUserConfigurationParameter == nil { - break - } - - args, err := ec.field_Mutation_setUserConfigurationParameter_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.SetUserConfigurationParameter(childComplexity, args["name"].(string), args["value"].(interface{})), true - - case "Mutation.testConnection": - if e.complexity.Mutation.TestConnection == nil { - break - } - - args, err := ec.field_Mutation_testConnection_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.TestConnection(childComplexity, args["config"].(model.ConnectionConfig)), true - - case "Mutation.testNetworkHandler": - if e.complexity.Mutation.TestNetworkHandler == nil { - break - } - - args, err := ec.field_Mutation_testNetworkHandler_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.TestNetworkHandler(childComplexity, args["config"].(model.NetworkHandlerConfigInput)), true - - case "Mutation.touchSession": - if e.complexity.Mutation.TouchSession == nil { - break - } - - return e.complexity.Mutation.TouchSession(childComplexity), true - - case "Mutation.updateConnection": - if e.complexity.Mutation.UpdateConnection == nil { - break - } - - args, err := ec.field_Mutation_updateConnection_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.UpdateConnection(childComplexity, args["config"].(model.ConnectionConfig)), true - - case "Mutation.updateResultsDataBatch": - if e.complexity.Mutation.UpdateResultsDataBatch == nil { - break - } - - args, err := ec.field_Mutation_updateResultsDataBatch_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.UpdateResultsDataBatch(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["updatedRows"].([]*model.SQLResultRow), args["deletedRows"].([]*model.SQLResultRow), args["addedRows"].([]*model.SQLResultRow)), true - - case "Mutation.updateResultsDataBatchScript": - if e.complexity.Mutation.UpdateResultsDataBatchScript == nil { - break - } - - args, err := ec.field_Mutation_updateResultsDataBatchScript_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.UpdateResultsDataBatchScript(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["updatedRows"].([]*model.SQLResultRow), args["deletedRows"].([]*model.SQLResultRow), args["addedRows"].([]*model.SQLResultRow)), true - - case "NavigatorNodeInfo.description": - if e.complexity.NavigatorNodeInfo.Description == nil { - break - } - - return e.complexity.NavigatorNodeInfo.Description(childComplexity), true - - case "NavigatorNodeInfo.features": - if e.complexity.NavigatorNodeInfo.Features == nil { - break - } - - return e.complexity.NavigatorNodeInfo.Features(childComplexity), true - - case "NavigatorNodeInfo.folder": - if e.complexity.NavigatorNodeInfo.Folder == nil { - break - } - - return e.complexity.NavigatorNodeInfo.Folder(childComplexity), true - - case "NavigatorNodeInfo.fullName": - if e.complexity.NavigatorNodeInfo.FullName == nil { - break - } - - return e.complexity.NavigatorNodeInfo.FullName(childComplexity), true - - case "NavigatorNodeInfo.hasChildren": - if e.complexity.NavigatorNodeInfo.HasChildren == nil { - break - } - - return e.complexity.NavigatorNodeInfo.HasChildren(childComplexity), true - - case "NavigatorNodeInfo.id": - if e.complexity.NavigatorNodeInfo.ID == nil { - break - } - - return e.complexity.NavigatorNodeInfo.ID(childComplexity), true - - case "NavigatorNodeInfo.icon": - if e.complexity.NavigatorNodeInfo.Icon == nil { - break - } - - return e.complexity.NavigatorNodeInfo.Icon(childComplexity), true - - case "NavigatorNodeInfo.inline": - if e.complexity.NavigatorNodeInfo.Inline == nil { - break - } - - return e.complexity.NavigatorNodeInfo.Inline(childComplexity), true - - case "NavigatorNodeInfo.name": - if e.complexity.NavigatorNodeInfo.Name == nil { - break - } - - return e.complexity.NavigatorNodeInfo.Name(childComplexity), true - - case "NavigatorNodeInfo.navigable": - if e.complexity.NavigatorNodeInfo.Navigable == nil { - break - } - - return e.complexity.NavigatorNodeInfo.Navigable(childComplexity), true - - case "NavigatorNodeInfo.nodeDetails": - if e.complexity.NavigatorNodeInfo.NodeDetails == nil { - break - } - - return e.complexity.NavigatorNodeInfo.NodeDetails(childComplexity), true - - case "NavigatorNodeInfo.nodeType": - if e.complexity.NavigatorNodeInfo.NodeType == nil { - break - } - - return e.complexity.NavigatorNodeInfo.NodeType(childComplexity), true - - case "NavigatorNodeInfo.object": - if e.complexity.NavigatorNodeInfo.Object == nil { - break - } - - return e.complexity.NavigatorNodeInfo.Object(childComplexity), true - - case "NavigatorSettings.hideFolders": - if e.complexity.NavigatorSettings.HideFolders == nil { - break - } - - return e.complexity.NavigatorSettings.HideFolders(childComplexity), true - - case "NavigatorSettings.hideSchemas": - if e.complexity.NavigatorSettings.HideSchemas == nil { - break - } - - return e.complexity.NavigatorSettings.HideSchemas(childComplexity), true - - case "NavigatorSettings.hideVirtualModel": - if e.complexity.NavigatorSettings.HideVirtualModel == nil { - break - } - - return e.complexity.NavigatorSettings.HideVirtualModel(childComplexity), true - - case "NavigatorSettings.mergeEntities": - if e.complexity.NavigatorSettings.MergeEntities == nil { - break - } - - return e.complexity.NavigatorSettings.MergeEntities(childComplexity), true - - case "NavigatorSettings.showOnlyEntities": - if e.complexity.NavigatorSettings.ShowOnlyEntities == nil { - break - } - - return e.complexity.NavigatorSettings.ShowOnlyEntities(childComplexity), true - - case "NavigatorSettings.showSystemObjects": - if e.complexity.NavigatorSettings.ShowSystemObjects == nil { - break - } - - return e.complexity.NavigatorSettings.ShowSystemObjects(childComplexity), true - - case "NavigatorSettings.showUtilityObjects": - if e.complexity.NavigatorSettings.ShowUtilityObjects == nil { - break - } - - return e.complexity.NavigatorSettings.ShowUtilityObjects(childComplexity), true - - case "NetworkEndpointInfo.clientVersion": - if e.complexity.NetworkEndpointInfo.ClientVersion == nil { - break - } - - return e.complexity.NetworkEndpointInfo.ClientVersion(childComplexity), true - - case "NetworkEndpointInfo.message": - if e.complexity.NetworkEndpointInfo.Message == nil { - break - } - - return e.complexity.NetworkEndpointInfo.Message(childComplexity), true - - case "NetworkEndpointInfo.serverVersion": - if e.complexity.NetworkEndpointInfo.ServerVersion == nil { - break - } - - return e.complexity.NetworkEndpointInfo.ServerVersion(childComplexity), true - - case "NetworkHandlerConfig.authType": - if e.complexity.NetworkHandlerConfig.AuthType == nil { - break - } - - return e.complexity.NetworkHandlerConfig.AuthType(childComplexity), true - - case "NetworkHandlerConfig.enabled": - if e.complexity.NetworkHandlerConfig.Enabled == nil { - break - } - - return e.complexity.NetworkHandlerConfig.Enabled(childComplexity), true - - case "NetworkHandlerConfig.id": - if e.complexity.NetworkHandlerConfig.ID == nil { - break - } - - return e.complexity.NetworkHandlerConfig.ID(childComplexity), true - - case "NetworkHandlerConfig.key": - if e.complexity.NetworkHandlerConfig.Key == nil { - break - } - - return e.complexity.NetworkHandlerConfig.Key(childComplexity), true - - case "NetworkHandlerConfig.password": - if e.complexity.NetworkHandlerConfig.Password == nil { - break - } - - return e.complexity.NetworkHandlerConfig.Password(childComplexity), true - - case "NetworkHandlerConfig.properties": - if e.complexity.NetworkHandlerConfig.Properties == nil { - break - } - - return e.complexity.NetworkHandlerConfig.Properties(childComplexity), true - - case "NetworkHandlerConfig.savePassword": - if e.complexity.NetworkHandlerConfig.SavePassword == nil { - break - } - - return e.complexity.NetworkHandlerConfig.SavePassword(childComplexity), true - - case "NetworkHandlerConfig.userName": - if e.complexity.NetworkHandlerConfig.UserName == nil { - break - } - - return e.complexity.NetworkHandlerConfig.UserName(childComplexity), true - - case "NetworkHandlerDescriptor.codeName": - if e.complexity.NetworkHandlerDescriptor.CodeName == nil { - break - } - - return e.complexity.NetworkHandlerDescriptor.CodeName(childComplexity), true - - case "NetworkHandlerDescriptor.description": - if e.complexity.NetworkHandlerDescriptor.Description == nil { - break - } - - return e.complexity.NetworkHandlerDescriptor.Description(childComplexity), true - - case "NetworkHandlerDescriptor.id": - if e.complexity.NetworkHandlerDescriptor.ID == nil { - break - } - - return e.complexity.NetworkHandlerDescriptor.ID(childComplexity), true - - case "NetworkHandlerDescriptor.label": - if e.complexity.NetworkHandlerDescriptor.Label == nil { - break - } - - return e.complexity.NetworkHandlerDescriptor.Label(childComplexity), true - - case "NetworkHandlerDescriptor.properties": - if e.complexity.NetworkHandlerDescriptor.Properties == nil { - break - } - - return e.complexity.NetworkHandlerDescriptor.Properties(childComplexity), true - - case "NetworkHandlerDescriptor.secured": - if e.complexity.NetworkHandlerDescriptor.Secured == nil { - break - } - - return e.complexity.NetworkHandlerDescriptor.Secured(childComplexity), true - - case "NetworkHandlerDescriptor.type": - if e.complexity.NetworkHandlerDescriptor.Type == nil { - break - } - - return e.complexity.NetworkHandlerDescriptor.Type(childComplexity), true - - case "ObjectDescriptor.description": - if e.complexity.ObjectDescriptor.Description == nil { - break - } - - return e.complexity.ObjectDescriptor.Description(childComplexity), true - - case "ObjectDescriptor.displayName": - if e.complexity.ObjectDescriptor.DisplayName == nil { - break - } - - return e.complexity.ObjectDescriptor.DisplayName(childComplexity), true - - case "ObjectDescriptor.fullName": - if e.complexity.ObjectDescriptor.FullName == nil { - break - } - - return e.complexity.ObjectDescriptor.FullName(childComplexity), true - - case "ObjectDescriptor.id": - if e.complexity.ObjectDescriptor.ID == nil { - break - } - - return e.complexity.ObjectDescriptor.ID(childComplexity), true - - case "ObjectDescriptor.uniqueName": - if e.complexity.ObjectDescriptor.UniqueName == nil { - break - } - - return e.complexity.ObjectDescriptor.UniqueName(childComplexity), true - - case "ObjectDescriptor.value": - if e.complexity.ObjectDescriptor.Value == nil { - break - } - - return e.complexity.ObjectDescriptor.Value(childComplexity), true - - case "ObjectDetails.description": - if e.complexity.ObjectDetails.Description == nil { - break - } - - return e.complexity.ObjectDetails.Description(childComplexity), true - - case "ObjectDetails.displayName": - if e.complexity.ObjectDetails.DisplayName == nil { - break - } - - return e.complexity.ObjectDetails.DisplayName(childComplexity), true - - case "ObjectDetails.id": - if e.complexity.ObjectDetails.ID == nil { - break - } - - return e.complexity.ObjectDetails.ID(childComplexity), true - - case "ObjectDetails.value": - if e.complexity.ObjectDetails.Value == nil { - break - } - - return e.complexity.ObjectDetails.Value(childComplexity), true - - case "ObjectOrigin.configuration": - if e.complexity.ObjectOrigin.Configuration == nil { - break - } - - return e.complexity.ObjectOrigin.Configuration(childComplexity), true - - case "ObjectOrigin.details": - if e.complexity.ObjectOrigin.Details == nil { - break - } - - return e.complexity.ObjectOrigin.Details(childComplexity), true - - case "ObjectOrigin.displayName": - if e.complexity.ObjectOrigin.DisplayName == nil { - break - } - - return e.complexity.ObjectOrigin.DisplayName(childComplexity), true - - case "ObjectOrigin.icon": - if e.complexity.ObjectOrigin.Icon == nil { - break - } - - return e.complexity.ObjectOrigin.Icon(childComplexity), true - - case "ObjectOrigin.subType": - if e.complexity.ObjectOrigin.SubType == nil { - break - } - - return e.complexity.ObjectOrigin.SubType(childComplexity), true - - case "ObjectOrigin.type": - if e.complexity.ObjectOrigin.Type == nil { - break - } - - return e.complexity.ObjectOrigin.Type(childComplexity), true - - case "ObjectPropertyInfo.category": - if e.complexity.ObjectPropertyInfo.Category == nil { - break - } - - return e.complexity.ObjectPropertyInfo.Category(childComplexity), true - - case "ObjectPropertyInfo.dataType": - if e.complexity.ObjectPropertyInfo.DataType == nil { - break - } - - return e.complexity.ObjectPropertyInfo.DataType(childComplexity), true - - case "ObjectPropertyInfo.defaultValue": - if e.complexity.ObjectPropertyInfo.DefaultValue == nil { - break - } - - return e.complexity.ObjectPropertyInfo.DefaultValue(childComplexity), true - - case "ObjectPropertyInfo.description": - if e.complexity.ObjectPropertyInfo.Description == nil { - break - } - - return e.complexity.ObjectPropertyInfo.Description(childComplexity), true - - case "ObjectPropertyInfo.displayName": - if e.complexity.ObjectPropertyInfo.DisplayName == nil { - break - } - - return e.complexity.ObjectPropertyInfo.DisplayName(childComplexity), true - - case "ObjectPropertyInfo.features": - if e.complexity.ObjectPropertyInfo.Features == nil { - break - } - - return e.complexity.ObjectPropertyInfo.Features(childComplexity), true - - case "ObjectPropertyInfo.id": - if e.complexity.ObjectPropertyInfo.ID == nil { - break - } - - return e.complexity.ObjectPropertyInfo.ID(childComplexity), true - - case "ObjectPropertyInfo.length": - if e.complexity.ObjectPropertyInfo.Length == nil { - break - } - - return e.complexity.ObjectPropertyInfo.Length(childComplexity), true - - case "ObjectPropertyInfo.order": - if e.complexity.ObjectPropertyInfo.Order == nil { - break - } - - return e.complexity.ObjectPropertyInfo.Order(childComplexity), true - - case "ObjectPropertyInfo.validValues": - if e.complexity.ObjectPropertyInfo.ValidValues == nil { - break - } - - return e.complexity.ObjectPropertyInfo.ValidValues(childComplexity), true - - case "ObjectPropertyInfo.value": - if e.complexity.ObjectPropertyInfo.Value == nil { - break - } - - return e.complexity.ObjectPropertyInfo.Value(childComplexity), true - - case "ProductInfo.buildTime": - if e.complexity.ProductInfo.BuildTime == nil { - break - } - - return e.complexity.ProductInfo.BuildTime(childComplexity), true - - case "ProductInfo.description": - if e.complexity.ProductInfo.Description == nil { - break - } - - return e.complexity.ProductInfo.Description(childComplexity), true - - case "ProductInfo.id": - if e.complexity.ProductInfo.ID == nil { - break - } - - return e.complexity.ProductInfo.ID(childComplexity), true - - case "ProductInfo.latestVersionInfo": - if e.complexity.ProductInfo.LatestVersionInfo == nil { - break - } - - return e.complexity.ProductInfo.LatestVersionInfo(childComplexity), true - - case "ProductInfo.licenseInfo": - if e.complexity.ProductInfo.LicenseInfo == nil { - break - } - - return e.complexity.ProductInfo.LicenseInfo(childComplexity), true - - case "ProductInfo.name": - if e.complexity.ProductInfo.Name == nil { - break - } - - return e.complexity.ProductInfo.Name(childComplexity), true - - case "ProductInfo.releaseTime": - if e.complexity.ProductInfo.ReleaseTime == nil { - break - } - - return e.complexity.ProductInfo.ReleaseTime(childComplexity), true - - case "ProductInfo.version": - if e.complexity.ProductInfo.Version == nil { - break - } - - return e.complexity.ProductInfo.Version(childComplexity), true - - case "Query.activeUser": - if e.complexity.Query.ActiveUser == nil { - break - } - - return e.complexity.Query.ActiveUser(childComplexity), true - - case "Query.allConnections": - if e.complexity.Query.AllConnections == nil { - break - } - - args, err := ec.field_Query_allConnections_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.AllConnections(childComplexity, args["id"].(*string)), true - - case "Query.authChangeLocalPassword": - if e.complexity.Query.AuthChangeLocalPassword == nil { - break - } - - args, err := ec.field_Query_authChangeLocalPassword_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.AuthChangeLocalPassword(childComplexity, args["oldPassword"].(string), args["newPassword"].(string)), true - - case "Query.authLogin": - if e.complexity.Query.AuthLogin == nil { - break - } - - args, err := ec.field_Query_authLogin_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.AuthLogin(childComplexity, args["provider"].(string), args["configuration"].(*string), args["credentials"].(interface{}), args["linkUser"].(*bool)), true - - case "Query.authLogout": - if e.complexity.Query.AuthLogout == nil { - break - } - - args, err := ec.field_Query_authLogout_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.AuthLogout(childComplexity, args["provider"].(*string), args["configuration"].(*string)), true - - case "Query.authModels": - if e.complexity.Query.AuthModels == nil { - break - } - - return e.complexity.Query.AuthModels(childComplexity), true - - case "Query.authProviders": - if e.complexity.Query.AuthProviders == nil { - break - } - - return e.complexity.Query.AuthProviders(childComplexity), true - - case "Query.authUpdateStatus": - if e.complexity.Query.AuthUpdateStatus == nil { - break - } - - args, err := ec.field_Query_authUpdateStatus_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.AuthUpdateStatus(childComplexity, args["authId"].(string), args["linkUser"].(*bool)), true - - case "Query.configureServer": - if e.complexity.Query.ConfigureServer == nil { - break - } - - args, err := ec.field_Query_configureServer_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ConfigureServer(childComplexity, args["configuration"].(model.ServerConfigInput)), true - - case "Query.connectionFolders": - if e.complexity.Query.ConnectionFolders == nil { - break - } - - args, err := ec.field_Query_connectionFolders_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ConnectionFolders(childComplexity, args["path"].(*string)), true - - case "Query.connectionInfo": - if e.complexity.Query.ConnectionInfo == nil { - break - } - - args, err := ec.field_Query_connectionInfo_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ConnectionInfo(childComplexity, args["id"].(string)), true - - case "Query.connectionState": - if e.complexity.Query.ConnectionState == nil { - break - } - - args, err := ec.field_Query_connectionState_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ConnectionState(childComplexity, args["id"].(string)), true - - case "Query.copyConnectionConfiguration": - if e.complexity.Query.CopyConnectionConfiguration == nil { - break - } - - args, err := ec.field_Query_copyConnectionConfiguration_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.CopyConnectionConfiguration(childComplexity, args["nodePath"].(string), args["config"].(*model.ConnectionConfig)), true - - case "Query.createConnectionConfiguration": - if e.complexity.Query.CreateConnectionConfiguration == nil { - break - } - - args, err := ec.field_Query_createConnectionConfiguration_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.CreateConnectionConfiguration(childComplexity, args["config"].(model.ConnectionConfig)), true - - case "Query.createRole": - if e.complexity.Query.CreateRole == nil { - break - } - - args, err := ec.field_Query_createRole_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.CreateRole(childComplexity, args["roleId"].(string), args["roleName"].(*string), args["description"].(*string)), true - - case "Query.createUser": - if e.complexity.Query.CreateUser == nil { - break - } - - args, err := ec.field_Query_createUser_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.CreateUser(childComplexity, args["userId"].(string)), true - - case "Query.dataTransferAvailableStreamProcessors": - if e.complexity.Query.DataTransferAvailableStreamProcessors == nil { - break - } - - return e.complexity.Query.DataTransferAvailableStreamProcessors(childComplexity), true - - case "Query.dataTransferExportDataFromContainer": - if e.complexity.Query.DataTransferExportDataFromContainer == nil { - break - } - - args, err := ec.field_Query_dataTransferExportDataFromContainer_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DataTransferExportDataFromContainer(childComplexity, args["connectionId"].(string), args["containerNodePath"].(string), args["parameters"].(model.DataTransferParameters)), true - - case "Query.dataTransferExportDataFromResults": - if e.complexity.Query.DataTransferExportDataFromResults == nil { - break - } - - args, err := ec.field_Query_dataTransferExportDataFromResults_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DataTransferExportDataFromResults(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["parameters"].(model.DataTransferParameters)), true - - case "Query.dataTransferRemoveDataFile": - if e.complexity.Query.DataTransferRemoveDataFile == nil { - break - } - - args, err := ec.field_Query_dataTransferRemoveDataFile_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DataTransferRemoveDataFile(childComplexity, args["dataFileId"].(string)), true - - case "Query.deleteAuthProviderConfiguration": - if e.complexity.Query.DeleteAuthProviderConfiguration == nil { - break - } - - args, err := ec.field_Query_deleteAuthProviderConfiguration_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DeleteAuthProviderConfiguration(childComplexity, args["id"].(string)), true - - case "Query.deleteConnectionConfiguration": - if e.complexity.Query.DeleteConnectionConfiguration == nil { - break - } - - args, err := ec.field_Query_deleteConnectionConfiguration_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DeleteConnectionConfiguration(childComplexity, args["id"].(string)), true - - case "Query.deleteRole": - if e.complexity.Query.DeleteRole == nil { - break - } - - args, err := ec.field_Query_deleteRole_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DeleteRole(childComplexity, args["roleId"].(string)), true - - case "Query.deleteUser": - if e.complexity.Query.DeleteUser == nil { - break - } - - args, err := ec.field_Query_deleteUser_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DeleteUser(childComplexity, args["userId"].(string)), true - - case "Query.deleteUserMetaParameter": - if e.complexity.Query.DeleteUserMetaParameter == nil { - break - } - - args, err := ec.field_Query_deleteUserMetaParameter_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DeleteUserMetaParameter(childComplexity, args["id"].(string)), true - - case "Query.driverList": - if e.complexity.Query.DriverList == nil { - break - } - - args, err := ec.field_Query_driverList_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.DriverList(childComplexity, args["id"].(*string)), true - - case "Query.enableUser": - if e.complexity.Query.EnableUser == nil { - break - } - - args, err := ec.field_Query_enableUser_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.EnableUser(childComplexity, args["userId"].(string), args["enabled"].(bool)), true - - case "Query.getConnectionSubjectAccess": - if e.complexity.Query.GetConnectionSubjectAccess == nil { - break - } - - args, err := ec.field_Query_getConnectionSubjectAccess_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.GetConnectionSubjectAccess(childComplexity, args["connectionId"].(*string)), true - - case "Query.getSubjectConnectionAccess": - if e.complexity.Query.GetSubjectConnectionAccess == nil { - break - } - - args, err := ec.field_Query_getSubjectConnectionAccess_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.GetSubjectConnectionAccess(childComplexity, args["subjectId"].(*string)), true - - case "Query.grantUserRole": - if e.complexity.Query.GrantUserRole == nil { - break - } - - args, err := ec.field_Query_grantUserRole_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.GrantUserRole(childComplexity, args["userId"].(string), args["roleId"].(string)), true - - case "Query.listAuthProviderConfigurationParameters": - if e.complexity.Query.ListAuthProviderConfigurationParameters == nil { - break - } - - args, err := ec.field_Query_listAuthProviderConfigurationParameters_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ListAuthProviderConfigurationParameters(childComplexity, args["providerId"].(string)), true - - case "Query.listAuthProviderConfigurations": - if e.complexity.Query.ListAuthProviderConfigurations == nil { - break - } - - args, err := ec.field_Query_listAuthProviderConfigurations_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ListAuthProviderConfigurations(childComplexity, args["providerId"].(*string)), true - - case "Query.listFeatureSets": - if e.complexity.Query.ListFeatureSets == nil { - break - } - - return e.complexity.Query.ListFeatureSets(childComplexity), true - - case "Query.listPermissions": - if e.complexity.Query.ListPermissions == nil { - break - } - - return e.complexity.Query.ListPermissions(childComplexity), true - - case "Query.listRoles": - if e.complexity.Query.ListRoles == nil { - break - } - - args, err := ec.field_Query_listRoles_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ListRoles(childComplexity, args["roleId"].(*string)), true - - case "Query.listUserProfileProperties": - if e.complexity.Query.ListUserProfileProperties == nil { - break - } - - return e.complexity.Query.ListUserProfileProperties(childComplexity), true - - case "Query.listUsers": - if e.complexity.Query.ListUsers == nil { - break - } - - args, err := ec.field_Query_listUsers_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ListUsers(childComplexity, args["userId"].(*string)), true - - case "Query.metadataGetNodeDDL": - if e.complexity.Query.MetadataGetNodeDdl == nil { - break - } - - args, err := ec.field_Query_metadataGetNodeDDL_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.MetadataGetNodeDdl(childComplexity, args["nodeId"].(string), args["options"].(interface{})), true - - case "Query.navGetStructContainers": - if e.complexity.Query.NavGetStructContainers == nil { - break - } - - args, err := ec.field_Query_navGetStructContainers_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.NavGetStructContainers(childComplexity, args["connectionId"].(string), args["contextId"].(*string), args["catalog"].(*string)), true - - case "Query.navNodeChildren": - if e.complexity.Query.NavNodeChildren == nil { - break - } - - args, err := ec.field_Query_navNodeChildren_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.NavNodeChildren(childComplexity, args["parentPath"].(string), args["offset"].(*int), args["limit"].(*int), args["onlyFolders"].(*bool)), true - - case "Query.navNodeInfo": - if e.complexity.Query.NavNodeInfo == nil { - break - } - - args, err := ec.field_Query_navNodeInfo_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.NavNodeInfo(childComplexity, args["nodePath"].(string)), true - - case "Query.navNodeParents": - if e.complexity.Query.NavNodeParents == nil { - break - } - - args, err := ec.field_Query_navNodeParents_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.NavNodeParents(childComplexity, args["nodePath"].(string)), true - - case "Query.navRefreshNode": - if e.complexity.Query.NavRefreshNode == nil { - break - } - - args, err := ec.field_Query_navRefreshNode_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.NavRefreshNode(childComplexity, args["nodePath"].(string)), true - - case "Query.networkHandlers": - if e.complexity.Query.NetworkHandlers == nil { - break - } - - return e.complexity.Query.NetworkHandlers(childComplexity), true - - case "Query.readSessionLog": - if e.complexity.Query.ReadSessionLog == nil { - break - } - - args, err := ec.field_Query_readSessionLog_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ReadSessionLog(childComplexity, args["maxEntries"].(*int), args["clearEntries"].(*bool)), true - - case "Query.revokeUserRole": - if e.complexity.Query.RevokeUserRole == nil { - break - } - - args, err := ec.field_Query_revokeUserRole_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.RevokeUserRole(childComplexity, args["userId"].(string), args["roleId"].(string)), true - - case "Query.rmListProjects": - if e.complexity.Query.RmListProjects == nil { - break - } - - return e.complexity.Query.RmListProjects(childComplexity), true - - case "Query.rmListResources": - if e.complexity.Query.RmListResources == nil { - break - } - - args, err := ec.field_Query_rmListResources_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.RmListResources(childComplexity, args["projectId"].(string), args["folder"].(*string), args["nameMask"].(*string), args["readProperties"].(*bool), args["readHistory"].(*bool)), true - - case "Query.rmReadResourceAsString": - if e.complexity.Query.RmReadResourceAsString == nil { - break - } - - args, err := ec.field_Query_rmReadResourceAsString_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.RmReadResourceAsString(childComplexity, args["projectId"].(string), args["resourcePath"].(string)), true - - case "Query.sqlCompletionProposals": - if e.complexity.Query.SQLCompletionProposals == nil { - break - } - - args, err := ec.field_Query_sqlCompletionProposals_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLCompletionProposals(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["query"].(string), args["position"].(int), args["maxResults"].(*int), args["simpleMode"].(*bool)), true - - case "Query.sqlDialectInfo": - if e.complexity.Query.SQLDialectInfo == nil { - break - } - - args, err := ec.field_Query_sqlDialectInfo_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLDialectInfo(childComplexity, args["connectionId"].(string)), true - - case "Query.sqlEntityQueryGenerators": - if e.complexity.Query.SQLEntityQueryGenerators == nil { - break - } - - args, err := ec.field_Query_sqlEntityQueryGenerators_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLEntityQueryGenerators(childComplexity, args["nodePathList"].([]string)), true - - case "Query.sqlFormatQuery": - if e.complexity.Query.SQLFormatQuery == nil { - break - } - - args, err := ec.field_Query_sqlFormatQuery_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLFormatQuery(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["query"].(string)), true - - case "Query.sqlGenerateEntityQuery": - if e.complexity.Query.SQLGenerateEntityQuery == nil { - break - } - - args, err := ec.field_Query_sqlGenerateEntityQuery_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLGenerateEntityQuery(childComplexity, args["generatorId"].(string), args["options"].(interface{}), args["nodePathList"].([]string)), true - - case "Query.sqlListContexts": - if e.complexity.Query.SQLListContexts == nil { - break - } - - args, err := ec.field_Query_sqlListContexts_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLListContexts(childComplexity, args["connectionId"].(*string), args["contextId"].(*string)), true - - case "Query.sqlParseQuery": - if e.complexity.Query.SQLParseQuery == nil { - break - } - - args, err := ec.field_Query_sqlParseQuery_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLParseQuery(childComplexity, args["connectionId"].(string), args["script"].(string), args["position"].(int)), true - - case "Query.sqlParseScript": - if e.complexity.Query.SQLParseScript == nil { - break - } - - args, err := ec.field_Query_sqlParseScript_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLParseScript(childComplexity, args["connectionId"].(string), args["script"].(string)), true - - case "Query.sqlSupportedOperations": - if e.complexity.Query.SQLSupportedOperations == nil { - break - } - - args, err := ec.field_Query_sqlSupportedOperations_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SQLSupportedOperations(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["attributeIndex"].(int)), true - - case "Query.saveAuthProviderConfiguration": - if e.complexity.Query.SaveAuthProviderConfiguration == nil { - break - } - - args, err := ec.field_Query_saveAuthProviderConfiguration_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SaveAuthProviderConfiguration(childComplexity, args["providerId"].(string), args["id"].(string), args["displayName"].(*string), args["disabled"].(*bool), args["iconURL"].(*string), args["description"].(*string), args["parameters"].(interface{})), true - - case "Query.saveUserMetaParameter": - if e.complexity.Query.SaveUserMetaParameter == nil { - break - } - - args, err := ec.field_Query_saveUserMetaParameter_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SaveUserMetaParameter(childComplexity, args["id"].(string), args["displayName"].(string), args["description"].(*string), args["required"].(bool)), true - - case "Query.searchConnections": - if e.complexity.Query.SearchConnections == nil { - break - } - - args, err := ec.field_Query_searchConnections_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SearchConnections(childComplexity, args["hostNames"].([]string)), true - - case "Query.serverConfig": - if e.complexity.Query.ServerConfig == nil { - break - } - - return e.complexity.Query.ServerConfig(childComplexity), true - - case "Query.sessionPermissions": - if e.complexity.Query.SessionPermissions == nil { - break - } - - return e.complexity.Query.SessionPermissions(childComplexity), true - - case "Query.sessionState": - if e.complexity.Query.SessionState == nil { - break - } - - return e.complexity.Query.SessionState(childComplexity), true - - case "Query.setConnectionSubjectAccess": - if e.complexity.Query.SetConnectionSubjectAccess == nil { - break - } - - args, err := ec.field_Query_setConnectionSubjectAccess_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SetConnectionSubjectAccess(childComplexity, args["connectionId"].(string), args["subjects"].([]string)), true - - case "Query.setDefaultNavigatorSettings": - if e.complexity.Query.SetDefaultNavigatorSettings == nil { - break - } - - args, err := ec.field_Query_setDefaultNavigatorSettings_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SetDefaultNavigatorSettings(childComplexity, args["settings"].(model.NavigatorSettingsInput)), true - - case "Query.setSubjectConnectionAccess": - if e.complexity.Query.SetSubjectConnectionAccess == nil { - break - } - - args, err := ec.field_Query_setSubjectConnectionAccess_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SetSubjectConnectionAccess(childComplexity, args["subjectId"].(string), args["connections"].([]string)), true - - case "Query.setSubjectPermissions": - if e.complexity.Query.SetSubjectPermissions == nil { - break - } - - args, err := ec.field_Query_setSubjectPermissions_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SetSubjectPermissions(childComplexity, args["roleId"].(string), args["permissions"].([]string)), true - - case "Query.setUserCredentials": - if e.complexity.Query.SetUserCredentials == nil { - break - } - - args, err := ec.field_Query_setUserCredentials_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SetUserCredentials(childComplexity, args["userId"].(string), args["providerId"].(string), args["credentials"].(interface{})), true - - case "Query.setUserMetaParameterValues": - if e.complexity.Query.SetUserMetaParameterValues == nil { - break - } - - args, err := ec.field_Query_setUserMetaParameterValues_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.SetUserMetaParameterValues(childComplexity, args["userId"].(string), args["parameters"].(interface{})), true - - case "Query.templateConnections": - if e.complexity.Query.TemplateConnections == nil { - break - } - - return e.complexity.Query.TemplateConnections(childComplexity), true - - case "Query.updateConnectionConfiguration": - if e.complexity.Query.UpdateConnectionConfiguration == nil { - break - } - - args, err := ec.field_Query_updateConnectionConfiguration_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.UpdateConnectionConfiguration(childComplexity, args["id"].(string), args["config"].(model.ConnectionConfig)), true - - case "Query.updateRole": - if e.complexity.Query.UpdateRole == nil { - break - } - - args, err := ec.field_Query_updateRole_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.UpdateRole(childComplexity, args["roleId"].(string), args["roleName"].(*string), args["description"].(*string)), true - - case "Query.userConnections": - if e.complexity.Query.UserConnections == nil { - break - } - - args, err := ec.field_Query_userConnections_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.UserConnections(childComplexity, args["id"].(*string)), true - - case "RMProject.createTime": - if e.complexity.RMProject.CreateTime == nil { - break - } - - return e.complexity.RMProject.CreateTime(childComplexity), true - - case "RMProject.creator": - if e.complexity.RMProject.Creator == nil { - break - } - - return e.complexity.RMProject.Creator(childComplexity), true - - case "RMProject.description": - if e.complexity.RMProject.Description == nil { - break - } - - return e.complexity.RMProject.Description(childComplexity), true - - case "RMProject.id": - if e.complexity.RMProject.ID == nil { - break - } - - return e.complexity.RMProject.ID(childComplexity), true - - case "RMProject.name": - if e.complexity.RMProject.Name == nil { - break - } - - return e.complexity.RMProject.Name(childComplexity), true - - case "RMProject.shared": - if e.complexity.RMProject.Shared == nil { - break - } - - return e.complexity.RMProject.Shared(childComplexity), true - - case "RMResource.folder": - if e.complexity.RMResource.Folder == nil { - break - } - - return e.complexity.RMResource.Folder(childComplexity), true - - case "RMResource.length": - if e.complexity.RMResource.Length == nil { - break - } - - return e.complexity.RMResource.Length(childComplexity), true - - case "RMResource.name": - if e.complexity.RMResource.Name == nil { - break - } - - return e.complexity.RMResource.Name(childComplexity), true - - case "SQLCompletionProposal.cursorPosition": - if e.complexity.SQLCompletionProposal.CursorPosition == nil { - break - } - - return e.complexity.SQLCompletionProposal.CursorPosition(childComplexity), true - - case "SQLCompletionProposal.displayString": - if e.complexity.SQLCompletionProposal.DisplayString == nil { - break - } - - return e.complexity.SQLCompletionProposal.DisplayString(childComplexity), true - - case "SQLCompletionProposal.icon": - if e.complexity.SQLCompletionProposal.Icon == nil { - break - } - - return e.complexity.SQLCompletionProposal.Icon(childComplexity), true - - case "SQLCompletionProposal.nodePath": - if e.complexity.SQLCompletionProposal.NodePath == nil { - break - } - - return e.complexity.SQLCompletionProposal.NodePath(childComplexity), true - - case "SQLCompletionProposal.replacementLength": - if e.complexity.SQLCompletionProposal.ReplacementLength == nil { - break - } - - return e.complexity.SQLCompletionProposal.ReplacementLength(childComplexity), true - - case "SQLCompletionProposal.replacementOffset": - if e.complexity.SQLCompletionProposal.ReplacementOffset == nil { - break - } - - return e.complexity.SQLCompletionProposal.ReplacementOffset(childComplexity), true - - case "SQLCompletionProposal.replacementString": - if e.complexity.SQLCompletionProposal.ReplacementString == nil { - break - } - - return e.complexity.SQLCompletionProposal.ReplacementString(childComplexity), true - - case "SQLCompletionProposal.score": - if e.complexity.SQLCompletionProposal.Score == nil { - break - } - - return e.complexity.SQLCompletionProposal.Score(childComplexity), true - - case "SQLCompletionProposal.type": - if e.complexity.SQLCompletionProposal.Type == nil { - break - } - - return e.complexity.SQLCompletionProposal.Type(childComplexity), true - - case "SQLContextInfo.connectionId": - if e.complexity.SQLContextInfo.ConnectionID == nil { - break - } - - return e.complexity.SQLContextInfo.ConnectionID(childComplexity), true - - case "SQLContextInfo.defaultCatalog": - if e.complexity.SQLContextInfo.DefaultCatalog == nil { - break - } - - return e.complexity.SQLContextInfo.DefaultCatalog(childComplexity), true - - case "SQLContextInfo.defaultSchema": - if e.complexity.SQLContextInfo.DefaultSchema == nil { - break - } - - return e.complexity.SQLContextInfo.DefaultSchema(childComplexity), true - - case "SQLContextInfo.id": - if e.complexity.SQLContextInfo.ID == nil { - break - } - - return e.complexity.SQLContextInfo.ID(childComplexity), true - - case "SQLDialectInfo.catalogSeparator": - if e.complexity.SQLDialectInfo.CatalogSeparator == nil { - break - } - - return e.complexity.SQLDialectInfo.CatalogSeparator(childComplexity), true - - case "SQLDialectInfo.dataTypes": - if e.complexity.SQLDialectInfo.DataTypes == nil { - break - } - - return e.complexity.SQLDialectInfo.DataTypes(childComplexity), true - - case "SQLDialectInfo.functions": - if e.complexity.SQLDialectInfo.Functions == nil { - break - } - - return e.complexity.SQLDialectInfo.Functions(childComplexity), true - - case "SQLDialectInfo.multiLineComments": - if e.complexity.SQLDialectInfo.MultiLineComments == nil { - break - } - - return e.complexity.SQLDialectInfo.MultiLineComments(childComplexity), true - - case "SQLDialectInfo.name": - if e.complexity.SQLDialectInfo.Name == nil { - break - } - - return e.complexity.SQLDialectInfo.Name(childComplexity), true - - case "SQLDialectInfo.quoteStrings": - if e.complexity.SQLDialectInfo.QuoteStrings == nil { - break - } - - return e.complexity.SQLDialectInfo.QuoteStrings(childComplexity), true - - case "SQLDialectInfo.reservedWords": - if e.complexity.SQLDialectInfo.ReservedWords == nil { - break - } - - return e.complexity.SQLDialectInfo.ReservedWords(childComplexity), true - - case "SQLDialectInfo.scriptDelimiter": - if e.complexity.SQLDialectInfo.ScriptDelimiter == nil { - break - } - - return e.complexity.SQLDialectInfo.ScriptDelimiter(childComplexity), true - - case "SQLDialectInfo.singleLineComments": - if e.complexity.SQLDialectInfo.SingleLineComments == nil { - break - } - - return e.complexity.SQLDialectInfo.SingleLineComments(childComplexity), true - - case "SQLDialectInfo.structSeparator": - if e.complexity.SQLDialectInfo.StructSeparator == nil { - break - } - - return e.complexity.SQLDialectInfo.StructSeparator(childComplexity), true - - case "SQLDialectInfo.supportsExplainExecutionPlan": - if e.complexity.SQLDialectInfo.SupportsExplainExecutionPlan == nil { - break - } - - return e.complexity.SQLDialectInfo.SupportsExplainExecutionPlan(childComplexity), true - - case "SQLExecuteInfo.duration": - if e.complexity.SQLExecuteInfo.Duration == nil { - break - } - - return e.complexity.SQLExecuteInfo.Duration(childComplexity), true - - case "SQLExecuteInfo.filterText": - if e.complexity.SQLExecuteInfo.FilterText == nil { - break - } - - return e.complexity.SQLExecuteInfo.FilterText(childComplexity), true - - case "SQLExecuteInfo.results": - if e.complexity.SQLExecuteInfo.Results == nil { - break - } - - return e.complexity.SQLExecuteInfo.Results(childComplexity), true - - case "SQLExecuteInfo.statusMessage": - if e.complexity.SQLExecuteInfo.StatusMessage == nil { - break - } - - return e.complexity.SQLExecuteInfo.StatusMessage(childComplexity), true - - case "SQLExecutionPlan.nodes": - if e.complexity.SQLExecutionPlan.Nodes == nil { - break - } - - return e.complexity.SQLExecutionPlan.Nodes(childComplexity), true - - case "SQLExecutionPlan.query": - if e.complexity.SQLExecutionPlan.Query == nil { - break - } - - return e.complexity.SQLExecutionPlan.Query(childComplexity), true - - case "SQLExecutionPlanNode.condition": - if e.complexity.SQLExecutionPlanNode.Condition == nil { - break - } - - return e.complexity.SQLExecutionPlanNode.Condition(childComplexity), true - - case "SQLExecutionPlanNode.description": - if e.complexity.SQLExecutionPlanNode.Description == nil { - break - } - - return e.complexity.SQLExecutionPlanNode.Description(childComplexity), true - - case "SQLExecutionPlanNode.id": - if e.complexity.SQLExecutionPlanNode.ID == nil { - break - } - - return e.complexity.SQLExecutionPlanNode.ID(childComplexity), true - - case "SQLExecutionPlanNode.kind": - if e.complexity.SQLExecutionPlanNode.Kind == nil { - break - } - - return e.complexity.SQLExecutionPlanNode.Kind(childComplexity), true - - case "SQLExecutionPlanNode.name": - if e.complexity.SQLExecutionPlanNode.Name == nil { - break - } - - return e.complexity.SQLExecutionPlanNode.Name(childComplexity), true - - case "SQLExecutionPlanNode.parentId": - if e.complexity.SQLExecutionPlanNode.ParentID == nil { - break - } - - return e.complexity.SQLExecutionPlanNode.ParentID(childComplexity), true - - case "SQLExecutionPlanNode.properties": - if e.complexity.SQLExecutionPlanNode.Properties == nil { - break - } - - return e.complexity.SQLExecutionPlanNode.Properties(childComplexity), true - - case "SQLExecutionPlanNode.type": - if e.complexity.SQLExecutionPlanNode.Type == nil { - break - } - - return e.complexity.SQLExecutionPlanNode.Type(childComplexity), true - - case "SQLQueryGenerator.description": - if e.complexity.SQLQueryGenerator.Description == nil { - break - } - - return e.complexity.SQLQueryGenerator.Description(childComplexity), true - - case "SQLQueryGenerator.id": - if e.complexity.SQLQueryGenerator.ID == nil { - break - } - - return e.complexity.SQLQueryGenerator.ID(childComplexity), true - - case "SQLQueryGenerator.label": - if e.complexity.SQLQueryGenerator.Label == nil { - break - } - - return e.complexity.SQLQueryGenerator.Label(childComplexity), true - - case "SQLQueryGenerator.multiObject": - if e.complexity.SQLQueryGenerator.MultiObject == nil { - break - } - - return e.complexity.SQLQueryGenerator.MultiObject(childComplexity), true - - case "SQLQueryGenerator.order": - if e.complexity.SQLQueryGenerator.Order == nil { - break - } - - return e.complexity.SQLQueryGenerator.Order(childComplexity), true - - case "SQLQueryResults.dataFormat": - if e.complexity.SQLQueryResults.DataFormat == nil { - break - } - - return e.complexity.SQLQueryResults.DataFormat(childComplexity), true - - case "SQLQueryResults.resultSet": - if e.complexity.SQLQueryResults.ResultSet == nil { - break - } - - return e.complexity.SQLQueryResults.ResultSet(childComplexity), true - - case "SQLQueryResults.sourceQuery": - if e.complexity.SQLQueryResults.SourceQuery == nil { - break - } - - return e.complexity.SQLQueryResults.SourceQuery(childComplexity), true - - case "SQLQueryResults.title": - if e.complexity.SQLQueryResults.Title == nil { - break - } - - return e.complexity.SQLQueryResults.Title(childComplexity), true - - case "SQLQueryResults.updateRowCount": - if e.complexity.SQLQueryResults.UpdateRowCount == nil { - break - } - - return e.complexity.SQLQueryResults.UpdateRowCount(childComplexity), true - - case "SQLResultColumn.dataKind": - if e.complexity.SQLResultColumn.DataKind == nil { - break - } - - return e.complexity.SQLResultColumn.DataKind(childComplexity), true - - case "SQLResultColumn.entityName": - if e.complexity.SQLResultColumn.EntityName == nil { - break - } - - return e.complexity.SQLResultColumn.EntityName(childComplexity), true - - case "SQLResultColumn.fullTypeName": - if e.complexity.SQLResultColumn.FullTypeName == nil { - break - } - - return e.complexity.SQLResultColumn.FullTypeName(childComplexity), true - - case "SQLResultColumn.icon": - if e.complexity.SQLResultColumn.Icon == nil { - break - } - - return e.complexity.SQLResultColumn.Icon(childComplexity), true - - case "SQLResultColumn.label": - if e.complexity.SQLResultColumn.Label == nil { - break - } - - return e.complexity.SQLResultColumn.Label(childComplexity), true - - case "SQLResultColumn.maxLength": - if e.complexity.SQLResultColumn.MaxLength == nil { - break - } - - return e.complexity.SQLResultColumn.MaxLength(childComplexity), true - - case "SQLResultColumn.name": - if e.complexity.SQLResultColumn.Name == nil { - break - } - - return e.complexity.SQLResultColumn.Name(childComplexity), true - - case "SQLResultColumn.position": - if e.complexity.SQLResultColumn.Position == nil { - break - } - - return e.complexity.SQLResultColumn.Position(childComplexity), true - - case "SQLResultColumn.precision": - if e.complexity.SQLResultColumn.Precision == nil { - break - } - - return e.complexity.SQLResultColumn.Precision(childComplexity), true - - case "SQLResultColumn.readOnly": - if e.complexity.SQLResultColumn.ReadOnly == nil { - break - } - - return e.complexity.SQLResultColumn.ReadOnly(childComplexity), true - - case "SQLResultColumn.readOnlyStatus": - if e.complexity.SQLResultColumn.ReadOnlyStatus == nil { - break - } - - return e.complexity.SQLResultColumn.ReadOnlyStatus(childComplexity), true - - case "SQLResultColumn.required": - if e.complexity.SQLResultColumn.Required == nil { - break - } - - return e.complexity.SQLResultColumn.Required(childComplexity), true - - case "SQLResultColumn.scale": - if e.complexity.SQLResultColumn.Scale == nil { - break - } - - return e.complexity.SQLResultColumn.Scale(childComplexity), true - - case "SQLResultColumn.supportedOperations": - if e.complexity.SQLResultColumn.SupportedOperations == nil { - break - } - - return e.complexity.SQLResultColumn.SupportedOperations(childComplexity), true - - case "SQLResultColumn.typeName": - if e.complexity.SQLResultColumn.TypeName == nil { - break - } - - return e.complexity.SQLResultColumn.TypeName(childComplexity), true - - case "SQLResultSet.columns": - if e.complexity.SQLResultSet.Columns == nil { - break - } - - return e.complexity.SQLResultSet.Columns(childComplexity), true - - case "SQLResultSet.hasMoreData": - if e.complexity.SQLResultSet.HasMoreData == nil { - break - } - - return e.complexity.SQLResultSet.HasMoreData(childComplexity), true - - case "SQLResultSet.hasRowIdentifier": - if e.complexity.SQLResultSet.HasRowIdentifier == nil { - break - } - - return e.complexity.SQLResultSet.HasRowIdentifier(childComplexity), true - - case "SQLResultSet.id": - if e.complexity.SQLResultSet.ID == nil { - break - } - - return e.complexity.SQLResultSet.ID(childComplexity), true - - case "SQLResultSet.rows": - if e.complexity.SQLResultSet.Rows == nil { - break - } - - return e.complexity.SQLResultSet.Rows(childComplexity), true - - case "SQLResultSet.singleEntity": - if e.complexity.SQLResultSet.SingleEntity == nil { - break - } - - return e.complexity.SQLResultSet.SingleEntity(childComplexity), true - - case "SQLScriptInfo.queries": - if e.complexity.SQLScriptInfo.Queries == nil { - break - } - - return e.complexity.SQLScriptInfo.Queries(childComplexity), true - - case "SQLScriptQuery.end": - if e.complexity.SQLScriptQuery.End == nil { - break - } - - return e.complexity.SQLScriptQuery.End(childComplexity), true - - case "SQLScriptQuery.start": - if e.complexity.SQLScriptQuery.Start == nil { - break - } - - return e.complexity.SQLScriptQuery.Start(childComplexity), true - - case "ServerConfig.adminCredentialsSaveEnabled": - if e.complexity.ServerConfig.AdminCredentialsSaveEnabled == nil { - break - } - - return e.complexity.ServerConfig.AdminCredentialsSaveEnabled(childComplexity), true - - case "ServerConfig.anonymousAccessEnabled": - if e.complexity.ServerConfig.AnonymousAccessEnabled == nil { - break - } - - return e.complexity.ServerConfig.AnonymousAccessEnabled(childComplexity), true - - case "ServerConfig.authenticationEnabled": - if e.complexity.ServerConfig.AuthenticationEnabled == nil { - break - } - - return e.complexity.ServerConfig.AuthenticationEnabled(childComplexity), true - - case "ServerConfig.configurationMode": - if e.complexity.ServerConfig.ConfigurationMode == nil { - break - } - - return e.complexity.ServerConfig.ConfigurationMode(childComplexity), true - - case "ServerConfig.defaultNavigatorSettings": - if e.complexity.ServerConfig.DefaultNavigatorSettings == nil { - break - } - - return e.complexity.ServerConfig.DefaultNavigatorSettings(childComplexity), true - - case "ServerConfig.developmentMode": - if e.complexity.ServerConfig.DevelopmentMode == nil { - break - } - - return e.complexity.ServerConfig.DevelopmentMode(childComplexity), true - - case "ServerConfig.disabledDrivers": - if e.complexity.ServerConfig.DisabledDrivers == nil { - break - } - - return e.complexity.ServerConfig.DisabledDrivers(childComplexity), true - - case "ServerConfig.enabledAuthProviders": - if e.complexity.ServerConfig.EnabledAuthProviders == nil { - break - } - - return e.complexity.ServerConfig.EnabledAuthProviders(childComplexity), true - - case "ServerConfig.enabledFeatures": - if e.complexity.ServerConfig.EnabledFeatures == nil { - break - } - - return e.complexity.ServerConfig.EnabledFeatures(childComplexity), true - - case "ServerConfig.hostName": - if e.complexity.ServerConfig.HostName == nil { - break - } - - return e.complexity.ServerConfig.HostName(childComplexity), true - - case "ServerConfig.licenseRequired": - if e.complexity.ServerConfig.LicenseRequired == nil { - break - } - - return e.complexity.ServerConfig.LicenseRequired(childComplexity), true - - case "ServerConfig.licenseValid": - if e.complexity.ServerConfig.LicenseValid == nil { - break - } - - return e.complexity.ServerConfig.LicenseValid(childComplexity), true - - case "ServerConfig.localHostAddress": - if e.complexity.ServerConfig.LocalHostAddress == nil { - break - } - - return e.complexity.ServerConfig.LocalHostAddress(childComplexity), true - - case "ServerConfig.name": - if e.complexity.ServerConfig.Name == nil { - break - } - - return e.complexity.ServerConfig.Name(childComplexity), true - - case "ServerConfig.productConfiguration": - if e.complexity.ServerConfig.ProductConfiguration == nil { - break - } - - return e.complexity.ServerConfig.ProductConfiguration(childComplexity), true - - case "ServerConfig.productInfo": - if e.complexity.ServerConfig.ProductInfo == nil { - break - } - - return e.complexity.ServerConfig.ProductInfo(childComplexity), true - - case "ServerConfig.publicCredentialsSaveEnabled": - if e.complexity.ServerConfig.PublicCredentialsSaveEnabled == nil { - break - } - - return e.complexity.ServerConfig.PublicCredentialsSaveEnabled(childComplexity), true - - case "ServerConfig.redirectOnFederatedAuth": - if e.complexity.ServerConfig.RedirectOnFederatedAuth == nil { - break - } - - return e.complexity.ServerConfig.RedirectOnFederatedAuth(childComplexity), true - - case "ServerConfig.resourceManagerEnabled": - if e.complexity.ServerConfig.ResourceManagerEnabled == nil { - break - } - - return e.complexity.ServerConfig.ResourceManagerEnabled(childComplexity), true - - case "ServerConfig.resourceQuotas": - if e.complexity.ServerConfig.ResourceQuotas == nil { - break - } - - return e.complexity.ServerConfig.ResourceQuotas(childComplexity), true - - case "ServerConfig.rootURI": - if e.complexity.ServerConfig.RootURI == nil { - break - } - - return e.complexity.ServerConfig.RootURI(childComplexity), true - - case "ServerConfig.serverURL": - if e.complexity.ServerConfig.ServerURL == nil { - break - } - - return e.complexity.ServerConfig.ServerURL(childComplexity), true - - case "ServerConfig.services": - if e.complexity.ServerConfig.Services == nil { - break - } - - return e.complexity.ServerConfig.Services(childComplexity), true - - case "ServerConfig.sessionExpireTime": - if e.complexity.ServerConfig.SessionExpireTime == nil { - break - } - - return e.complexity.ServerConfig.SessionExpireTime(childComplexity), true - - case "ServerConfig.supportedLanguages": - if e.complexity.ServerConfig.SupportedLanguages == nil { - break - } - - return e.complexity.ServerConfig.SupportedLanguages(childComplexity), true - - case "ServerConfig.supportsConnectionBrowser": - if e.complexity.ServerConfig.SupportsConnectionBrowser == nil { - break - } - - return e.complexity.ServerConfig.SupportsConnectionBrowser(childComplexity), true - - case "ServerConfig.supportsCustomConnections": - if e.complexity.ServerConfig.SupportsCustomConnections == nil { - break - } - - return e.complexity.ServerConfig.SupportsCustomConnections(childComplexity), true - - case "ServerConfig.supportsWorkspaces": - if e.complexity.ServerConfig.SupportsWorkspaces == nil { - break - } - - return e.complexity.ServerConfig.SupportsWorkspaces(childComplexity), true - - case "ServerConfig.version": - if e.complexity.ServerConfig.Version == nil { - break - } - - return e.complexity.ServerConfig.Version(childComplexity), true - - case "ServerConfig.workspaceId": - if e.complexity.ServerConfig.WorkspaceID == nil { - break - } - - return e.complexity.ServerConfig.WorkspaceID(childComplexity), true - - case "ServerError.causedBy": - if e.complexity.ServerError.CausedBy == nil { - break - } - - return e.complexity.ServerError.CausedBy(childComplexity), true - - case "ServerError.errorCode": - if e.complexity.ServerError.ErrorCode == nil { - break - } - - return e.complexity.ServerError.ErrorCode(childComplexity), true - - case "ServerError.errorType": - if e.complexity.ServerError.ErrorType == nil { - break - } - - return e.complexity.ServerError.ErrorType(childComplexity), true - - case "ServerError.message": - if e.complexity.ServerError.Message == nil { - break - } - - return e.complexity.ServerError.Message(childComplexity), true - - case "ServerError.stackTrace": - if e.complexity.ServerError.StackTrace == nil { - break - } - - return e.complexity.ServerError.StackTrace(childComplexity), true - - case "ServerLanguage.displayName": - if e.complexity.ServerLanguage.DisplayName == nil { - break - } - - return e.complexity.ServerLanguage.DisplayName(childComplexity), true - - case "ServerLanguage.isoCode": - if e.complexity.ServerLanguage.IsoCode == nil { - break - } - - return e.complexity.ServerLanguage.IsoCode(childComplexity), true - - case "ServerLanguage.nativeName": - if e.complexity.ServerLanguage.NativeName == nil { - break - } - - return e.complexity.ServerLanguage.NativeName(childComplexity), true - - case "ServerMessage.message": - if e.complexity.ServerMessage.Message == nil { - break - } - - return e.complexity.ServerMessage.Message(childComplexity), true - - case "ServerMessage.time": - if e.complexity.ServerMessage.Time == nil { - break - } - - return e.complexity.ServerMessage.Time(childComplexity), true - - case "SessionInfo.actionParameters": - if e.complexity.SessionInfo.ActionParameters == nil { - break - } - - return e.complexity.SessionInfo.ActionParameters(childComplexity), true - - case "SessionInfo.cacheExpired": - if e.complexity.SessionInfo.CacheExpired == nil { - break - } - - return e.complexity.SessionInfo.CacheExpired(childComplexity), true - - case "SessionInfo.connections": - if e.complexity.SessionInfo.Connections == nil { - break - } - - return e.complexity.SessionInfo.Connections(childComplexity), true - - case "SessionInfo.createTime": - if e.complexity.SessionInfo.CreateTime == nil { - break - } - - return e.complexity.SessionInfo.CreateTime(childComplexity), true - - case "SessionInfo.lastAccessTime": - if e.complexity.SessionInfo.LastAccessTime == nil { - break - } - - return e.complexity.SessionInfo.LastAccessTime(childComplexity), true - - case "SessionInfo.locale": - if e.complexity.SessionInfo.Locale == nil { - break - } - - return e.complexity.SessionInfo.Locale(childComplexity), true - - case "SessionInfo.serverMessages": - if e.complexity.SessionInfo.ServerMessages == nil { - break - } - - return e.complexity.SessionInfo.ServerMessages(childComplexity), true - - case "UserAuthToken.authConfiguration": - if e.complexity.UserAuthToken.AuthConfiguration == nil { - break - } - - return e.complexity.UserAuthToken.AuthConfiguration(childComplexity), true - - case "UserAuthToken.authProvider": - if e.complexity.UserAuthToken.AuthProvider == nil { - break - } - - return e.complexity.UserAuthToken.AuthProvider(childComplexity), true - - case "UserAuthToken.displayName": - if e.complexity.UserAuthToken.DisplayName == nil { - break - } - - return e.complexity.UserAuthToken.DisplayName(childComplexity), true - - case "UserAuthToken.loginTime": - if e.complexity.UserAuthToken.LoginTime == nil { - break - } - - return e.complexity.UserAuthToken.LoginTime(childComplexity), true - - case "UserAuthToken.message": - if e.complexity.UserAuthToken.Message == nil { - break - } - - return e.complexity.UserAuthToken.Message(childComplexity), true - - case "UserAuthToken.origin": - if e.complexity.UserAuthToken.Origin == nil { - break - } - - return e.complexity.UserAuthToken.Origin(childComplexity), true - - case "UserAuthToken.userId": - if e.complexity.UserAuthToken.UserID == nil { - break - } - - return e.complexity.UserAuthToken.UserID(childComplexity), true - - case "UserInfo.authRole": - if e.complexity.UserInfo.AuthRole == nil { - break - } - - return e.complexity.UserInfo.AuthRole(childComplexity), true - - case "UserInfo.authTokens": - if e.complexity.UserInfo.AuthTokens == nil { - break - } - - return e.complexity.UserInfo.AuthTokens(childComplexity), true - - case "UserInfo.configurationParameters": - if e.complexity.UserInfo.ConfigurationParameters == nil { - break - } - - return e.complexity.UserInfo.ConfigurationParameters(childComplexity), true - - case "UserInfo.displayName": - if e.complexity.UserInfo.DisplayName == nil { - break - } - - return e.complexity.UserInfo.DisplayName(childComplexity), true - - case "UserInfo.linkedAuthProviders": - if e.complexity.UserInfo.LinkedAuthProviders == nil { - break - } - - return e.complexity.UserInfo.LinkedAuthProviders(childComplexity), true - - case "UserInfo.metaParameters": - if e.complexity.UserInfo.MetaParameters == nil { - break - } - - return e.complexity.UserInfo.MetaParameters(childComplexity), true - - case "UserInfo.userId": - if e.complexity.UserInfo.UserID == nil { - break - } - - return e.complexity.UserInfo.UserID(childComplexity), true - - case "WebFeatureSet.description": - if e.complexity.WebFeatureSet.Description == nil { - break - } - - return e.complexity.WebFeatureSet.Description(childComplexity), true - - case "WebFeatureSet.enabled": - if e.complexity.WebFeatureSet.Enabled == nil { - break - } - - return e.complexity.WebFeatureSet.Enabled(childComplexity), true - - case "WebFeatureSet.id": - if e.complexity.WebFeatureSet.ID == nil { - break - } - - return e.complexity.WebFeatureSet.ID(childComplexity), true - - case "WebFeatureSet.icon": - if e.complexity.WebFeatureSet.Icon == nil { - break - } - - return e.complexity.WebFeatureSet.Icon(childComplexity), true - - case "WebFeatureSet.label": - if e.complexity.WebFeatureSet.Label == nil { - break - } - - return e.complexity.WebFeatureSet.Label(childComplexity), true - - case "WebServiceConfig.bundleVersion": - if e.complexity.WebServiceConfig.BundleVersion == nil { - break - } - - return e.complexity.WebServiceConfig.BundleVersion(childComplexity), true - - case "WebServiceConfig.description": - if e.complexity.WebServiceConfig.Description == nil { - break - } - - return e.complexity.WebServiceConfig.Description(childComplexity), true - - case "WebServiceConfig.id": - if e.complexity.WebServiceConfig.ID == nil { - break - } - - return e.complexity.WebServiceConfig.ID(childComplexity), true - - case "WebServiceConfig.name": - if e.complexity.WebServiceConfig.Name == nil { - break - } - - return e.complexity.WebServiceConfig.Name(childComplexity), true - - } - return 0, false -} - -func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { - rc := graphql.GetOperationContext(ctx) - ec := executionContext{rc, e} - inputUnmarshalMap := graphql.BuildUnmarshalerMap( - ec.unmarshalInputConnectionConfig, - ec.unmarshalInputDataTransferParameters, - ec.unmarshalInputNavigatorSettingsInput, - ec.unmarshalInputNetworkHandlerConfigInput, - ec.unmarshalInputObjectPropertyFilter, - ec.unmarshalInputSQLDataFilter, - ec.unmarshalInputSQLDataFilterConstraint, - ec.unmarshalInputSQLResultRow, - ec.unmarshalInputServerConfigInput, - ) - first := true - - switch rc.Operation.Operation { - case ast.Query: - return func(ctx context.Context) *graphql.Response { - if !first { - return nil - } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - data := ec._Query(ctx, rc.Operation.SelectionSet) - var buf bytes.Buffer - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - case ast.Mutation: - return func(ctx context.Context) *graphql.Response { - if !first { - return nil - } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - data := ec._Mutation(ctx, rc.Operation.SelectionSet) - var buf bytes.Buffer - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - - default: - return graphql.OneShot(graphql.ErrorResponse(ctx, "unsupported GraphQL operation")) - } -} - -type executionContext struct { - *graphql.OperationContext - *executableSchema -} - -func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { - if ec.DisableIntrospection { - return nil, errors.New("introspection disabled") - } - return introspection.WrapSchema(parsedSchema), nil -} - -func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { - if ec.DisableIntrospection { - return nil, errors.New("introspection disabled") - } - return introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name]), nil -} - -var sources = []*ast.Source{ - {Name: "../schema/schema.graphqls", Input: `# Any object (JSON) -scalar Object -# Date/Time -scalar DateTime - -type Query - -type Mutation - -schema { - query: Query - mutation: Mutation -} -`, BuiltIn: false}, - {Name: "../schema/service.admin.graphqls", Input: ` -enum AdminSubjectType { - user, - role -} - -type AdminConnectionGrantInfo { - connectionId: ID! @deprecated(reason: "use dataSourceId instead") - dataSourceId: ID! - subjectId: ID! - subjectType: AdminSubjectType! -} - -type AdminConnectionSearchInfo { - displayName: String! - host: String! - port: Int! - possibleDrivers: [ID!]! - defaultDriver: ID! -} - -type AdminUserInfo { - userId: ID! - - metaParameters: Object! - configurationParameters: Object! - grantedRoles: [ID!]! - grantedConnections: [AdminConnectionGrantInfo!]! - - origins: [ObjectOrigin!]! - - linkedAuthProviders: [String!]! - enabled: Boolean! -} - -type AdminRoleInfo { - roleId: ID! - roleName: String - description: String - - grantedUsers: [ID!]! - grantedConnections: [AdminConnectionGrantInfo!]! - - rolePermissions: [ID!]! -} - -type AdminPermissionInfo { - id: ID! - label: String - description: String - - provider: String! - category: String -} - -type AdminAuthProviderConfiguration { - providerId: ID! - id: ID! - displayName: String! - disabled: Boolean! - - iconURL: String - description: String - - parameters: Object! - - signInLink: String - signOutLink: String - redirectLink: String - metadataLink: String -} - -type WebFeatureSet { - id: String! - label: String! - description: String - icon: String - - enabled: Boolean! -} - -input ServerConfigInput { - serverName: String - serverURL: String - - adminName: String - adminPassword: String - - anonymousAccessEnabled: Boolean - authenticationEnabled: Boolean - customConnectionsEnabled: Boolean - publicCredentialsSaveEnabled: Boolean - adminCredentialsSaveEnabled: Boolean - resourceManagerEnabled: Boolean - - enabledFeatures: [ID!] - enabledAuthProviders: [ID!] - disabledDrivers: [ID!] - - sessionExpireTime: Int -} - -extend type Query { - - #### Users and roles - - listUsers(userId: ID): [AdminUserInfo!]! - listRoles(roleId: ID): [AdminRoleInfo!]! - listPermissions: [AdminPermissionInfo!]! - - createUser(userId: ID!): AdminUserInfo! - deleteUser(userId: ID!): Boolean - - createRole(roleId: ID!, roleName: String, description: String): AdminRoleInfo! - updateRole(roleId: ID!, roleName: String, description: String): AdminRoleInfo! - deleteRole(roleId: ID!): Boolean - - grantUserRole(userId: ID!, roleId: ID!): Boolean - revokeUserRole(userId: ID!, roleId: ID!): Boolean - - setSubjectPermissions(roleId: ID!, permissions: [ID!]!): [AdminPermissionInfo!]! - - setUserCredentials(userId: ID!, providerId: ID!, credentials: Object!): Boolean - - enableUser(userId: ID!, enabled: Boolean!): Boolean - - #### Connection management - - # All connection configurations - allConnections( id: ID ): [ ConnectionInfo! ]! - - searchConnections( hostNames: [String!]! ): [AdminConnectionSearchInfo!]! - - createConnectionConfiguration( config: ConnectionConfig! ): ConnectionInfo! - copyConnectionConfiguration( nodePath: String!, config: ConnectionConfig ): ConnectionInfo! - updateConnectionConfiguration( id: ID!, config: ConnectionConfig! ): ConnectionInfo! - deleteConnectionConfiguration( id: ID! ): Boolean - - # Permissions - - getConnectionSubjectAccess(connectionId: ID): [AdminConnectionGrantInfo!]! - setConnectionSubjectAccess(connectionId: ID!, subjects: [ID!]!): Boolean - - getSubjectConnectionAccess(subjectId: ID): [AdminConnectionGrantInfo!]! - setSubjectConnectionAccess(subjectId: ID!, connections: [ID!]!): Boolean - - #### Feature sets - - listFeatureSets: [WebFeatureSet!]! - - #### Auth providers and configurations - - listAuthProviderConfigurationParameters(providerId: ID!): [ObjectPropertyInfo!]! - listAuthProviderConfigurations(providerId: ID): [AdminAuthProviderConfiguration!]! - - saveAuthProviderConfiguration( - providerId: ID!, - id: ID!, - displayName: String, - disabled: Boolean, - iconURL: String - description: String - parameters: Object): AdminAuthProviderConfiguration! - deleteAuthProviderConfiguration(id: ID!): Boolean! - - #### User profile - - saveUserMetaParameter(id: ID!, displayName: String!, description: String, required: Boolean!): ObjectPropertyInfo! - - deleteUserMetaParameter(id: ID!): Boolean! - - setUserMetaParameterValues(userId: ID!, parameters: Object!): Boolean! - - #### Global configuration - - configureServer(configuration: ServerConfigInput!): Boolean! - - # Changes default navigator settings - setDefaultNavigatorSettings( settings: NavigatorSettingsInput!): Boolean! - -} -`, BuiltIn: false}, - {Name: "../schema/service.auth.graphqls", Input: `enum AuthCredentialEncryption { - none, - plain, - hash -} - -enum AuthStatus { - SUCCESS, - IN_PROGRESS, - ERROR -} - -type AuthCredentialInfo { - id: ID! - displayName: String! - description: String - - # This field must be shown in admin panel - admin: Boolean! - # This field must be shown in login form - user: Boolean! - # This field can be used as user identifier - - identifying: Boolean! - possibleValues: [String] - encryption: AuthCredentialEncryption -} - -type AuthProviderConfiguration { - id: ID! - displayName: String! - disabled: Boolean! - - iconURL: String - description: String - - # URL to external authentication service. - # If specified then it is external auhentication provider (SSO). - # Otherwise authLogin function must be called. - signInLink: String - signOutLink: String - metadataLink: String -} - -type AuthProviderCredentialsProfile { - id: String - label: String - description: String - credentialParameters: [AuthCredentialInfo!]! -} - -type AuthProviderInfo { - id: ID! - label: String! - icon: ID - description: String - - defaultProvider: Boolean! - - # Configurable providers must be configured first. See configurations field. - configurable: Boolean! - - # Provider configurations (applicable only if configurable=true) - configurations: [AuthProviderConfiguration!] - - credentialProfiles: [AuthProviderCredentialsProfile!]! - - requiredFeatures: [String!]! -} - -type AuthInfo { - redirectLink: String - - authId: String - - authStatus: AuthStatus! - - userTokens: [UserAuthToken!] -} - -type UserAuthToken { - # Auth provider used for authorization - authProvider: ID! - - # Auth provider configuration ID - authConfiguration: ID - - # Authorization time - loginTime: DateTime! - - # User identity (aka user name) specific to auth provider - userId: String! - - # User display name specific to auth provider - displayName: String! - - # Optional login message - message: String - - # Auth origin - origin: ObjectOrigin! - -} - -type UserInfo { - # User unique identifier - userId: ID! - - # Human readable display name. It is taken from the first auth provider which was used for user login. - displayName: String - # User auth role ID. Optional. - authRole: ID - - # All authentication tokens used during current session - authTokens: [UserAuthToken!]! - - linkedAuthProviders: [String!]! - - # User profile properties map - metaParameters: Object! - # User configuration parameters - configurationParameters: Object! - -} - - -extend type Query { - - # Authorize user using specified auth provider. If linkUser=true then associates new - authLogin(provider: ID!, configuration: ID, credentials: Object, linkUser: Boolean): AuthInfo! - - authUpdateStatus(authId: ID!, linkUser: Boolean): AuthInfo! - - # Logouts user. If provider not specified then all authorizations are revoked from session. - authLogout(provider: ID, configuration: ID): Boolean - - # Active user information. null is no user was authorized within session - activeUser: UserInfo - - authProviders: [AuthProviderInfo!]! - - authChangeLocalPassword(oldPassword: String!, newPassword: String!): Boolean! - - listUserProfileProperties: [ObjectPropertyInfo!]! - -} - -extend type Mutation { - - # Set user config parameter. If parameter value is null then removes the parameter - setUserConfigurationParameter(name: String!, value: Object): Boolean! - -} -`, BuiltIn: false}, - {Name: "../schema/service.core.graphqls", Input: ` -#################################################### -# General stuff -#################################################### - -# Property - -type ObjectPropertyInfo { - # ID - id: String - # Human readable name - displayName: String - # Property description - description: String - # Property category (may be used if object has a lot of properties) - category: String - # Property data type (int, String, etc) - dataType: String - - # Property value. Note: for some properties value reading may take a lot of time (e.g. RowCount for tables) - value: Object - - # List of values this property can take. Makes sense only for enumerable properties - validValues: [ Object ] - # Default property value - defaultValue: Object - - # Property value length - length: ObjectPropertyLength! - - # Supported features (system, hidden, inherited, foreign, expensive, etc) - features: [ String! ]! - # Order position - order: Int! -} - -enum ObjectPropertyLength { - # 1 character - TINY, - # 20 characters - SHORT, - # <= 64 characters - MEDIUM, - # Full line length. The default - LONG, - # Multi-line long text - MULTILINE -} - -# Async types - -type AsyncTaskInfo { - id: String! - name: String - running: Boolean! - - status: String - error: ServerError - - result: SQLExecuteInfo @deprecated # Deprecated. Use asyncSqlExecuteResults instead - # Task result. - # Can be some kind of identifier to obtain real result using another API function - taskResult: Object -} - -# Various server errors descriptor - -type ServerError { - message: String - errorCode: String - errorType: String - stackTrace: String - causedBy: ServerError -} - -type ServerMessage { - time: String - message: String -} - -# Languages supported by server - -type ServerLanguage { - isoCode: String! - displayName: String - nativeName: String -} - -type WebServiceConfig { - id: String! - name: String! - description: String! - bundleVersion: String! -} - -type ProductInfo { - id: ID! - version: String! - name: String! - description: String - buildTime: String! - releaseTime: String! - licenseInfo: String - - latestVersionInfo: String -} - -type ServerConfig { - name: String! - version: String! - workspaceId: ID! - - serverURL: String! - - rootURI: String! - - hostName: String! - - anonymousAccessEnabled: Boolean - authenticationEnabled: Boolean @deprecated - supportsCustomConnections: Boolean - supportsConnectionBrowser: Boolean - supportsWorkspaces: Boolean - resourceManagerEnabled: Boolean - - publicCredentialsSaveEnabled: Boolean - adminCredentialsSaveEnabled: Boolean - - licenseRequired: Boolean! - licenseValid: Boolean! - - sessionExpireTime: Int - localHostAddress: String - - configurationMode: Boolean - developmentMode: Boolean - redirectOnFederatedAuth: Boolean - - enabledFeatures: [ID!]! - enabledAuthProviders: [ID!]! - supportedLanguages: [ ServerLanguage! ]! - services: [ WebServiceConfig ] - productConfiguration: Object! - productInfo: ProductInfo! - defaultNavigatorSettings: NavigatorSettings! - disabledDrivers: [ID!]! - resourceQuotas: Object! -} - -type SessionInfo { - createTime: String! - lastAccessTime: String! - locale: String! - - cacheExpired: Boolean! - - serverMessages: [ ServerMessage ] - connections: [ ConnectionInfo! ]! - actionParameters: Object -} - -#################################################### -# Drivers and connections -#################################################### - -type DatabaseAuthModel { - id: ID! - displayName: String! - description: String - icon: String - # checks if the auth model needs a configuration on a local file system - requiresLocalConfiguration: Boolean - - properties: [ObjectPropertyInfo!]! -} - -type DriverInfo { - id: ID! - name: String - description: String - icon: String - iconBig: String - - # Driver provider ID - providerId: ID - # Driver Java class name - driverClassName: String - defaultHost: String - defaultPort: String - defaultDatabase: String - defaultServer: String - defaultUser: String - sampleURL: String - driverInfoURL: String - driverPropertiesURL: String - embedded: Boolean - enabled: Boolean! - requiresServerName: Boolean - - # this fields must be removed and be replaced by DriverAuthModel - allowsEmptyPassword: Boolean @deprecated - - licenseRequired: Boolean - license: String - custom: Boolean - # Driver score for ordering, biggest first - promotedScore: Int - - # Never used? - #connectionProperties: Object - #defaultConnectionProperties: Object - - # Driver properties. - # Note: it is expensive property and it may produce database server roundtrips. - # Call it only when you really need it. - # These properties are for advanced users in usually shouldn't be specified for new connections. - driverProperties: [ObjectPropertyInfo!]! - # Driver parameters (map name->value) - driverParameters: Object! - - # Additional driver provider properties - # These properties can be configured by user on main connection page - # to provide important connection settings - providerProperties: [ObjectPropertyInfo!]! - - # False for drivers which do not support authentication - anonymousAccess: Boolean - - defaultAuthModel: ID! - applicableAuthModels: [ID!]! - - applicableNetworkHandlers: [ID]! -} - -enum ResultDataFormat { - resultset, - document, - graph, - timeseries -} - -## Network handler config - -enum NetworkHandlerType { - TUNNEL, - PROXY, - CONFIG -} - -enum NetworkHandlerAuthType { - PASSWORD, - PUBLIC_KEY, - AGENT -} - -type NetworkHandlerDescriptor { - id: ID! - codeName: String! - label: String! - description: String - secured: Boolean! - type: NetworkHandlerType - properties: [ObjectPropertyInfo!]! -} - -type NetworkHandlerConfig { - id: ID! - enabled: Boolean! - authType: NetworkHandlerAuthType! - userName: String - password: String - key: String - savePassword: Boolean! - properties: Object! -} - -# Connection instance -type ConnectionInfo { - id: ID! - driverId: ID! - - name: String! - description: String - - host: String - port: String - serverName: String - databaseName: String - url: String - - properties: Object - - template: Boolean! - connected: Boolean! - provided: Boolean! - readOnly: Boolean! - useUrl: Boolean! - saveCredentials: Boolean! - - folder: ID - nodePath: String - - connectTime: String - connectionError: ServerError - serverVersion: String - clientVersion: String - - origin: ObjectOrigin! - - authNeeded: Boolean! - authModel: ID - authProperties: [ObjectPropertyInfo!]! - - providerProperties: Object! - networkHandlersConfig: [NetworkHandlerConfig!]! - - # Supported features (provided etc) - features: [ String! ]! - navigatorSettings: NavigatorSettings! - supportedDataFormats: [ ResultDataFormat! ]! -} - -type ConnectionFolderInfo { - id: ID! - description: String -} - -type NetworkEndpointInfo { - message: String - clientVersion: String - serverVersion: String -} - -type ObjectOrigin { - type: ID! - subType: ID - displayName: String! - icon: String - configuration: Object - details: [ObjectPropertyInfo!] -} - -type NavigatorSettings { - showSystemObjects: Boolean! - showUtilityObjects: Boolean! - showOnlyEntities: Boolean! - mergeEntities: Boolean! - hideFolders: Boolean! - hideSchemas: Boolean! - hideVirtualModel: Boolean! -} - -type LogEntry { - time: DateTime - type: String! - message: String - stackTrace: String -} - -#################################################### -# Input types -#################################################### - -input NavigatorSettingsInput { - showSystemObjects: Boolean! - showUtilityObjects: Boolean! - showOnlyEntities: Boolean! - mergeEntities: Boolean! - hideFolders: Boolean! - hideSchemas: Boolean! - hideVirtualModel: Boolean! -} - -input NetworkHandlerConfigInput { - id: ID! - enabled: Boolean - authType: NetworkHandlerAuthType - userName: String - password: String - key: String - savePassword: Boolean - properties: Object -} - -# Configuration of particular connection. Used for new connection create. Includes auth info -input ConnectionConfig { - # used only for testing created connection - connectionId: String - name: String - description: String - - # ID of template connection - templateId: ID - # ID of database driver - driverId: ID - - # Custom connection parameters (all optional) - - host: String - port: String - serverName: String - databaseName: String - # Connection url jdbc:{driver}://{host}[:{port}]/[{database}] - url: String - # Properties - properties: Object - - # Template connection - template: Boolean - # Read-onyl connection - readOnly: Boolean - - # User credentials - - saveCredentials: Boolean - authModelId: ID - credentials: Object - - # Map of provider properties (name/value) - - providerProperties: Object - - # Network handlers. Map of id->property map (name/value). - - networkHandlersConfig: [NetworkHandlerConfigInput!] - - #### deprecated fields - - # ID of predefined datasource - dataSourceId: ID #@deprecated - - # Direct user credentials - userName: String #@deprecated - userPassword: String #@deprecated - - # Folder - folder: ID -} - -#################################################### -# Main API -#################################################### - -extend type Query { - # Returns server config - serverConfig: ServerConfig! - - # Returns session state ( initialize if not ) - sessionState: SessionInfo! - - # Session permissions - sessionPermissions: [ID]! - - # Get driver info - driverList( id: ID ): [ DriverInfo! ]! - authModels: [DatabaseAuthModel!]! - networkHandlers: [NetworkHandlerDescriptor!]! - - # List of user connections. - userConnections( id: ID ): [ ConnectionInfo! ]! - # List of template connections. - templateConnections: [ ConnectionInfo! ]! - - # List of connection folders - connectionFolders( path: ID ): [ ConnectionFolderInfo! ]! - - # Return connection state - connectionState( id: ID! ): ConnectionInfo! @deprecated - - # Return connection info - connectionInfo( id: ID! ): ConnectionInfo! - - readSessionLog(maxEntries: Int, clearEntries: Boolean): [ LogEntry! ]! -} - -extend type Mutation { - # Initialize session - openSession(defaultLocale: String): SessionInfo! - - # Destroy session - closeSession: Boolean - - # Refreshes session on server and returns its state - touchSession: Boolean - - # Refresh session connection list - refreshSessionConnections: Boolean - - # Refreshes session on server and returns its state - changeSessionLanguage(locale: String): Boolean - - # Create new custom connection. Custom connections exist only within the current session. - createConnection( config: ConnectionConfig! ): ConnectionInfo! - - updateConnection( config: ConnectionConfig! ): ConnectionInfo! - - deleteConnection( id: ID! ): Boolean! - - createConnectionFromTemplate( templateId: ID!, connectionName: String ): ConnectionInfo! - - # Create new folder - createConnectionFolder(parentFolderPath: ID, folderName: String! ): ConnectionFolderInfo! - - deleteConnectionFolder( folderPath: ID! ): Boolean! - - # Copies connection configuration from node - copyConnectionFromNode( nodePath: String!, config: ConnectionConfig ): ConnectionInfo! - - # Test connection configuration. Returns remote server version - testConnection( config: ConnectionConfig! ): ConnectionInfo! - - # Test connection configuration. Returns remote server version - testNetworkHandler( config: NetworkHandlerConfigInput! ): NetworkEndpointInfo! - - # Initiate existing connection - initConnection( id: ID!, credentials: Object, networkCredentials: [NetworkHandlerConfigInput!], saveCredentials: Boolean ): ConnectionInfo! - - # Disconnect from database - closeConnection( id: ID! ): ConnectionInfo! - - # Changes navigator settings for connection - setConnectionNavigatorSettings( id: ID!, settings: NavigatorSettingsInput!): ConnectionInfo! - - #### Generic async functions - - asyncTaskCancel(id: String!): Boolean - - asyncTaskInfo(id: String!, removeOnFinish: Boolean!): AsyncTaskInfo! - - - #### Deprecated API - - # Create connection from template. Use createConnection instead - openConnection( config: ConnectionConfig! ): ConnectionInfo! @deprecated - - # Use asyncTaskInfo instead - asyncTaskStatus(id: String!): AsyncTaskInfo! @deprecated - -} - -`, BuiltIn: false}, - {Name: "../schema/service.data.transfer.graphqls", Input: `# Data transfer queries - -type DataTransferProcessorInfo { - id: ID! - name: String - description: String - fileExtension: String - appFileExtension: String - appName: String - order: Int! - icon: String - properties: [ ObjectPropertyInfo ] - isBinary: Boolean - isHTML: Boolean -} - -input DataTransferParameters { - # Processor ID - processorId: ID! - # General settings: - # - openNewConnection: opens new database connection for data transfer task - settings: Object - # Processor properties. See DataTransferProcessorInfo.properties - processorProperties: Object! - # Data filter settings - filter: SQLDataFilter -} - -extend type Query { - - # Available transfer processors - dataTransferAvailableStreamProcessors: [ DataTransferProcessorInfo! ]! - - dataTransferExportDataFromContainer( - connectionId: ID!, - containerNodePath: ID!, - parameters: DataTransferParameters! - ): AsyncTaskInfo! - - dataTransferExportDataFromResults( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - parameters: DataTransferParameters! - ): AsyncTaskInfo! - - dataTransferRemoveDataFile(dataFileId: String!): Boolean - -} -`, BuiltIn: false}, - {Name: "../schema/service.metadata.graphqls", Input: `# Metadata queries - -extend type Query { - - # Get child nodes - metadataGetNodeDDL(nodeId: ID!, options: Object): String - -} -`, BuiltIn: false}, - {Name: "../schema/service.navigator.graphqls", Input: `# Nodes, objects and properties - -type ObjectDescriptor { - id: Int - displayName: String - fullName: String - uniqueName: String - description: String - value: String -} - -input ObjectPropertyFilter { - ids: [String!] - features: [String!] - categories: [String!] - dataTypes: [String!] -} - -type ObjectDetails { - id: Int - displayName: String - description: String - value: Object -} - -type DatabaseObjectInfo { - # Object name - name: String - # Description - optional - description: String - # Object type. Java class name in most cases - type: String - - # Read object properties. - # Optional parameter 'ids' filters properties by id. null means all properties. - # Note: property value reading may take a lot of time so don't read all property values always - # Examine property meta (features in particular) before reading them - properties(filter: ObjectPropertyFilter): [ ObjectPropertyInfo ] - - # Optional properties - - ordinalPosition: Int - fullyQualifiedName: String - overloadedName: String - uniqueName: String - state: String - - # Features: script, scriptExtended, dataContainer, dataManipulator, - # entity, schema, catalog - features: [ String! ] - - # Supported editors: ddl, permissions, sourceDeclaration, sourceDefinition - editors: [ String! ] -} - -type NavigatorNodeInfo { - # Node ID - generally a full path to the node from root of tree - id: ID! - # Node human readable name - name: String - #Node full name - fullName: String - # Node icon path - icon: String - # Node description - description: String - # Node type - nodeType: String - # Can this property have child nodes? - hasChildren: Boolean - - # Associated object. Maybe null for non-database objects - object: DatabaseObjectInfo - - # Supported features: item, container, leaf - # canDelete, canRename - features: [ String! ] - - # Object detailed info. - # If is different than properties. It doesn't perform any expensive operation and doesn't require authentication. - nodeDetails: [ ObjectPropertyInfo! ] - - folder: Boolean - inline: Boolean - navigable: Boolean -} - -type DatabaseCatalog { - catalog: NavigatorNodeInfo! - schemaList: [ NavigatorNodeInfo! ]! -} - -type DatabaseStructContainers { - catalogList: [ DatabaseCatalog! ]! - schemaList: [ NavigatorNodeInfo! ]! - supportsCatalogChange: Boolean! - supportsSchemaChange: Boolean! -} - -#################################################### -# Main API -#################################################### - -extend type Query { - - # Get child nodes - navNodeChildren( - parentPath: ID!, - offset: Int, - limit: Int, - onlyFolders: Boolean): [ NavigatorNodeInfo! ]! - - # Get child nodes - navNodeParents(nodePath: ID!): [ NavigatorNodeInfo! ]! - - navNodeInfo( nodePath: ID! ): NavigatorNodeInfo! - - navRefreshNode( nodePath: ID! ): Boolean - - # contextId currently not using - navGetStructContainers( connectionId: ID!, contextId: ID, catalog: ID ): DatabaseStructContainers! - -} - -extend type Mutation { - - # Rename node and returns new node name - navRenameNode( nodePath: ID!, newName: String! ): String - - # Deletes nodes with specified IDs and returns number of deleted nodes - navDeleteNodes( nodePaths: [ID!]! ): Int - - # Moves nodes with specified IDs to the connection folder - navMoveNodesToFolder(nodePaths: [ID!]!, folderPath: ID!): Boolean - -}`, BuiltIn: false}, - {Name: "../schema/service.rm.graphqls", Input: `# Metadata queries - -type RMProject { - id: String! - name: String! - description: String - shared: Boolean! - - createTime: DateTime! - creator: String! -} - -type RMResource { - name: String! - folder: Boolean! - length: Int! -} - -extend type Query { - - # List accessible projects - rmListProjects: [RMProject!]! - - # List accessible projects - rmListResources( - projectId: String!, - folder: String, - nameMask: String, - readProperties: Boolean, - readHistory: Boolean): [RMResource!]! - - # Reads resource contents as string in UTF-8 - rmReadResourceAsString( - projectId: String!, - resourcePath: String!): String! - -} - -extend type Mutation { - - rmCreateResource( - projectId: String!, - resourcePath: String!, - isFolder: Boolean!): String! - - rmMoveResource( - projectId: String!, - oldResourcePath: String!, - newResourcePath: String): String! - - rmDeleteResource( - projectId: String!, - resourcePath: String!, - recursive: Boolean!): Boolean - - rmWriteResourceStringContent( - projectId: String!, - resourcePath: String!, - data: String!): String! -}`, BuiltIn: false}, - {Name: "../schema/service.sql.graphqls", Input: `#################################################### -# SQL helpers -#################################################### - -type SQLDialectInfo { - name: String! - - dataTypes: [ String ]! - functions: [ String ]! - reservedWords: [ String ]! - quoteStrings: [ [ String ] ]! - singleLineComments: [ String ]! - multiLineComments: [ [ String ] ]! - - catalogSeparator: String - structSeparator: String - scriptDelimiter: String - - supportsExplainExecutionPlan: Boolean! - -} - -type SQLCompletionProposal { - displayString: String! - type: String! - score: Int - - replacementString: String! - replacementOffset: Int! - replacementLength: Int! - cursorPosition: Int - - icon: String - nodePath: String -} - -#################################################### -# Data read / SQL execution -#################################################### - -# SQL context must be created for each SQL editor -type SQLContextInfo { - - id: ID! - connectionId: ID! - defaultCatalog: String - defaultSchema: String - -} - -input SQLDataFilterConstraint { - attributePosition: Int! - orderPosition: Int - orderAsc: Boolean - - criteria: String - operator: String - value: Object -} - -input SQLDataFilter { - # Row offset. We use Float because offset may be bigger than 32 bit. - offset: Float - limit: Int - - constraints: [ SQLDataFilterConstraint ] - where: String - orderBy: String -} - -type SQLResultColumn { - position: Int! - name: String - label: String - icon: String - entityName: String - - dataKind: String - typeName: String - fullTypeName: String - # Column value max length. We use Float because it may be bigger than 32 bit. - maxLength: Float - scale: Int - precision: Int - - required: Boolean! - - readOnly: Boolean! - readOnlyStatus: String - - # Operations supported for this attribute - supportedOperations: [DataTypeLogicalOperation!]! -} - -type DatabaseDocument { - id: String - contentType: String - properties: Object - data: Object -} - -type SQLResultSet { - id: ID! - columns: [ SQLResultColumn ] - rows: [ [ Object ] ] - - # True means that resultset was generated by single entity query - # New rows can be added, old rows can be deleted - singleEntity: Boolean! - # server always returns hasMoreData = false - hasMoreData: Boolean! - # can't update data or load LOB file if hasRowIdentifier = false - hasRowIdentifier: Boolean! -} - -type SQLQueryResults { - title: String - updateRowCount: Float - sourceQuery: String - - # Actual data format of this result - dataFormat: ResultDataFormat - - resultSet: SQLResultSet -} - -type SQLExecuteInfo { - - # Status message - statusMessage: String - # Execute time (ms) - duration: Int! - # Actual conditions applied to query - filterText: String - # Results - results: [ SQLQueryResults! ]! -} - -input SQLResultRow { - data: [ Object ]! - updateValues: Object -} - -type DataTypeLogicalOperation { - id: ID! - expression: String! - argumentCount: Int -} - -#################################################### -# SQL Execution plan -#################################################### - -type SQLExecutionPlan { - query: String! - nodes: [SQLExecutionPlanNode!]! -} - -type SQLExecutionPlanNode { - id: ID! - parentId: ID - - kind: String! - name: String - type: String! - condition: String - description: String - properties: [ObjectPropertyInfo!]! -} - -#################################################### -# SQL Generation -#################################################### - -type SQLQueryGenerator { - id: String! - label: String! - description: String - order: Int! - multiObject: Boolean! -} - -#################################################### -# SQL Query info -#################################################### -type SQLScriptInfo { - queries: [ SQLScriptQuery! ]! -} - -type SQLScriptQuery { - start: Int! - end: Int! -} -#################################################### -# Query and Mutation -#################################################### - -extend type Query { - - sqlDialectInfo( connectionId: ID! ): SQLDialectInfo - - # Lists SQL contexts for a connection (optional) or returns the particular context info - sqlListContexts( connectionId: ID, contextId: ID ): [ SQLContextInfo ]! - - sqlCompletionProposals( - connectionId: ID!, - contextId: ID!, - query: String!, - position: Int!, - maxResults: Int, - simpleMode: Boolean - ): [ SQLCompletionProposal ] - - sqlFormatQuery( - connectionId: ID!, - contextId: ID!, - query: String! - ): String! - - sqlSupportedOperations( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - attributeIndex: Int! - ): [DataTypeLogicalOperation!]! - - # List of all available entity query generators - sqlEntityQueryGenerators(nodePathList: [String!]! - ): [SQLQueryGenerator!]! - - # Options: - # fullyQualifiedNames: Boolean - # compactSQL: Boolean - # showComments: Boolean - # showPermissions: Boolean - # showFullDdl: Boolean - # excludeAutoGeneratedColumn: Boolean - # useCustomDataFormat: Boolean - sqlGenerateEntityQuery( - generatorId: String!, - options: Object!, - nodePathList: [String!]! - ): String! - - sqlParseScript( - connectionId: ID!, - script: String! - ): SQLScriptInfo! - - sqlParseQuery( - connectionId: ID!, - script: String!, - position: Int! - ): SQLScriptQuery! -} - -extend type Mutation { - sqlContextCreate( connectionId: ID!, defaultCatalog: String, defaultSchema: String ): SQLContextInfo! - - sqlContextSetDefaults( connectionId: ID!, contextId: ID!, defaultCatalog: ID, defaultSchema: ID ): Boolean! - - sqlContextDestroy( connectionId: ID!, contextId: ID! ): Boolean! - - # Execute SQL and return results - asyncSqlExecuteQuery( - projectId: ID, - connectionId: ID!, - contextId: ID!, - sql: String!, - resultId: ID, - filter: SQLDataFilter, - dataFormat: ResultDataFormat, # requested data format. May be ignored by server - readLogs: Boolean # added 23.2.1 - ): AsyncTaskInfo! - - # Read data from table - asyncReadDataFromContainer( - connectionId: ID!, - contextId: ID!, - containerNodePath: ID!, - resultId: ID, - filter: SQLDataFilter, - dataFormat: ResultDataFormat - ): AsyncTaskInfo! - - # Close results (free resources) - sqlResultClose(connectionId: ID!, contextId: ID!, resultId: ID!): Boolean! - - # Update multiple cell values - updateResultsDataBatch( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - - updatedRows: [ SQLResultRow! ], - deletedRows: [ SQLResultRow! ], - addedRows: [ SQLResultRow! ], - ): SQLExecuteInfo! - - # Return SQL script for cell values update - updateResultsDataBatchScript( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - - updatedRows: [ SQLResultRow! ], - deletedRows: [ SQLResultRow! ], - addedRows: [ SQLResultRow! ], - ): String! - - #Return BLOB name - readLobValue( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - lobColumnIndex: Int!, - row: [ SQLResultRow! ]! - ): String! - - # Returns SQLExecuteInfo - asyncSqlExecuteResults(taskId: ID!): SQLExecuteInfo ! - - # Read data from table - asyncSqlExplainExecutionPlan( - connectionId: ID!, - contextId: ID!, - query: String!, - configuration: Object! - ): AsyncTaskInfo! - - # Returns SQLExecutionPlan - asyncSqlExplainExecutionPlanResult(taskId: ID!): SQLExecutionPlan ! - -} -`, BuiltIn: false}, -} -var parsedSchema = gqlparser.MustLoadSchema(sources...) - -// endregion ************************** generated!.gotpl ************************** - -// region ***************************** args.gotpl ***************************** - -func (ec *executionContext) field_DatabaseObjectInfo_properties_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *model.ObjectPropertyFilter - if tmp, ok := rawArgs["filter"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filter")) - arg0, err = ec.unmarshalOObjectPropertyFilter2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyFilter(ctx, tmp) - if err != nil { - return nil, err - } - } - args["filter"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_asyncReadDataFromContainer_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["containerNodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("containerNodePath")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["containerNodePath"] = arg2 - var arg3 *string - if tmp, ok := rawArgs["resultId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultId")) - arg3, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultId"] = arg3 - var arg4 *model.SQLDataFilter - if tmp, ok := rawArgs["filter"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filter")) - arg4, err = ec.unmarshalOSQLDataFilter2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDataFilter(ctx, tmp) - if err != nil { - return nil, err - } - } - args["filter"] = arg4 - var arg5 *model.ResultDataFormat - if tmp, ok := rawArgs["dataFormat"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataFormat")) - arg5, err = ec.unmarshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx, tmp) - if err != nil { - return nil, err - } - } - args["dataFormat"] = arg5 - return args, nil -} - -func (ec *executionContext) field_Mutation_asyncSqlExecuteQuery_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg2 - var arg3 string - if tmp, ok := rawArgs["sql"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("sql")) - arg3, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["sql"] = arg3 - var arg4 *string - if tmp, ok := rawArgs["resultId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultId")) - arg4, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultId"] = arg4 - var arg5 *model.SQLDataFilter - if tmp, ok := rawArgs["filter"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filter")) - arg5, err = ec.unmarshalOSQLDataFilter2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDataFilter(ctx, tmp) - if err != nil { - return nil, err - } - } - args["filter"] = arg5 - var arg6 *model.ResultDataFormat - if tmp, ok := rawArgs["dataFormat"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataFormat")) - arg6, err = ec.unmarshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx, tmp) - if err != nil { - return nil, err - } - } - args["dataFormat"] = arg6 - var arg7 *bool - if tmp, ok := rawArgs["readLogs"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("readLogs")) - arg7, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["readLogs"] = arg7 - return args, nil -} - -func (ec *executionContext) field_Mutation_asyncSqlExecuteResults_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["taskId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("taskId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["taskId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_asyncSqlExplainExecutionPlanResult_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["taskId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("taskId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["taskId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_asyncSqlExplainExecutionPlan_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["query"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("query")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["query"] = arg2 - var arg3 interface{} - if tmp, ok := rawArgs["configuration"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configuration")) - arg3, err = ec.unmarshalNObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["configuration"] = arg3 - return args, nil -} - -func (ec *executionContext) field_Mutation_asyncTaskCancel_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_asyncTaskInfo_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - var arg1 bool - if tmp, ok := rawArgs["removeOnFinish"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("removeOnFinish")) - arg1, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["removeOnFinish"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_asyncTaskStatus_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_changeSessionLanguage_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["locale"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("locale")) - arg0, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["locale"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_closeConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_copyConnectionFromNode_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePath"] = arg0 - var arg1 *model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg1, err = ec.unmarshalOConnectionConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_createConnectionFolder_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["parentFolderPath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parentFolderPath")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["parentFolderPath"] = arg0 - var arg1 string - if tmp, ok := rawArgs["folderName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folderName")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["folderName"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_createConnectionFromTemplate_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["templateId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("templateId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["templateId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["connectionName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionName")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionName"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_createConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_deleteConnectionFolder_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["folderPath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folderPath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["folderPath"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_deleteConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_initConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["credentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("credentials")) - arg1, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["credentials"] = arg1 - var arg2 []*model.NetworkHandlerConfigInput - if tmp, ok := rawArgs["networkCredentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("networkCredentials")) - arg2, err = ec.unmarshalONetworkHandlerConfigInput2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigInputᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["networkCredentials"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["saveCredentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("saveCredentials")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["saveCredentials"] = arg3 - return args, nil -} - -func (ec *executionContext) field_Mutation_navDeleteNodes_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 []string - if tmp, ok := rawArgs["nodePaths"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePaths")) - arg0, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePaths"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_navMoveNodesToFolder_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 []string - if tmp, ok := rawArgs["nodePaths"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePaths")) - arg0, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePaths"] = arg0 - var arg1 string - if tmp, ok := rawArgs["folderPath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folderPath")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["folderPath"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_navRenameNode_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePath"] = arg0 - var arg1 string - if tmp, ok := rawArgs["newName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("newName")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["newName"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_openConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_openSession_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["defaultLocale"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultLocale")) - arg0, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["defaultLocale"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_readLobValue_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultsId"] = arg2 - var arg3 int - if tmp, ok := rawArgs["lobColumnIndex"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("lobColumnIndex")) - arg3, err = ec.unmarshalNInt2int(ctx, tmp) - if err != nil { - return nil, err - } - } - args["lobColumnIndex"] = arg3 - var arg4 []*model.SQLResultRow - if tmp, ok := rawArgs["row"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("row")) - arg4, err = ec.unmarshalNSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["row"] = arg4 - return args, nil -} - -func (ec *executionContext) field_Mutation_rmCreateResource_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["resourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resourcePath"] = arg1 - var arg2 bool - if tmp, ok := rawArgs["isFolder"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("isFolder")) - arg2, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["isFolder"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Mutation_rmDeleteResource_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["resourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resourcePath"] = arg1 - var arg2 bool - if tmp, ok := rawArgs["recursive"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("recursive")) - arg2, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["recursive"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Mutation_rmMoveResource_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["oldResourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("oldResourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["oldResourcePath"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["newResourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("newResourcePath")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["newResourcePath"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Mutation_rmWriteResourceStringContent_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["resourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resourcePath"] = arg1 - var arg2 string - if tmp, ok := rawArgs["data"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("data")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["data"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Mutation_setConnectionNavigatorSettings_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - var arg1 model.NavigatorSettingsInput - if tmp, ok := rawArgs["settings"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("settings")) - arg1, err = ec.unmarshalNNavigatorSettingsInput2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorSettingsInput(ctx, tmp) - if err != nil { - return nil, err - } - } - args["settings"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_setUserConfigurationParameter_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["name"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["name"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["value"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("value")) - arg1, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["value"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_sqlContextCreate_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["defaultCatalog"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultCatalog")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["defaultCatalog"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["defaultSchema"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultSchema")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["defaultSchema"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Mutation_sqlContextDestroy_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Mutation_sqlContextSetDefaults_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["defaultCatalog"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultCatalog")) - arg2, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["defaultCatalog"] = arg2 - var arg3 *string - if tmp, ok := rawArgs["defaultSchema"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultSchema")) - arg3, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["defaultSchema"] = arg3 - return args, nil -} - -func (ec *executionContext) field_Mutation_sqlResultClose_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultId"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Mutation_testConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_testNetworkHandler_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.NetworkHandlerConfigInput - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNNetworkHandlerConfigInput2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigInput(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_updateConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Mutation_updateResultsDataBatchScript_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultsId"] = arg2 - var arg3 []*model.SQLResultRow - if tmp, ok := rawArgs["updatedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("updatedRows")) - arg3, err = ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["updatedRows"] = arg3 - var arg4 []*model.SQLResultRow - if tmp, ok := rawArgs["deletedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("deletedRows")) - arg4, err = ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["deletedRows"] = arg4 - var arg5 []*model.SQLResultRow - if tmp, ok := rawArgs["addedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addedRows")) - arg5, err = ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["addedRows"] = arg5 - return args, nil -} - -func (ec *executionContext) field_Mutation_updateResultsDataBatch_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultsId"] = arg2 - var arg3 []*model.SQLResultRow - if tmp, ok := rawArgs["updatedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("updatedRows")) - arg3, err = ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["updatedRows"] = arg3 - var arg4 []*model.SQLResultRow - if tmp, ok := rawArgs["deletedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("deletedRows")) - arg4, err = ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["deletedRows"] = arg4 - var arg5 []*model.SQLResultRow - if tmp, ok := rawArgs["addedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addedRows")) - arg5, err = ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["addedRows"] = arg5 - return args, nil -} - -func (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["name"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["name"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_allConnections_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_authChangeLocalPassword_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["oldPassword"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("oldPassword")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["oldPassword"] = arg0 - var arg1 string - if tmp, ok := rawArgs["newPassword"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("newPassword")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["newPassword"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_authLogin_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["provider"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("provider")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["provider"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["configuration"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configuration")) - arg1, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["configuration"] = arg1 - var arg2 interface{} - if tmp, ok := rawArgs["credentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("credentials")) - arg2, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["credentials"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["linkUser"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("linkUser")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["linkUser"] = arg3 - return args, nil -} - -func (ec *executionContext) field_Query_authLogout_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["provider"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("provider")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["provider"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["configuration"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configuration")) - arg1, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["configuration"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_authUpdateStatus_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["authId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("authId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["authId"] = arg0 - var arg1 *bool - if tmp, ok := rawArgs["linkUser"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("linkUser")) - arg1, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["linkUser"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_configureServer_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.ServerConfigInput - if tmp, ok := rawArgs["configuration"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configuration")) - arg0, err = ec.unmarshalNServerConfigInput2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerConfigInput(ctx, tmp) - if err != nil { - return nil, err - } - } - args["configuration"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_connectionFolders_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["path"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("path")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["path"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_connectionInfo_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_connectionState_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_copyConnectionConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePath"] = arg0 - var arg1 *model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg1, err = ec.unmarshalOConnectionConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_createConnectionConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_createRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["roleName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleName")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleName"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["description"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["description"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Query_createUser_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["userId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_dataTransferExportDataFromContainer_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["containerNodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("containerNodePath")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["containerNodePath"] = arg1 - var arg2 model.DataTransferParameters - if tmp, ok := rawArgs["parameters"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parameters")) - arg2, err = ec.unmarshalNDataTransferParameters2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTransferParameters(ctx, tmp) - if err != nil { - return nil, err - } - } - args["parameters"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Query_dataTransferExportDataFromResults_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultsId"] = arg2 - var arg3 model.DataTransferParameters - if tmp, ok := rawArgs["parameters"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parameters")) - arg3, err = ec.unmarshalNDataTransferParameters2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTransferParameters(ctx, tmp) - if err != nil { - return nil, err - } - } - args["parameters"] = arg3 - return args, nil -} - -func (ec *executionContext) field_Query_dataTransferRemoveDataFile_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["dataFileId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataFileId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["dataFileId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_deleteAuthProviderConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_deleteConnectionConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_deleteRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_deleteUserMetaParameter_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_deleteUser_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["userId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_driverList_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_enableUser_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["userId"] = arg0 - var arg1 bool - if tmp, ok := rawArgs["enabled"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabled")) - arg1, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["enabled"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_getConnectionSubjectAccess_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_getSubjectConnectionAccess_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["subjectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("subjectId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["subjectId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_grantUserRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["userId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleId"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_listAuthProviderConfigurationParameters_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["providerId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["providerId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_listAuthProviderConfigurations_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["providerId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["providerId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_listRoles_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_listUsers_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["userId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_metadataGetNodeDDL_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodeId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodeId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodeId"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["options"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("options")) - arg1, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["options"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_navGetStructContainers_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["catalog"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("catalog")) - arg2, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["catalog"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Query_navNodeChildren_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["parentPath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parentPath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["parentPath"] = arg0 - var arg1 *int - if tmp, ok := rawArgs["offset"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("offset")) - arg1, err = ec.unmarshalOInt2ᚖint(ctx, tmp) - if err != nil { - return nil, err - } - } - args["offset"] = arg1 - var arg2 *int - if tmp, ok := rawArgs["limit"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("limit")) - arg2, err = ec.unmarshalOInt2ᚖint(ctx, tmp) - if err != nil { - return nil, err - } - } - args["limit"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["onlyFolders"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("onlyFolders")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["onlyFolders"] = arg3 - return args, nil -} - -func (ec *executionContext) field_Query_navNodeInfo_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePath"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_navNodeParents_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePath"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_navRefreshNode_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePath"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_readSessionLog_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *int - if tmp, ok := rawArgs["maxEntries"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("maxEntries")) - arg0, err = ec.unmarshalOInt2ᚖint(ctx, tmp) - if err != nil { - return nil, err - } - } - args["maxEntries"] = arg0 - var arg1 *bool - if tmp, ok := rawArgs["clearEntries"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearEntries")) - arg1, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["clearEntries"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_revokeUserRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["userId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleId"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_rmListResources_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["projectId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["folder"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folder")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["folder"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["nameMask"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameMask")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nameMask"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["readProperties"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("readProperties")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["readProperties"] = arg3 - var arg4 *bool - if tmp, ok := rawArgs["readHistory"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("readHistory")) - arg4, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["readHistory"] = arg4 - return args, nil -} - -func (ec *executionContext) field_Query_rmReadResourceAsString_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["resourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resourcePath"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_saveAuthProviderConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["providerId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["providerId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["displayName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("displayName")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["displayName"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["disabled"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("disabled")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["disabled"] = arg3 - var arg4 *string - if tmp, ok := rawArgs["iconURL"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("iconURL")) - arg4, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["iconURL"] = arg4 - var arg5 *string - if tmp, ok := rawArgs["description"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - arg5, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["description"] = arg5 - var arg6 interface{} - if tmp, ok := rawArgs["parameters"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parameters")) - arg6, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["parameters"] = arg6 - return args, nil -} - -func (ec *executionContext) field_Query_saveUserMetaParameter_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - var arg1 string - if tmp, ok := rawArgs["displayName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("displayName")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["displayName"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["description"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["description"] = arg2 - var arg3 bool - if tmp, ok := rawArgs["required"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("required")) - arg3, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["required"] = arg3 - return args, nil -} - -func (ec *executionContext) field_Query_searchConnections_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 []string - if tmp, ok := rawArgs["hostNames"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hostNames")) - arg0, err = ec.unmarshalNString2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["hostNames"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_setConnectionSubjectAccess_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 []string - if tmp, ok := rawArgs["subjects"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("subjects")) - arg1, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["subjects"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_setDefaultNavigatorSettings_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 model.NavigatorSettingsInput - if tmp, ok := rawArgs["settings"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("settings")) - arg0, err = ec.unmarshalNNavigatorSettingsInput2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorSettingsInput(ctx, tmp) - if err != nil { - return nil, err - } - } - args["settings"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_setSubjectConnectionAccess_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["subjectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("subjectId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["subjectId"] = arg0 - var arg1 []string - if tmp, ok := rawArgs["connections"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connections")) - arg1, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connections"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_setSubjectPermissions_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleId"] = arg0 - var arg1 []string - if tmp, ok := rawArgs["permissions"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("permissions")) - arg1, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["permissions"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_setUserCredentials_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["userId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["providerId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["providerId"] = arg1 - var arg2 interface{} - if tmp, ok := rawArgs["credentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("credentials")) - arg2, err = ec.unmarshalNObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["credentials"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Query_setUserMetaParameterValues_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["userId"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["parameters"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parameters")) - arg1, err = ec.unmarshalNObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["parameters"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_sqlCompletionProposals_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["query"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("query")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["query"] = arg2 - var arg3 int - if tmp, ok := rawArgs["position"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("position")) - arg3, err = ec.unmarshalNInt2int(ctx, tmp) - if err != nil { - return nil, err - } - } - args["position"] = arg3 - var arg4 *int - if tmp, ok := rawArgs["maxResults"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("maxResults")) - arg4, err = ec.unmarshalOInt2ᚖint(ctx, tmp) - if err != nil { - return nil, err - } - } - args["maxResults"] = arg4 - var arg5 *bool - if tmp, ok := rawArgs["simpleMode"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("simpleMode")) - arg5, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["simpleMode"] = arg5 - return args, nil -} - -func (ec *executionContext) field_Query_sqlDialectInfo_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_sqlEntityQueryGenerators_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 []string - if tmp, ok := rawArgs["nodePathList"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePathList")) - arg0, err = ec.unmarshalNString2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePathList"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_sqlFormatQuery_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["query"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("query")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["query"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Query_sqlGenerateEntityQuery_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["generatorId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("generatorId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["generatorId"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["options"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("options")) - arg1, err = ec.unmarshalNObject2interface(ctx, tmp) - if err != nil { - return nil, err - } - } - args["options"] = arg1 - var arg2 []string - if tmp, ok := rawArgs["nodePathList"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePathList")) - arg2, err = ec.unmarshalNString2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } - } - args["nodePathList"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Query_sqlListContexts_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_sqlParseQuery_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["script"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("script")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["script"] = arg1 - var arg2 int - if tmp, ok := rawArgs["position"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("position")) - arg2, err = ec.unmarshalNInt2int(ctx, tmp) - if err != nil { - return nil, err - } - } - args["position"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Query_sqlParseScript_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["script"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("script")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["script"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_sqlSupportedOperations_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultsId"] = arg2 - var arg3 int - if tmp, ok := rawArgs["attributeIndex"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("attributeIndex")) - arg3, err = ec.unmarshalNInt2int(ctx, tmp) - if err != nil { - return nil, err - } - } - args["attributeIndex"] = arg3 - return args, nil -} - -func (ec *executionContext) field_Query_updateConnectionConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - var arg1 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg1, err = ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } - } - args["config"] = arg1 - return args, nil -} - -func (ec *executionContext) field_Query_updateRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["roleName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleName")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["roleName"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["description"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["description"] = arg2 - return args, nil -} - -func (ec *executionContext) field_Query_userConnections_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } - } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field___Type_enumValues_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 bool - if tmp, ok := rawArgs["includeDeprecated"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) - arg0, err = ec.unmarshalOBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["includeDeprecated"] = arg0 - return args, nil -} - -func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 bool - if tmp, ok := rawArgs["includeDeprecated"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) - arg0, err = ec.unmarshalOBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } - } - args["includeDeprecated"] = arg0 - return args, nil -} - -// endregion ***************************** args.gotpl ***************************** - -// region ************************** directives.gotpl ************************** - -// endregion ************************** directives.gotpl ************************** - -// region **************************** field.gotpl ***************************** - -func (ec *executionContext) _AdminAuthProviderConfiguration_providerId(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_providerId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProviderID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_providerId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_id(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_displayName(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_disabled(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_disabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Disabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_disabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_iconURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IconURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_parameters(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_parameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Parameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_parameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_signInLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SignInLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_signOutLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SignOutLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_redirectLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_redirectLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RedirectLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_redirectLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminAuthProviderConfiguration_metadataLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_metadataLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MetadataLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_metadataLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminAuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionGrantInfo_connectionId(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionGrantInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionGrantInfo_connectionId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConnectionID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_connectionId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionGrantInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionGrantInfo_dataSourceId(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionGrantInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataSourceID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionGrantInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionGrantInfo_subjectId(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionGrantInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionGrantInfo_subjectId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubjectID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_subjectId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionGrantInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionGrantInfo_subjectType(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionGrantInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionGrantInfo_subjectType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubjectType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(model.AdminSubjectType) - fc.Result = res - return ec.marshalNAdminSubjectType2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminSubjectType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_subjectType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionGrantInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type AdminSubjectType does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionSearchInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionSearchInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionSearchInfo_host(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_host(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Host, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_host(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionSearchInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionSearchInfo_port(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_port(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Port, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_port(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionSearchInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionSearchInfo_possibleDrivers(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_possibleDrivers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PossibleDrivers, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_possibleDrivers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionSearchInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminConnectionSearchInfo_defaultDriver(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_defaultDriver(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultDriver, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_defaultDriver(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminConnectionSearchInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminPermissionInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminPermissionInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminPermissionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminPermissionInfo_label(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminPermissionInfo_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminPermissionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminPermissionInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminPermissionInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminPermissionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminPermissionInfo_provider(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_provider(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Provider, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminPermissionInfo_provider(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminPermissionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminPermissionInfo_category(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_category(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Category, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminPermissionInfo_category(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminPermissionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminRoleInfo_roleId(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_roleId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RoleID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminRoleInfo_roleId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminRoleInfo_roleName(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_roleName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RoleName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminRoleInfo_roleName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminRoleInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminRoleInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminRoleInfo_grantedUsers(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_grantedUsers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.GrantedUsers, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminRoleInfo_grantedUsers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminRoleInfo_grantedConnections(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_grantedConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.GrantedConnections, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminConnectionGrantInfo) - fc.Result = res - return ec.marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminRoleInfo_grantedConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "connectionId": - return ec.fieldContext_AdminConnectionGrantInfo_connectionId(ctx, field) - case "dataSourceId": - return ec.fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx, field) - case "subjectId": - return ec.fieldContext_AdminConnectionGrantInfo_subjectId(ctx, field) - case "subjectType": - return ec.fieldContext_AdminConnectionGrantInfo_subjectType(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminConnectionGrantInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminRoleInfo_rolePermissions(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_rolePermissions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RolePermissions, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminRoleInfo_rolePermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminUserInfo_userId(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_userId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminUserInfo_userId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminUserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminUserInfo_metaParameters(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MetaParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminUserInfo_metaParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminUserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminUserInfo_configurationParameters(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConfigurationParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminUserInfo_configurationParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminUserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminUserInfo_grantedRoles(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_grantedRoles(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.GrantedRoles, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminUserInfo_grantedRoles(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminUserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminUserInfo_grantedConnections(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.GrantedConnections, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminConnectionGrantInfo) - fc.Result = res - return ec.marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminUserInfo_grantedConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminUserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "connectionId": - return ec.fieldContext_AdminConnectionGrantInfo_connectionId(ctx, field) - case "dataSourceId": - return ec.fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx, field) - case "subjectId": - return ec.fieldContext_AdminConnectionGrantInfo_subjectId(ctx, field) - case "subjectType": - return ec.fieldContext_AdminConnectionGrantInfo_subjectType(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminConnectionGrantInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminUserInfo_origins(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_origins(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Origins, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectOrigin) - fc.Result = res - return ec.marshalNObjectOrigin2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectOriginᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminUserInfo_origins(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminUserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "type": - return ec.fieldContext_ObjectOrigin_type(ctx, field) - case "subType": - return ec.fieldContext_ObjectOrigin_subType(ctx, field) - case "displayName": - return ec.fieldContext_ObjectOrigin_displayName(ctx, field) - case "icon": - return ec.fieldContext_ObjectOrigin_icon(ctx, field) - case "configuration": - return ec.fieldContext_ObjectOrigin_configuration(ctx, field) - case "details": - return ec.fieldContext_ObjectOrigin_details(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectOrigin", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminUserInfo_linkedAuthProviders(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LinkedAuthProviders, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminUserInfo_linkedAuthProviders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminUserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AdminUserInfo_enabled(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_enabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Enabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AdminUserInfo_enabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AdminUserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AsyncTaskInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AsyncTaskInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AsyncTaskInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AsyncTaskInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AsyncTaskInfo_running(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_running(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Running, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AsyncTaskInfo_running(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AsyncTaskInfo_status(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_status(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Status, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AsyncTaskInfo_status(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AsyncTaskInfo_error(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_error(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Error, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.ServerError) - fc.Result = res - return ec.marshalOServerError2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerError(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AsyncTaskInfo_error(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "message": - return ec.fieldContext_ServerError_message(ctx, field) - case "errorCode": - return ec.fieldContext_ServerError_errorCode(ctx, field) - case "errorType": - return ec.fieldContext_ServerError_errorType(ctx, field) - case "stackTrace": - return ec.fieldContext_ServerError_stackTrace(ctx, field) - case "causedBy": - return ec.fieldContext_ServerError_causedBy(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerError", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AsyncTaskInfo_result(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_result(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Result, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.SQLExecuteInfo) - fc.Result = res - return ec.marshalOSQLExecuteInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecuteInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AsyncTaskInfo_result(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "statusMessage": - return ec.fieldContext_SQLExecuteInfo_statusMessage(ctx, field) - case "duration": - return ec.fieldContext_SQLExecuteInfo_duration(ctx, field) - case "filterText": - return ec.fieldContext_SQLExecuteInfo_filterText(ctx, field) - case "results": - return ec.fieldContext_SQLExecuteInfo_results(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLExecuteInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AsyncTaskInfo_taskResult(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.TaskResult, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AsyncTaskInfo_taskResult(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthCredentialInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthCredentialInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthCredentialInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthCredentialInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthCredentialInfo_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthCredentialInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthCredentialInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthCredentialInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthCredentialInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthCredentialInfo_admin(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_admin(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Admin, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthCredentialInfo_admin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthCredentialInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthCredentialInfo_user(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_user(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.User, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthCredentialInfo_user(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthCredentialInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthCredentialInfo_identifying(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_identifying(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Identifying, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthCredentialInfo_identifying(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthCredentialInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthCredentialInfo_possibleValues(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_possibleValues(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PossibleValues, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalOString2ᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthCredentialInfo_possibleValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthCredentialInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthCredentialInfo_encryption(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_encryption(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Encryption, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.AuthCredentialEncryption) - fc.Result = res - return ec.marshalOAuthCredentialEncryption2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthCredentialEncryption(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthCredentialInfo_encryption(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthCredentialInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type AuthCredentialEncryption does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthInfo_redirectLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthInfo_redirectLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RedirectLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthInfo_redirectLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthInfo_authId(ctx context.Context, field graphql.CollectedField, obj *model.AuthInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthInfo_authId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthInfo_authId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthInfo_authStatus(ctx context.Context, field graphql.CollectedField, obj *model.AuthInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthInfo_authStatus(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthStatus, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(model.AuthStatus) - fc.Result = res - return ec.marshalNAuthStatus2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthStatus(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthInfo_authStatus(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type AuthStatus does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthInfo_userTokens(ctx context.Context, field graphql.CollectedField, obj *model.AuthInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthInfo_userTokens(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserTokens, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.UserAuthToken) - fc.Result = res - return ec.marshalOUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserAuthTokenᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthInfo_userTokens(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "authProvider": - return ec.fieldContext_UserAuthToken_authProvider(ctx, field) - case "authConfiguration": - return ec.fieldContext_UserAuthToken_authConfiguration(ctx, field) - case "loginTime": - return ec.fieldContext_UserAuthToken_loginTime(ctx, field) - case "userId": - return ec.fieldContext_UserAuthToken_userId(ctx, field) - case "displayName": - return ec.fieldContext_UserAuthToken_displayName(ctx, field) - case "message": - return ec.fieldContext_UserAuthToken_message(ctx, field) - case "origin": - return ec.fieldContext_UserAuthToken_origin(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type UserAuthToken", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderConfiguration_id(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderConfiguration_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderConfiguration_displayName(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderConfiguration_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderConfiguration_disabled(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_disabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Disabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderConfiguration_disabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_iconURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IconURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_signInLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SignInLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_signOutLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SignOutLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderConfiguration_metadataLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_metadataLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MetadataLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderConfiguration_metadataLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderConfiguration", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderCredentialsProfile_id(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderCredentialsProfile) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderCredentialsProfile_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderCredentialsProfile", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderCredentialsProfile_label(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderCredentialsProfile) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderCredentialsProfile_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderCredentialsProfile", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderCredentialsProfile_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderCredentialsProfile) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderCredentialsProfile_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderCredentialsProfile", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderCredentialsProfile_credentialParameters(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderCredentialsProfile) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderCredentialsProfile_credentialParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CredentialParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AuthCredentialInfo) - fc.Result = res - return ec.marshalNAuthCredentialInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthCredentialInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_credentialParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderCredentialsProfile", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AuthCredentialInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_AuthCredentialInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_AuthCredentialInfo_description(ctx, field) - case "admin": - return ec.fieldContext_AuthCredentialInfo_admin(ctx, field) - case "user": - return ec.fieldContext_AuthCredentialInfo_user(ctx, field) - case "identifying": - return ec.fieldContext_AuthCredentialInfo_identifying(ctx, field) - case "possibleValues": - return ec.fieldContext_AuthCredentialInfo_possibleValues(ctx, field) - case "encryption": - return ec.fieldContext_AuthCredentialInfo_encryption(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AuthCredentialInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_label(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_defaultProvider(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_defaultProvider(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultProvider, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_defaultProvider(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_configurable(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_configurable(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Configurable, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_configurable(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_configurations(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_configurations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Configurations, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.AuthProviderConfiguration) - fc.Result = res - return ec.marshalOAuthProviderConfiguration2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderConfigurationᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_configurations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AuthProviderConfiguration_id(ctx, field) - case "displayName": - return ec.fieldContext_AuthProviderConfiguration_displayName(ctx, field) - case "disabled": - return ec.fieldContext_AuthProviderConfiguration_disabled(ctx, field) - case "iconURL": - return ec.fieldContext_AuthProviderConfiguration_iconURL(ctx, field) - case "description": - return ec.fieldContext_AuthProviderConfiguration_description(ctx, field) - case "signInLink": - return ec.fieldContext_AuthProviderConfiguration_signInLink(ctx, field) - case "signOutLink": - return ec.fieldContext_AuthProviderConfiguration_signOutLink(ctx, field) - case "metadataLink": - return ec.fieldContext_AuthProviderConfiguration_metadataLink(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AuthProviderConfiguration", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_credentialProfiles(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_credentialProfiles(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CredentialProfiles, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AuthProviderCredentialsProfile) - fc.Result = res - return ec.marshalNAuthProviderCredentialsProfile2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderCredentialsProfileᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_credentialProfiles(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AuthProviderCredentialsProfile_id(ctx, field) - case "label": - return ec.fieldContext_AuthProviderCredentialsProfile_label(ctx, field) - case "description": - return ec.fieldContext_AuthProviderCredentialsProfile_description(ctx, field) - case "credentialParameters": - return ec.fieldContext_AuthProviderCredentialsProfile_credentialParameters(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AuthProviderCredentialsProfile", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _AuthProviderInfo_requiredFeatures(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_requiredFeatures(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RequiredFeatures, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_AuthProviderInfo_requiredFeatures(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "AuthProviderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionFolderInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionFolderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionFolderInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionFolderInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionFolderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionFolderInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionFolderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionFolderInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionFolderInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionFolderInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_driverId(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_driverId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_driverId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_host(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_host(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Host, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_host(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_port(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_port(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Port, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_port(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_serverName(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_serverName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_serverName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_databaseName(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DatabaseName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_databaseName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_url(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_url(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.URL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_url(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_properties(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_template(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_template(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Template, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_template(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_connected(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_connected(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Connected, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_connected(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_provided(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_provided(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Provided, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_provided(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_readOnly(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReadOnly, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_readOnly(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_useUrl(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UseURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_useUrl(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_saveCredentials(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SaveCredentials, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_saveCredentials(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_folder(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_folder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Folder, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_folder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_nodePath(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NodePath, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_nodePath(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_connectTime(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConnectTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_connectTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_connectionError(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConnectionError, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.ServerError) - fc.Result = res - return ec.marshalOServerError2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerError(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_connectionError(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "message": - return ec.fieldContext_ServerError_message(ctx, field) - case "errorCode": - return ec.fieldContext_ServerError_errorCode(ctx, field) - case "errorType": - return ec.fieldContext_ServerError_errorType(ctx, field) - case "stackTrace": - return ec.fieldContext_ServerError_stackTrace(ctx, field) - case "causedBy": - return ec.fieldContext_ServerError_causedBy(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerError", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_serverVersion(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_serverVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_clientVersion(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ClientVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_clientVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_origin(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_origin(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Origin, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ObjectOrigin) - fc.Result = res - return ec.marshalNObjectOrigin2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectOrigin(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_origin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "type": - return ec.fieldContext_ObjectOrigin_type(ctx, field) - case "subType": - return ec.fieldContext_ObjectOrigin_subType(ctx, field) - case "displayName": - return ec.fieldContext_ObjectOrigin_displayName(ctx, field) - case "icon": - return ec.fieldContext_ObjectOrigin_icon(ctx, field) - case "configuration": - return ec.fieldContext_ObjectOrigin_configuration(ctx, field) - case "details": - return ec.fieldContext_ObjectOrigin_details(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectOrigin", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_authNeeded(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthNeeded, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_authNeeded(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_authModel(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_authModel(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthModel, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_authModel(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_authProperties(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthProperties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_authProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_providerProperties(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProviderProperties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_providerProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_networkHandlersConfig(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NetworkHandlersConfig, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NetworkHandlerConfig) - fc.Result = res - return ec.marshalNNetworkHandlerConfig2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_networkHandlersConfig(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_NetworkHandlerConfig_id(ctx, field) - case "enabled": - return ec.fieldContext_NetworkHandlerConfig_enabled(ctx, field) - case "authType": - return ec.fieldContext_NetworkHandlerConfig_authType(ctx, field) - case "userName": - return ec.fieldContext_NetworkHandlerConfig_userName(ctx, field) - case "password": - return ec.fieldContext_NetworkHandlerConfig_password(ctx, field) - case "key": - return ec.fieldContext_NetworkHandlerConfig_key(ctx, field) - case "savePassword": - return ec.fieldContext_NetworkHandlerConfig_savePassword(ctx, field) - case "properties": - return ec.fieldContext_NetworkHandlerConfig_properties(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NetworkHandlerConfig", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_features(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Features, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_features(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_navigatorSettings(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NavigatorSettings, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NavigatorSettings) - fc.Result = res - return ec.marshalNNavigatorSettings2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorSettings(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_navigatorSettings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "showSystemObjects": - return ec.fieldContext_NavigatorSettings_showSystemObjects(ctx, field) - case "showUtilityObjects": - return ec.fieldContext_NavigatorSettings_showUtilityObjects(ctx, field) - case "showOnlyEntities": - return ec.fieldContext_NavigatorSettings_showOnlyEntities(ctx, field) - case "mergeEntities": - return ec.fieldContext_NavigatorSettings_mergeEntities(ctx, field) - case "hideFolders": - return ec.fieldContext_NavigatorSettings_hideFolders(ctx, field) - case "hideSchemas": - return ec.fieldContext_NavigatorSettings_hideSchemas(ctx, field) - case "hideVirtualModel": - return ec.fieldContext_NavigatorSettings_hideVirtualModel(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NavigatorSettings", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ConnectionInfo_supportedDataFormats(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportedDataFormats, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]model.ResultDataFormat) - fc.Result = res - return ec.marshalNResultDataFormat2ᚕgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormatᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ConnectionInfo_supportedDataFormats(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ConnectionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ResultDataFormat does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_fileExtension(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_fileExtension(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FileExtension, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_fileExtension(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_appFileExtension(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_appFileExtension(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AppFileExtension, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_appFileExtension(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_appName(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_appName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AppName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_appName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_order(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_order(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Order, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_order(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_properties(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_isBinary(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_isBinary(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsBinary, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_isBinary(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTransferProcessorInfo_isHTML(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_isHTML(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsHTML, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_isHTML(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTypeLogicalOperation_id(ctx context.Context, field graphql.CollectedField, obj *model.DataTypeLogicalOperation) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTypeLogicalOperation_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTypeLogicalOperation_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTypeLogicalOperation", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTypeLogicalOperation_expression(ctx context.Context, field graphql.CollectedField, obj *model.DataTypeLogicalOperation) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTypeLogicalOperation_expression(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Expression, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTypeLogicalOperation_expression(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTypeLogicalOperation", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DataTypeLogicalOperation_argumentCount(ctx context.Context, field graphql.CollectedField, obj *model.DataTypeLogicalOperation) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTypeLogicalOperation_argumentCount(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ArgumentCount, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DataTypeLogicalOperation_argumentCount(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DataTypeLogicalOperation", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseAuthModel_id(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseAuthModel_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseAuthModel", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseAuthModel_displayName(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseAuthModel_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseAuthModel", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseAuthModel_description(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseAuthModel_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseAuthModel", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseAuthModel_icon(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseAuthModel_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseAuthModel", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseAuthModel_requiresLocalConfiguration(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_requiresLocalConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RequiresLocalConfiguration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseAuthModel_requiresLocalConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseAuthModel", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseAuthModel_properties(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseAuthModel_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseAuthModel", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseCatalog_catalog(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseCatalog) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseCatalog_catalog(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Catalog, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseCatalog_catalog(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseCatalog", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) - case "name": - return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) - case "fullName": - return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) - case "icon": - return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) - case "description": - return ec.fieldContext_NavigatorNodeInfo_description(ctx, field) - case "nodeType": - return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) - case "hasChildren": - return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) - case "object": - return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) - case "features": - return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) - case "nodeDetails": - return ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) - case "folder": - return ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) - case "inline": - return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) - case "navigable": - return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseCatalog_schemaList(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseCatalog) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseCatalog_schemaList(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SchemaList, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseCatalog_schemaList(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseCatalog", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) - case "name": - return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) - case "fullName": - return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) - case "icon": - return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) - case "description": - return ec.fieldContext_NavigatorNodeInfo_description(ctx, field) - case "nodeType": - return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) - case "hasChildren": - return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) - case "object": - return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) - case "features": - return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) - case "nodeDetails": - return ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) - case "folder": - return ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) - case "inline": - return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) - case "navigable": - return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseDocument_id(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseDocument) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseDocument_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseDocument_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseDocument", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseDocument_contentType(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseDocument) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseDocument_contentType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ContentType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseDocument_contentType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseDocument", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseDocument_properties(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseDocument) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseDocument_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseDocument_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseDocument", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseDocument_data(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseDocument) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseDocument_data(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Data, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseDocument_data(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseDocument", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_type(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_properties(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_DatabaseObjectInfo_properties_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_ordinalPosition(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_ordinalPosition(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.OrdinalPosition, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_ordinalPosition(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_fullyQualifiedName(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_fullyQualifiedName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FullyQualifiedName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_fullyQualifiedName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_overloadedName(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_overloadedName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.OverloadedName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_overloadedName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_uniqueName(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_uniqueName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UniqueName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_uniqueName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_state(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_state(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.State, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_state(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_features(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Features, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_features(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseObjectInfo_editors(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_editors(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Editors, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseObjectInfo_editors(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseObjectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseStructContainers_catalogList(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseStructContainers_catalogList(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CatalogList, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DatabaseCatalog) - fc.Result = res - return ec.marshalNDatabaseCatalog2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseCatalogᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseStructContainers_catalogList(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseStructContainers", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "catalog": - return ec.fieldContext_DatabaseCatalog_catalog(ctx, field) - case "schemaList": - return ec.fieldContext_DatabaseCatalog_schemaList(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type DatabaseCatalog", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseStructContainers_schemaList(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseStructContainers_schemaList(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SchemaList, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseStructContainers_schemaList(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseStructContainers", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) - case "name": - return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) - case "fullName": - return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) - case "icon": - return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) - case "description": - return ec.fieldContext_NavigatorNodeInfo_description(ctx, field) - case "nodeType": - return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) - case "hasChildren": - return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) - case "object": - return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) - case "features": - return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) - case "nodeDetails": - return ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) - case "folder": - return ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) - case "inline": - return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) - case "navigable": - return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseStructContainers_supportsCatalogChange(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseStructContainers_supportsCatalogChange(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsCatalogChange, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseStructContainers_supportsCatalogChange(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseStructContainers", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DatabaseStructContainers_supportsSchemaChange(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseStructContainers_supportsSchemaChange(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsSchemaChange, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DatabaseStructContainers_supportsSchemaChange(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DatabaseStructContainers", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_iconBig(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_iconBig(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IconBig, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_iconBig(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_providerId(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_providerId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProviderID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_providerId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_driverClassName(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverClassName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverClassName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_driverClassName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_defaultHost(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultHost(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultHost, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_defaultHost(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_defaultPort(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultPort(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultPort, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_defaultPort(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_defaultDatabase(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultDatabase(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultDatabase, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_defaultDatabase(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_defaultServer(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultServer(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultServer, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_defaultServer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_defaultUser(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultUser, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_defaultUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_sampleURL(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_sampleURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SampleURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_sampleURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_driverInfoURL(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverInfoURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverInfoURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_driverInfoURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_driverPropertiesURL(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverPropertiesURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverPropertiesURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_driverPropertiesURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_embedded(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_embedded(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Embedded, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_embedded(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_enabled(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_enabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Enabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_enabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_requiresServerName(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_requiresServerName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RequiresServerName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_requiresServerName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_allowsEmptyPassword(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_allowsEmptyPassword(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AllowsEmptyPassword, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_allowsEmptyPassword(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_licenseRequired(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_licenseRequired(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LicenseRequired, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_licenseRequired(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_license(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_license(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.License, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_license(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_custom(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_custom(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Custom, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_custom(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_promotedScore(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_promotedScore(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PromotedScore, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_promotedScore(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_driverProperties(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverProperties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_driverProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_driverParameters(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_driverParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_providerProperties(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_providerProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProviderProperties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_providerProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_anonymousAccess(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_anonymousAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AnonymousAccess, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_anonymousAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_defaultAuthModel(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultAuthModel(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultAuthModel, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_defaultAuthModel(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_applicableAuthModels(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_applicableAuthModels(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ApplicableAuthModels, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_applicableAuthModels(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _DriverInfo_applicableNetworkHandlers(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_applicableNetworkHandlers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ApplicableNetworkHandlers, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNID2ᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_DriverInfo_applicableNetworkHandlers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "DriverInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _LogEntry_time(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_LogEntry_time(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Time, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*time.Time) - fc.Result = res - return ec.marshalODateTime2ᚖtimeᚐTime(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_LogEntry_time(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "LogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type DateTime does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _LogEntry_type(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_LogEntry_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_LogEntry_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "LogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _LogEntry_message(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_LogEntry_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_LogEntry_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "LogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _LogEntry_stackTrace(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_LogEntry_stackTrace(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StackTrace, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_LogEntry_stackTrace(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "LogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _Mutation_setUserConfigurationParameter(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_setUserConfigurationParameter(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SetUserConfigurationParameter(rctx, fc.Args["name"].(string), - func() interface{} { - if fc.Args["value"] == nil { - return nil - } - return fc.Args["value"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_setUserConfigurationParameter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_setUserConfigurationParameter_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_openSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_openSession(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().OpenSession(rctx, fc.Args["defaultLocale"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SessionInfo) - fc.Result = res - return ec.marshalNSessionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSessionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_openSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "createTime": - return ec.fieldContext_SessionInfo_createTime(ctx, field) - case "lastAccessTime": - return ec.fieldContext_SessionInfo_lastAccessTime(ctx, field) - case "locale": - return ec.fieldContext_SessionInfo_locale(ctx, field) - case "cacheExpired": - return ec.fieldContext_SessionInfo_cacheExpired(ctx, field) - case "serverMessages": - return ec.fieldContext_SessionInfo_serverMessages(ctx, field) - case "connections": - return ec.fieldContext_SessionInfo_connections(ctx, field) - case "actionParameters": - return ec.fieldContext_SessionInfo_actionParameters(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SessionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_openSession_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_closeSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_closeSession(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CloseSession(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_closeSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _Mutation_touchSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_touchSession(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().TouchSession(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_touchSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _Mutation_refreshSessionConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_refreshSessionConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RefreshSessionConnections(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_refreshSessionConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _Mutation_changeSessionLanguage(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_changeSessionLanguage(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().ChangeSessionLanguage(rctx, fc.Args["locale"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_changeSessionLanguage(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_changeSessionLanguage_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_createConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_createConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CreateConnection(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_createConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_createConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_updateConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_updateConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().UpdateConnection(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_updateConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_updateConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_deleteConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_deleteConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().DeleteConnection(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_deleteConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_deleteConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_createConnectionFromTemplate(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_createConnectionFromTemplate(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CreateConnectionFromTemplate(rctx, fc.Args["templateId"].(string), fc.Args["connectionName"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_createConnectionFromTemplate(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_createConnectionFromTemplate_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_createConnectionFolder(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_createConnectionFolder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CreateConnectionFolder(rctx, fc.Args["parentFolderPath"].(*string), fc.Args["folderName"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionFolderInfo) - fc.Result = res - return ec.marshalNConnectionFolderInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionFolderInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_createConnectionFolder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionFolderInfo_id(ctx, field) - case "description": - return ec.fieldContext_ConnectionFolderInfo_description(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionFolderInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_createConnectionFolder_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_deleteConnectionFolder(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_deleteConnectionFolder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().DeleteConnectionFolder(rctx, fc.Args["folderPath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_deleteConnectionFolder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_deleteConnectionFolder_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_copyConnectionFromNode(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_copyConnectionFromNode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CopyConnectionFromNode(rctx, fc.Args["nodePath"].(string), fc.Args["config"].(*model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_copyConnectionFromNode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_copyConnectionFromNode_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_testConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_testConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().TestConnection(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_testConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_testConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_testNetworkHandler(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_testNetworkHandler(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().TestNetworkHandler(rctx, fc.Args["config"].(model.NetworkHandlerConfigInput)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NetworkEndpointInfo) - fc.Result = res - return ec.marshalNNetworkEndpointInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkEndpointInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_testNetworkHandler(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "message": - return ec.fieldContext_NetworkEndpointInfo_message(ctx, field) - case "clientVersion": - return ec.fieldContext_NetworkEndpointInfo_clientVersion(ctx, field) - case "serverVersion": - return ec.fieldContext_NetworkEndpointInfo_serverVersion(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NetworkEndpointInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_testNetworkHandler_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_initConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_initConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().InitConnection(rctx, fc.Args["id"].(string), - func() interface{} { - if fc.Args["credentials"] == nil { - return nil - } - return fc.Args["credentials"].(interface{}) - }(), fc.Args["networkCredentials"].([]*model.NetworkHandlerConfigInput), fc.Args["saveCredentials"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_initConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_initConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_closeConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_closeConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CloseConnection(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_closeConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_closeConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_setConnectionNavigatorSettings(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_setConnectionNavigatorSettings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SetConnectionNavigatorSettings(rctx, fc.Args["id"].(string), fc.Args["settings"].(model.NavigatorSettingsInput)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_setConnectionNavigatorSettings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_setConnectionNavigatorSettings_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_asyncTaskCancel(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncTaskCancel(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncTaskCancel(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_asyncTaskCancel(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncTaskCancel_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_asyncTaskInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncTaskInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncTaskInfo(rctx, fc.Args["id"].(string), fc.Args["removeOnFinish"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_asyncTaskInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncTaskInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_openConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_openConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().OpenConnection(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_openConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_openConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_asyncTaskStatus(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncTaskStatus(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncTaskStatus(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_asyncTaskStatus(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncTaskStatus_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_navRenameNode(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_navRenameNode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().NavRenameNode(rctx, fc.Args["nodePath"].(string), fc.Args["newName"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_navRenameNode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_navRenameNode_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_navDeleteNodes(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_navDeleteNodes(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().NavDeleteNodes(rctx, fc.Args["nodePaths"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_navDeleteNodes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_navDeleteNodes_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_navMoveNodesToFolder(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_navMoveNodesToFolder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().NavMoveNodesToFolder(rctx, fc.Args["nodePaths"].([]string), fc.Args["folderPath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_navMoveNodesToFolder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_navMoveNodesToFolder_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_rmCreateResource(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_rmCreateResource(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RmCreateResource(rctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["isFolder"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_rmCreateResource(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_rmCreateResource_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_rmMoveResource(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_rmMoveResource(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RmMoveResource(rctx, fc.Args["projectId"].(string), fc.Args["oldResourcePath"].(string), fc.Args["newResourcePath"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_rmMoveResource(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_rmMoveResource_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_rmDeleteResource(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_rmDeleteResource(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RmDeleteResource(rctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["recursive"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_rmDeleteResource(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_rmDeleteResource_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_rmWriteResourceStringContent(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_rmWriteResourceStringContent(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RmWriteResourceStringContent(rctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["data"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_rmWriteResourceStringContent(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_rmWriteResourceStringContent_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_sqlContextCreate(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_sqlContextCreate(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SQLContextCreate(rctx, fc.Args["connectionId"].(string), fc.Args["defaultCatalog"].(*string), fc.Args["defaultSchema"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLContextInfo) - fc.Result = res - return ec.marshalNSQLContextInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLContextInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_sqlContextCreate(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_SQLContextInfo_id(ctx, field) - case "connectionId": - return ec.fieldContext_SQLContextInfo_connectionId(ctx, field) - case "defaultCatalog": - return ec.fieldContext_SQLContextInfo_defaultCatalog(ctx, field) - case "defaultSchema": - return ec.fieldContext_SQLContextInfo_defaultSchema(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLContextInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_sqlContextCreate_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_sqlContextSetDefaults(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_sqlContextSetDefaults(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SQLContextSetDefaults(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["defaultCatalog"].(*string), fc.Args["defaultSchema"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_sqlContextSetDefaults(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_sqlContextSetDefaults_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_sqlContextDestroy(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_sqlContextDestroy(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SQLContextDestroy(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_sqlContextDestroy(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_sqlContextDestroy_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_asyncSqlExecuteQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncSqlExecuteQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncSQLExecuteQuery(rctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["sql"].(string), fc.Args["resultId"].(*string), fc.Args["filter"].(*model.SQLDataFilter), fc.Args["dataFormat"].(*model.ResultDataFormat), fc.Args["readLogs"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_asyncSqlExecuteQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncSqlExecuteQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_asyncReadDataFromContainer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncReadDataFromContainer(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncReadDataFromContainer(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["containerNodePath"].(string), fc.Args["resultId"].(*string), fc.Args["filter"].(*model.SQLDataFilter), fc.Args["dataFormat"].(*model.ResultDataFormat)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_asyncReadDataFromContainer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncReadDataFromContainer_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_sqlResultClose(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_sqlResultClose(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SQLResultClose(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_sqlResultClose(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_sqlResultClose_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_updateResultsDataBatch(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_updateResultsDataBatch(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().UpdateResultsDataBatch(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["updatedRows"].([]*model.SQLResultRow), fc.Args["deletedRows"].([]*model.SQLResultRow), fc.Args["addedRows"].([]*model.SQLResultRow)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLExecuteInfo) - fc.Result = res - return ec.marshalNSQLExecuteInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecuteInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_updateResultsDataBatch(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "statusMessage": - return ec.fieldContext_SQLExecuteInfo_statusMessage(ctx, field) - case "duration": - return ec.fieldContext_SQLExecuteInfo_duration(ctx, field) - case "filterText": - return ec.fieldContext_SQLExecuteInfo_filterText(ctx, field) - case "results": - return ec.fieldContext_SQLExecuteInfo_results(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLExecuteInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_updateResultsDataBatch_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_updateResultsDataBatchScript(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_updateResultsDataBatchScript(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().UpdateResultsDataBatchScript(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["updatedRows"].([]*model.SQLResultRow), fc.Args["deletedRows"].([]*model.SQLResultRow), fc.Args["addedRows"].([]*model.SQLResultRow)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_updateResultsDataBatchScript(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_updateResultsDataBatchScript_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_readLobValue(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_readLobValue(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().ReadLobValue(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["lobColumnIndex"].(int), fc.Args["row"].([]*model.SQLResultRow)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_readLobValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_readLobValue_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_asyncSqlExecuteResults(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncSqlExecuteResults(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncSQLExecuteResults(rctx, fc.Args["taskId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLExecuteInfo) - fc.Result = res - return ec.marshalNSQLExecuteInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecuteInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_asyncSqlExecuteResults(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "statusMessage": - return ec.fieldContext_SQLExecuteInfo_statusMessage(ctx, field) - case "duration": - return ec.fieldContext_SQLExecuteInfo_duration(ctx, field) - case "filterText": - return ec.fieldContext_SQLExecuteInfo_filterText(ctx, field) - case "results": - return ec.fieldContext_SQLExecuteInfo_results(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLExecuteInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncSqlExecuteResults_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_asyncSqlExplainExecutionPlan(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncSqlExplainExecutionPlan(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncSQLExplainExecutionPlan(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string), - func() interface{} { - if fc.Args["configuration"] == nil { - return nil - } - return fc.Args["configuration"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_asyncSqlExplainExecutionPlan(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncSqlExplainExecutionPlan_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_asyncSqlExplainExecutionPlanResult(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncSqlExplainExecutionPlanResult(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncSQLExplainExecutionPlanResult(rctx, fc.Args["taskId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLExecutionPlan) - fc.Result = res - return ec.marshalNSQLExecutionPlan2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecutionPlan(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_asyncSqlExplainExecutionPlanResult(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "query": - return ec.fieldContext_SQLExecutionPlan_query(ctx, field) - case "nodes": - return ec.fieldContext_SQLExecutionPlan_nodes(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLExecutionPlan", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncSqlExplainExecutionPlanResult_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_fullName(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FullName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_fullName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_nodeType(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NodeType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_hasChildren(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HasChildren, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_hasChildren(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_object(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_object(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Object, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.DatabaseObjectInfo) - fc.Result = res - return ec.marshalODatabaseObjectInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseObjectInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_object(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext_DatabaseObjectInfo_name(ctx, field) - case "description": - return ec.fieldContext_DatabaseObjectInfo_description(ctx, field) - case "type": - return ec.fieldContext_DatabaseObjectInfo_type(ctx, field) - case "properties": - return ec.fieldContext_DatabaseObjectInfo_properties(ctx, field) - case "ordinalPosition": - return ec.fieldContext_DatabaseObjectInfo_ordinalPosition(ctx, field) - case "fullyQualifiedName": - return ec.fieldContext_DatabaseObjectInfo_fullyQualifiedName(ctx, field) - case "overloadedName": - return ec.fieldContext_DatabaseObjectInfo_overloadedName(ctx, field) - case "uniqueName": - return ec.fieldContext_DatabaseObjectInfo_uniqueName(ctx, field) - case "state": - return ec.fieldContext_DatabaseObjectInfo_state(ctx, field) - case "features": - return ec.fieldContext_DatabaseObjectInfo_features(ctx, field) - case "editors": - return ec.fieldContext_DatabaseObjectInfo_editors(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type DatabaseObjectInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_features(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Features, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_features(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_nodeDetails(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NodeDetails, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeDetails(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_folder(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Folder, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_folder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_inline(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Inline, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_inline(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_navigable(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Navigable, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorNodeInfo_navigable(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorSettings_showSystemObjects(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_showSystemObjects(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ShowSystemObjects, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorSettings_showSystemObjects(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorSettings", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorSettings_showUtilityObjects(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_showUtilityObjects(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ShowUtilityObjects, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorSettings_showUtilityObjects(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorSettings", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorSettings_showOnlyEntities(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_showOnlyEntities(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ShowOnlyEntities, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorSettings_showOnlyEntities(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorSettings", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorSettings_mergeEntities(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_mergeEntities(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MergeEntities, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorSettings_mergeEntities(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorSettings", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorSettings_hideFolders(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_hideFolders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HideFolders, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorSettings_hideFolders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorSettings", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorSettings_hideSchemas(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_hideSchemas(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HideSchemas, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorSettings_hideSchemas(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorSettings", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NavigatorSettings_hideVirtualModel(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_hideVirtualModel(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HideVirtualModel, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NavigatorSettings_hideVirtualModel(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorSettings", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkEndpointInfo_message(ctx context.Context, field graphql.CollectedField, obj *model.NetworkEndpointInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkEndpointInfo_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkEndpointInfo_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkEndpointInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkEndpointInfo_clientVersion(ctx context.Context, field graphql.CollectedField, obj *model.NetworkEndpointInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkEndpointInfo_clientVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ClientVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkEndpointInfo_clientVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkEndpointInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkEndpointInfo_serverVersion(ctx context.Context, field graphql.CollectedField, obj *model.NetworkEndpointInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkEndpointInfo_serverVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkEndpointInfo_serverVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkEndpointInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerConfig_id(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerConfig_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerConfig_enabled(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_enabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Enabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerConfig_enabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerConfig_authType(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_authType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(model.NetworkHandlerAuthType) - fc.Result = res - return ec.marshalNNetworkHandlerAuthType2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerAuthType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerConfig_authType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type NetworkHandlerAuthType does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerConfig_userName(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_userName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerConfig_userName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerConfig_password(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_password(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Password, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerConfig_password(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerConfig_key(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_key(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Key, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerConfig_key(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerConfig_savePassword(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_savePassword(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SavePassword, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerConfig_savePassword(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerConfig_properties(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerConfig_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerDescriptor_id(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerDescriptor_codeName(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_codeName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CodeName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_codeName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerDescriptor_label(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerDescriptor_description(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerDescriptor_secured(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_secured(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Secured, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_secured(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerDescriptor_type(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.NetworkHandlerType) - fc.Result = res - return ec.marshalONetworkHandlerType2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type NetworkHandlerType does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _NetworkHandlerDescriptor_properties(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NetworkHandlerDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDescriptor_id(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDescriptor_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDescriptor_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDescriptor_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDescriptor_fullName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_fullName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FullName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDescriptor_fullName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDescriptor_uniqueName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_uniqueName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UniqueName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDescriptor_uniqueName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDescriptor_description(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDescriptor_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDescriptor_value(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_value(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Value, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDescriptor_value(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDescriptor", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDetails_id(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDetails) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDetails_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDetails_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDetails", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDetails_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDetails) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDetails_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDetails_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDetails", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDetails_description(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDetails) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDetails_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDetails_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDetails", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectDetails_value(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDetails) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDetails_value(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Value, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectDetails_value(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectDetails", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectOrigin_type(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectOrigin_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectOrigin", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectOrigin_subType(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_subType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectOrigin_subType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectOrigin", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectOrigin_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectOrigin_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectOrigin", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectOrigin_icon(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectOrigin_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectOrigin", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectOrigin_configuration(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_configuration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Configuration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectOrigin_configuration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectOrigin", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectOrigin_details(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_details(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Details, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectOrigin_details(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectOrigin", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_category(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Category, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_category(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_dataType(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_dataType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_value(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Value, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_value(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_validValues(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ValidValues, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]interface{}) - fc.Result = res - return ec.marshalOObject2ᚕinterface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_validValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_defaultValue(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultValue, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_defaultValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_length(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Length, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(model.ObjectPropertyLength) - fc.Result = res - return ec.marshalNObjectPropertyLength2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyLength(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_length(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ObjectPropertyLength does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Features, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_features(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ObjectPropertyInfo_order(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Order, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ObjectPropertyInfo_order(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ObjectPropertyInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ProductInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ProductInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ProductInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ProductInfo_version(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_version(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Version, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ProductInfo_version(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ProductInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ProductInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ProductInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ProductInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ProductInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ProductInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ProductInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ProductInfo_buildTime(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_buildTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.BuildTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ProductInfo_buildTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ProductInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ProductInfo_releaseTime(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_releaseTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReleaseTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ProductInfo_releaseTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ProductInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ProductInfo_licenseInfo(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_licenseInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LicenseInfo, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ProductInfo_licenseInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ProductInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ProductInfo_latestVersionInfo(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_latestVersionInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LatestVersionInfo, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ProductInfo_latestVersionInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ProductInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_listUsers(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listUsers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListUsers(rctx, fc.Args["userId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminUserInfo) - fc.Result = res - return ec.marshalNAdminUserInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminUserInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_listUsers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "userId": - return ec.fieldContext_AdminUserInfo_userId(ctx, field) - case "metaParameters": - return ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) - case "configurationParameters": - return ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) - case "grantedRoles": - return ec.fieldContext_AdminUserInfo_grantedRoles(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) - case "origins": - return ec.fieldContext_AdminUserInfo_origins(ctx, field) - case "linkedAuthProviders": - return ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) - case "enabled": - return ec.fieldContext_AdminUserInfo_enabled(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminUserInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_listUsers_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_listRoles(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listRoles(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListRoles(rctx, fc.Args["roleId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminRoleInfo) - fc.Result = res - return ec.marshalNAdminRoleInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminRoleInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_listRoles(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "roleId": - return ec.fieldContext_AdminRoleInfo_roleId(ctx, field) - case "roleName": - return ec.fieldContext_AdminRoleInfo_roleName(ctx, field) - case "description": - return ec.fieldContext_AdminRoleInfo_description(ctx, field) - case "grantedUsers": - return ec.fieldContext_AdminRoleInfo_grantedUsers(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminRoleInfo_grantedConnections(ctx, field) - case "rolePermissions": - return ec.fieldContext_AdminRoleInfo_rolePermissions(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminRoleInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_listRoles_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_listPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listPermissions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListPermissions(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminPermissionInfo) - fc.Result = res - return ec.marshalNAdminPermissionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminPermissionInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_listPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AdminPermissionInfo_id(ctx, field) - case "label": - return ec.fieldContext_AdminPermissionInfo_label(ctx, field) - case "description": - return ec.fieldContext_AdminPermissionInfo_description(ctx, field) - case "provider": - return ec.fieldContext_AdminPermissionInfo_provider(ctx, field) - case "category": - return ec.fieldContext_AdminPermissionInfo_category(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminPermissionInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_createUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_createUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().CreateUser(rctx, fc.Args["userId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AdminUserInfo) - fc.Result = res - return ec.marshalNAdminUserInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminUserInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_createUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "userId": - return ec.fieldContext_AdminUserInfo_userId(ctx, field) - case "metaParameters": - return ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) - case "configurationParameters": - return ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) - case "grantedRoles": - return ec.fieldContext_AdminUserInfo_grantedRoles(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) - case "origins": - return ec.fieldContext_AdminUserInfo_origins(ctx, field) - case "linkedAuthProviders": - return ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) - case "enabled": - return ec.fieldContext_AdminUserInfo_enabled(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminUserInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_createUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_deleteUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteUser(rctx, fc.Args["userId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_deleteUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_deleteUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_createRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_createRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().CreateRole(rctx, fc.Args["roleId"].(string), fc.Args["roleName"].(*string), fc.Args["description"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AdminRoleInfo) - fc.Result = res - return ec.marshalNAdminRoleInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminRoleInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_createRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "roleId": - return ec.fieldContext_AdminRoleInfo_roleId(ctx, field) - case "roleName": - return ec.fieldContext_AdminRoleInfo_roleName(ctx, field) - case "description": - return ec.fieldContext_AdminRoleInfo_description(ctx, field) - case "grantedUsers": - return ec.fieldContext_AdminRoleInfo_grantedUsers(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminRoleInfo_grantedConnections(ctx, field) - case "rolePermissions": - return ec.fieldContext_AdminRoleInfo_rolePermissions(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminRoleInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_createRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_updateRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_updateRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().UpdateRole(rctx, fc.Args["roleId"].(string), fc.Args["roleName"].(*string), fc.Args["description"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AdminRoleInfo) - fc.Result = res - return ec.marshalNAdminRoleInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminRoleInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_updateRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "roleId": - return ec.fieldContext_AdminRoleInfo_roleId(ctx, field) - case "roleName": - return ec.fieldContext_AdminRoleInfo_roleName(ctx, field) - case "description": - return ec.fieldContext_AdminRoleInfo_description(ctx, field) - case "grantedUsers": - return ec.fieldContext_AdminRoleInfo_grantedUsers(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminRoleInfo_grantedConnections(ctx, field) - case "rolePermissions": - return ec.fieldContext_AdminRoleInfo_rolePermissions(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminRoleInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_updateRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_deleteRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteRole(rctx, fc.Args["roleId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_deleteRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_deleteRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_grantUserRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_grantUserRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().GrantUserRole(rctx, fc.Args["userId"].(string), fc.Args["roleId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_grantUserRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_grantUserRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_revokeUserRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_revokeUserRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().RevokeUserRole(rctx, fc.Args["userId"].(string), fc.Args["roleId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_revokeUserRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_revokeUserRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_setSubjectPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setSubjectPermissions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetSubjectPermissions(rctx, fc.Args["roleId"].(string), fc.Args["permissions"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminPermissionInfo) - fc.Result = res - return ec.marshalNAdminPermissionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminPermissionInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_setSubjectPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AdminPermissionInfo_id(ctx, field) - case "label": - return ec.fieldContext_AdminPermissionInfo_label(ctx, field) - case "description": - return ec.fieldContext_AdminPermissionInfo_description(ctx, field) - case "provider": - return ec.fieldContext_AdminPermissionInfo_provider(ctx, field) - case "category": - return ec.fieldContext_AdminPermissionInfo_category(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminPermissionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setSubjectPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_setUserCredentials(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setUserCredentials(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetUserCredentials(rctx, fc.Args["userId"].(string), fc.Args["providerId"].(string), - func() interface{} { - if fc.Args["credentials"] == nil { - return nil - } - return fc.Args["credentials"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_setUserCredentials(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setUserCredentials_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_enableUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_enableUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().EnableUser(rctx, fc.Args["userId"].(string), fc.Args["enabled"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_enableUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_enableUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_allConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_allConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AllConnections(rctx, fc.Args["id"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_allConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_allConnections_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_searchConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_searchConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SearchConnections(rctx, fc.Args["hostNames"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminConnectionSearchInfo) - fc.Result = res - return ec.marshalNAdminConnectionSearchInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionSearchInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_searchConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "displayName": - return ec.fieldContext_AdminConnectionSearchInfo_displayName(ctx, field) - case "host": - return ec.fieldContext_AdminConnectionSearchInfo_host(ctx, field) - case "port": - return ec.fieldContext_AdminConnectionSearchInfo_port(ctx, field) - case "possibleDrivers": - return ec.fieldContext_AdminConnectionSearchInfo_possibleDrivers(ctx, field) - case "defaultDriver": - return ec.fieldContext_AdminConnectionSearchInfo_defaultDriver(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminConnectionSearchInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_searchConnections_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_createConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_createConnectionConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().CreateConnectionConfiguration(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_createConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_createConnectionConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_copyConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_copyConnectionConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().CopyConnectionConfiguration(rctx, fc.Args["nodePath"].(string), fc.Args["config"].(*model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_copyConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_copyConnectionConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_updateConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_updateConnectionConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().UpdateConnectionConfiguration(rctx, fc.Args["id"].(string), fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_updateConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_updateConnectionConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_deleteConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteConnectionConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteConnectionConfiguration(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_deleteConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_deleteConnectionConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_getConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_getConnectionSubjectAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().GetConnectionSubjectAccess(rctx, fc.Args["connectionId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminConnectionGrantInfo) - fc.Result = res - return ec.marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_getConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "connectionId": - return ec.fieldContext_AdminConnectionGrantInfo_connectionId(ctx, field) - case "dataSourceId": - return ec.fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx, field) - case "subjectId": - return ec.fieldContext_AdminConnectionGrantInfo_subjectId(ctx, field) - case "subjectType": - return ec.fieldContext_AdminConnectionGrantInfo_subjectType(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminConnectionGrantInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_getConnectionSubjectAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_setConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setConnectionSubjectAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetConnectionSubjectAccess(rctx, fc.Args["connectionId"].(string), fc.Args["subjects"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_setConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setConnectionSubjectAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_getSubjectConnectionAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_getSubjectConnectionAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().GetSubjectConnectionAccess(rctx, fc.Args["subjectId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminConnectionGrantInfo) - fc.Result = res - return ec.marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_getSubjectConnectionAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "connectionId": - return ec.fieldContext_AdminConnectionGrantInfo_connectionId(ctx, field) - case "dataSourceId": - return ec.fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx, field) - case "subjectId": - return ec.fieldContext_AdminConnectionGrantInfo_subjectId(ctx, field) - case "subjectType": - return ec.fieldContext_AdminConnectionGrantInfo_subjectType(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminConnectionGrantInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_getSubjectConnectionAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_setSubjectConnectionAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setSubjectConnectionAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetSubjectConnectionAccess(rctx, fc.Args["subjectId"].(string), fc.Args["connections"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_setSubjectConnectionAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setSubjectConnectionAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_listFeatureSets(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listFeatureSets(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListFeatureSets(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.WebFeatureSet) - fc.Result = res - return ec.marshalNWebFeatureSet2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐWebFeatureSetᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_listFeatureSets(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_WebFeatureSet_id(ctx, field) - case "label": - return ec.fieldContext_WebFeatureSet_label(ctx, field) - case "description": - return ec.fieldContext_WebFeatureSet_description(ctx, field) - case "icon": - return ec.fieldContext_WebFeatureSet_icon(ctx, field) - case "enabled": - return ec.fieldContext_WebFeatureSet_enabled(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type WebFeatureSet", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_listAuthProviderConfigurationParameters(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listAuthProviderConfigurationParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListAuthProviderConfigurationParameters(rctx, fc.Args["providerId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurationParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_listAuthProviderConfigurationParameters_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_listAuthProviderConfigurations(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listAuthProviderConfigurations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListAuthProviderConfigurations(rctx, fc.Args["providerId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminAuthProviderConfiguration) - fc.Result = res - return ec.marshalNAdminAuthProviderConfiguration2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminAuthProviderConfigurationᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "providerId": - return ec.fieldContext_AdminAuthProviderConfiguration_providerId(ctx, field) - case "id": - return ec.fieldContext_AdminAuthProviderConfiguration_id(ctx, field) - case "displayName": - return ec.fieldContext_AdminAuthProviderConfiguration_displayName(ctx, field) - case "disabled": - return ec.fieldContext_AdminAuthProviderConfiguration_disabled(ctx, field) - case "iconURL": - return ec.fieldContext_AdminAuthProviderConfiguration_iconURL(ctx, field) - case "description": - return ec.fieldContext_AdminAuthProviderConfiguration_description(ctx, field) - case "parameters": - return ec.fieldContext_AdminAuthProviderConfiguration_parameters(ctx, field) - case "signInLink": - return ec.fieldContext_AdminAuthProviderConfiguration_signInLink(ctx, field) - case "signOutLink": - return ec.fieldContext_AdminAuthProviderConfiguration_signOutLink(ctx, field) - case "redirectLink": - return ec.fieldContext_AdminAuthProviderConfiguration_redirectLink(ctx, field) - case "metadataLink": - return ec.fieldContext_AdminAuthProviderConfiguration_metadataLink(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminAuthProviderConfiguration", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_listAuthProviderConfigurations_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_saveAuthProviderConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_saveAuthProviderConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SaveAuthProviderConfiguration(rctx, fc.Args["providerId"].(string), fc.Args["id"].(string), fc.Args["displayName"].(*string), fc.Args["disabled"].(*bool), fc.Args["iconURL"].(*string), fc.Args["description"].(*string), - func() interface{} { - if fc.Args["parameters"] == nil { - return nil - } - return fc.Args["parameters"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AdminAuthProviderConfiguration) - fc.Result = res - return ec.marshalNAdminAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminAuthProviderConfiguration(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_saveAuthProviderConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "providerId": - return ec.fieldContext_AdminAuthProviderConfiguration_providerId(ctx, field) - case "id": - return ec.fieldContext_AdminAuthProviderConfiguration_id(ctx, field) - case "displayName": - return ec.fieldContext_AdminAuthProviderConfiguration_displayName(ctx, field) - case "disabled": - return ec.fieldContext_AdminAuthProviderConfiguration_disabled(ctx, field) - case "iconURL": - return ec.fieldContext_AdminAuthProviderConfiguration_iconURL(ctx, field) - case "description": - return ec.fieldContext_AdminAuthProviderConfiguration_description(ctx, field) - case "parameters": - return ec.fieldContext_AdminAuthProviderConfiguration_parameters(ctx, field) - case "signInLink": - return ec.fieldContext_AdminAuthProviderConfiguration_signInLink(ctx, field) - case "signOutLink": - return ec.fieldContext_AdminAuthProviderConfiguration_signOutLink(ctx, field) - case "redirectLink": - return ec.fieldContext_AdminAuthProviderConfiguration_redirectLink(ctx, field) - case "metadataLink": - return ec.fieldContext_AdminAuthProviderConfiguration_metadataLink(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminAuthProviderConfiguration", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_saveAuthProviderConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_deleteAuthProviderConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteAuthProviderConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteAuthProviderConfiguration(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_deleteAuthProviderConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_deleteAuthProviderConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_saveUserMetaParameter(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_saveUserMetaParameter(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SaveUserMetaParameter(rctx, fc.Args["id"].(string), fc.Args["displayName"].(string), fc.Args["description"].(*string), fc.Args["required"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_saveUserMetaParameter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_saveUserMetaParameter_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_deleteUserMetaParameter(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteUserMetaParameter(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteUserMetaParameter(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_deleteUserMetaParameter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_deleteUserMetaParameter_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_setUserMetaParameterValues(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setUserMetaParameterValues(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetUserMetaParameterValues(rctx, fc.Args["userId"].(string), - func() interface{} { - if fc.Args["parameters"] == nil { - return nil - } - return fc.Args["parameters"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_setUserMetaParameterValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setUserMetaParameterValues_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_configureServer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_configureServer(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ConfigureServer(rctx, fc.Args["configuration"].(model.ServerConfigInput)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_configureServer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_configureServer_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_setDefaultNavigatorSettings(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setDefaultNavigatorSettings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetDefaultNavigatorSettings(rctx, fc.Args["settings"].(model.NavigatorSettingsInput)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_setDefaultNavigatorSettings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setDefaultNavigatorSettings_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_authLogin(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authLogin(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthLogin(rctx, fc.Args["provider"].(string), fc.Args["configuration"].(*string), - func() interface{} { - if fc.Args["credentials"] == nil { - return nil - } - return fc.Args["credentials"].(interface{}) - }(), fc.Args["linkUser"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AuthInfo) - fc.Result = res - return ec.marshalNAuthInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_authLogin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "redirectLink": - return ec.fieldContext_AuthInfo_redirectLink(ctx, field) - case "authId": - return ec.fieldContext_AuthInfo_authId(ctx, field) - case "authStatus": - return ec.fieldContext_AuthInfo_authStatus(ctx, field) - case "userTokens": - return ec.fieldContext_AuthInfo_userTokens(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AuthInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_authLogin_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_authUpdateStatus(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authUpdateStatus(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthUpdateStatus(rctx, fc.Args["authId"].(string), fc.Args["linkUser"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AuthInfo) - fc.Result = res - return ec.marshalNAuthInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_authUpdateStatus(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "redirectLink": - return ec.fieldContext_AuthInfo_redirectLink(ctx, field) - case "authId": - return ec.fieldContext_AuthInfo_authId(ctx, field) - case "authStatus": - return ec.fieldContext_AuthInfo_authStatus(ctx, field) - case "userTokens": - return ec.fieldContext_AuthInfo_userTokens(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AuthInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_authUpdateStatus_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_authLogout(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authLogout(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthLogout(rctx, fc.Args["provider"].(*string), fc.Args["configuration"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_authLogout(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_authLogout_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_activeUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_activeUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ActiveUser(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.UserInfo) - fc.Result = res - return ec.marshalOUserInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_activeUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "userId": - return ec.fieldContext_UserInfo_userId(ctx, field) - case "displayName": - return ec.fieldContext_UserInfo_displayName(ctx, field) - case "authRole": - return ec.fieldContext_UserInfo_authRole(ctx, field) - case "authTokens": - return ec.fieldContext_UserInfo_authTokens(ctx, field) - case "linkedAuthProviders": - return ec.fieldContext_UserInfo_linkedAuthProviders(ctx, field) - case "metaParameters": - return ec.fieldContext_UserInfo_metaParameters(ctx, field) - case "configurationParameters": - return ec.fieldContext_UserInfo_configurationParameters(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type UserInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_authProviders(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authProviders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthProviders(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AuthProviderInfo) - fc.Result = res - return ec.marshalNAuthProviderInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_authProviders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AuthProviderInfo_id(ctx, field) - case "label": - return ec.fieldContext_AuthProviderInfo_label(ctx, field) - case "icon": - return ec.fieldContext_AuthProviderInfo_icon(ctx, field) - case "description": - return ec.fieldContext_AuthProviderInfo_description(ctx, field) - case "defaultProvider": - return ec.fieldContext_AuthProviderInfo_defaultProvider(ctx, field) - case "configurable": - return ec.fieldContext_AuthProviderInfo_configurable(ctx, field) - case "configurations": - return ec.fieldContext_AuthProviderInfo_configurations(ctx, field) - case "credentialProfiles": - return ec.fieldContext_AuthProviderInfo_credentialProfiles(ctx, field) - case "requiredFeatures": - return ec.fieldContext_AuthProviderInfo_requiredFeatures(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AuthProviderInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_authChangeLocalPassword(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authChangeLocalPassword(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthChangeLocalPassword(rctx, fc.Args["oldPassword"].(string), fc.Args["newPassword"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_authChangeLocalPassword(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_authChangeLocalPassword_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_listUserProfileProperties(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listUserProfileProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListUserProfileProperties(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_listUserProfileProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_serverConfig(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_serverConfig(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ServerConfig(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ServerConfig) - fc.Result = res - return ec.marshalNServerConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerConfig(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_serverConfig(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext_ServerConfig_name(ctx, field) - case "version": - return ec.fieldContext_ServerConfig_version(ctx, field) - case "workspaceId": - return ec.fieldContext_ServerConfig_workspaceId(ctx, field) - case "serverURL": - return ec.fieldContext_ServerConfig_serverURL(ctx, field) - case "rootURI": - return ec.fieldContext_ServerConfig_rootURI(ctx, field) - case "hostName": - return ec.fieldContext_ServerConfig_hostName(ctx, field) - case "anonymousAccessEnabled": - return ec.fieldContext_ServerConfig_anonymousAccessEnabled(ctx, field) - case "authenticationEnabled": - return ec.fieldContext_ServerConfig_authenticationEnabled(ctx, field) - case "supportsCustomConnections": - return ec.fieldContext_ServerConfig_supportsCustomConnections(ctx, field) - case "supportsConnectionBrowser": - return ec.fieldContext_ServerConfig_supportsConnectionBrowser(ctx, field) - case "supportsWorkspaces": - return ec.fieldContext_ServerConfig_supportsWorkspaces(ctx, field) - case "resourceManagerEnabled": - return ec.fieldContext_ServerConfig_resourceManagerEnabled(ctx, field) - case "publicCredentialsSaveEnabled": - return ec.fieldContext_ServerConfig_publicCredentialsSaveEnabled(ctx, field) - case "adminCredentialsSaveEnabled": - return ec.fieldContext_ServerConfig_adminCredentialsSaveEnabled(ctx, field) - case "licenseRequired": - return ec.fieldContext_ServerConfig_licenseRequired(ctx, field) - case "licenseValid": - return ec.fieldContext_ServerConfig_licenseValid(ctx, field) - case "sessionExpireTime": - return ec.fieldContext_ServerConfig_sessionExpireTime(ctx, field) - case "localHostAddress": - return ec.fieldContext_ServerConfig_localHostAddress(ctx, field) - case "configurationMode": - return ec.fieldContext_ServerConfig_configurationMode(ctx, field) - case "developmentMode": - return ec.fieldContext_ServerConfig_developmentMode(ctx, field) - case "redirectOnFederatedAuth": - return ec.fieldContext_ServerConfig_redirectOnFederatedAuth(ctx, field) - case "enabledFeatures": - return ec.fieldContext_ServerConfig_enabledFeatures(ctx, field) - case "enabledAuthProviders": - return ec.fieldContext_ServerConfig_enabledAuthProviders(ctx, field) - case "supportedLanguages": - return ec.fieldContext_ServerConfig_supportedLanguages(ctx, field) - case "services": - return ec.fieldContext_ServerConfig_services(ctx, field) - case "productConfiguration": - return ec.fieldContext_ServerConfig_productConfiguration(ctx, field) - case "productInfo": - return ec.fieldContext_ServerConfig_productInfo(ctx, field) - case "defaultNavigatorSettings": - return ec.fieldContext_ServerConfig_defaultNavigatorSettings(ctx, field) - case "disabledDrivers": - return ec.fieldContext_ServerConfig_disabledDrivers(ctx, field) - case "resourceQuotas": - return ec.fieldContext_ServerConfig_resourceQuotas(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerConfig", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_sessionState(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sessionState(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SessionState(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SessionInfo) - fc.Result = res - return ec.marshalNSessionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSessionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sessionState(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "createTime": - return ec.fieldContext_SessionInfo_createTime(ctx, field) - case "lastAccessTime": - return ec.fieldContext_SessionInfo_lastAccessTime(ctx, field) - case "locale": - return ec.fieldContext_SessionInfo_locale(ctx, field) - case "cacheExpired": - return ec.fieldContext_SessionInfo_cacheExpired(ctx, field) - case "serverMessages": - return ec.fieldContext_SessionInfo_serverMessages(ctx, field) - case "connections": - return ec.fieldContext_SessionInfo_connections(ctx, field) - case "actionParameters": - return ec.fieldContext_SessionInfo_actionParameters(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SessionInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_sessionPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sessionPermissions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SessionPermissions(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNID2ᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sessionPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_driverList(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_driverList(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DriverList(rctx, fc.Args["id"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DriverInfo) - fc.Result = res - return ec.marshalNDriverInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDriverInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_driverList(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_DriverInfo_id(ctx, field) - case "name": - return ec.fieldContext_DriverInfo_name(ctx, field) - case "description": - return ec.fieldContext_DriverInfo_description(ctx, field) - case "icon": - return ec.fieldContext_DriverInfo_icon(ctx, field) - case "iconBig": - return ec.fieldContext_DriverInfo_iconBig(ctx, field) - case "providerId": - return ec.fieldContext_DriverInfo_providerId(ctx, field) - case "driverClassName": - return ec.fieldContext_DriverInfo_driverClassName(ctx, field) - case "defaultHost": - return ec.fieldContext_DriverInfo_defaultHost(ctx, field) - case "defaultPort": - return ec.fieldContext_DriverInfo_defaultPort(ctx, field) - case "defaultDatabase": - return ec.fieldContext_DriverInfo_defaultDatabase(ctx, field) - case "defaultServer": - return ec.fieldContext_DriverInfo_defaultServer(ctx, field) - case "defaultUser": - return ec.fieldContext_DriverInfo_defaultUser(ctx, field) - case "sampleURL": - return ec.fieldContext_DriverInfo_sampleURL(ctx, field) - case "driverInfoURL": - return ec.fieldContext_DriverInfo_driverInfoURL(ctx, field) - case "driverPropertiesURL": - return ec.fieldContext_DriverInfo_driverPropertiesURL(ctx, field) - case "embedded": - return ec.fieldContext_DriverInfo_embedded(ctx, field) - case "enabled": - return ec.fieldContext_DriverInfo_enabled(ctx, field) - case "requiresServerName": - return ec.fieldContext_DriverInfo_requiresServerName(ctx, field) - case "allowsEmptyPassword": - return ec.fieldContext_DriverInfo_allowsEmptyPassword(ctx, field) - case "licenseRequired": - return ec.fieldContext_DriverInfo_licenseRequired(ctx, field) - case "license": - return ec.fieldContext_DriverInfo_license(ctx, field) - case "custom": - return ec.fieldContext_DriverInfo_custom(ctx, field) - case "promotedScore": - return ec.fieldContext_DriverInfo_promotedScore(ctx, field) - case "driverProperties": - return ec.fieldContext_DriverInfo_driverProperties(ctx, field) - case "driverParameters": - return ec.fieldContext_DriverInfo_driverParameters(ctx, field) - case "providerProperties": - return ec.fieldContext_DriverInfo_providerProperties(ctx, field) - case "anonymousAccess": - return ec.fieldContext_DriverInfo_anonymousAccess(ctx, field) - case "defaultAuthModel": - return ec.fieldContext_DriverInfo_defaultAuthModel(ctx, field) - case "applicableAuthModels": - return ec.fieldContext_DriverInfo_applicableAuthModels(ctx, field) - case "applicableNetworkHandlers": - return ec.fieldContext_DriverInfo_applicableNetworkHandlers(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type DriverInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_driverList_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_authModels(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authModels(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthModels(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DatabaseAuthModel) - fc.Result = res - return ec.marshalNDatabaseAuthModel2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseAuthModelᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_authModels(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_DatabaseAuthModel_id(ctx, field) - case "displayName": - return ec.fieldContext_DatabaseAuthModel_displayName(ctx, field) - case "description": - return ec.fieldContext_DatabaseAuthModel_description(ctx, field) - case "icon": - return ec.fieldContext_DatabaseAuthModel_icon(ctx, field) - case "requiresLocalConfiguration": - return ec.fieldContext_DatabaseAuthModel_requiresLocalConfiguration(ctx, field) - case "properties": - return ec.fieldContext_DatabaseAuthModel_properties(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type DatabaseAuthModel", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_networkHandlers(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_networkHandlers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NetworkHandlers(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NetworkHandlerDescriptor) - fc.Result = res - return ec.marshalNNetworkHandlerDescriptor2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerDescriptorᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_networkHandlers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_NetworkHandlerDescriptor_id(ctx, field) - case "codeName": - return ec.fieldContext_NetworkHandlerDescriptor_codeName(ctx, field) - case "label": - return ec.fieldContext_NetworkHandlerDescriptor_label(ctx, field) - case "description": - return ec.fieldContext_NetworkHandlerDescriptor_description(ctx, field) - case "secured": - return ec.fieldContext_NetworkHandlerDescriptor_secured(ctx, field) - case "type": - return ec.fieldContext_NetworkHandlerDescriptor_type(ctx, field) - case "properties": - return ec.fieldContext_NetworkHandlerDescriptor_properties(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NetworkHandlerDescriptor", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_userConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_userConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().UserConnections(rctx, fc.Args["id"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_userConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_userConnections_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_templateConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_templateConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().TemplateConnections(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_templateConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_connectionFolders(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_connectionFolders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ConnectionFolders(rctx, fc.Args["path"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionFolderInfo) - fc.Result = res - return ec.marshalNConnectionFolderInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionFolderInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_connectionFolders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionFolderInfo_id(ctx, field) - case "description": - return ec.fieldContext_ConnectionFolderInfo_description(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionFolderInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_connectionFolders_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_connectionState(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_connectionState(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ConnectionState(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_connectionState(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_connectionState_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_connectionInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_connectionInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ConnectionInfo(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_connectionInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_connectionInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_readSessionLog(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_readSessionLog(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ReadSessionLog(rctx, fc.Args["maxEntries"].(*int), fc.Args["clearEntries"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.LogEntry) - fc.Result = res - return ec.marshalNLogEntry2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐLogEntryᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_readSessionLog(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "time": - return ec.fieldContext_LogEntry_time(ctx, field) - case "type": - return ec.fieldContext_LogEntry_type(ctx, field) - case "message": - return ec.fieldContext_LogEntry_message(ctx, field) - case "stackTrace": - return ec.fieldContext_LogEntry_stackTrace(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type LogEntry", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_readSessionLog_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_dataTransferAvailableStreamProcessors(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_dataTransferAvailableStreamProcessors(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DataTransferAvailableStreamProcessors(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DataTransferProcessorInfo) - fc.Result = res - return ec.marshalNDataTransferProcessorInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTransferProcessorInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_dataTransferAvailableStreamProcessors(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_DataTransferProcessorInfo_id(ctx, field) - case "name": - return ec.fieldContext_DataTransferProcessorInfo_name(ctx, field) - case "description": - return ec.fieldContext_DataTransferProcessorInfo_description(ctx, field) - case "fileExtension": - return ec.fieldContext_DataTransferProcessorInfo_fileExtension(ctx, field) - case "appFileExtension": - return ec.fieldContext_DataTransferProcessorInfo_appFileExtension(ctx, field) - case "appName": - return ec.fieldContext_DataTransferProcessorInfo_appName(ctx, field) - case "order": - return ec.fieldContext_DataTransferProcessorInfo_order(ctx, field) - case "icon": - return ec.fieldContext_DataTransferProcessorInfo_icon(ctx, field) - case "properties": - return ec.fieldContext_DataTransferProcessorInfo_properties(ctx, field) - case "isBinary": - return ec.fieldContext_DataTransferProcessorInfo_isBinary(ctx, field) - case "isHTML": - return ec.fieldContext_DataTransferProcessorInfo_isHTML(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type DataTransferProcessorInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_dataTransferExportDataFromContainer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_dataTransferExportDataFromContainer(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DataTransferExportDataFromContainer(rctx, fc.Args["connectionId"].(string), fc.Args["containerNodePath"].(string), fc.Args["parameters"].(model.DataTransferParameters)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_dataTransferExportDataFromContainer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_dataTransferExportDataFromContainer_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_dataTransferExportDataFromResults(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_dataTransferExportDataFromResults(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DataTransferExportDataFromResults(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["parameters"].(model.DataTransferParameters)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_dataTransferExportDataFromResults(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_dataTransferExportDataFromResults_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_dataTransferRemoveDataFile(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_dataTransferRemoveDataFile(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DataTransferRemoveDataFile(rctx, fc.Args["dataFileId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_dataTransferRemoveDataFile(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_dataTransferRemoveDataFile_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_metadataGetNodeDDL(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_metadataGetNodeDDL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().MetadataGetNodeDdl(rctx, fc.Args["nodeId"].(string), - func() interface{} { - if fc.Args["options"] == nil { - return nil - } - return fc.Args["options"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_metadataGetNodeDDL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_metadataGetNodeDDL_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_navNodeChildren(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navNodeChildren(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavNodeChildren(rctx, fc.Args["parentPath"].(string), fc.Args["offset"].(*int), fc.Args["limit"].(*int), fc.Args["onlyFolders"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_navNodeChildren(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) - case "name": - return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) - case "fullName": - return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) - case "icon": - return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) - case "description": - return ec.fieldContext_NavigatorNodeInfo_description(ctx, field) - case "nodeType": - return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) - case "hasChildren": - return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) - case "object": - return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) - case "features": - return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) - case "nodeDetails": - return ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) - case "folder": - return ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) - case "inline": - return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) - case "navigable": - return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_navNodeChildren_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_navNodeParents(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navNodeParents(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavNodeParents(rctx, fc.Args["nodePath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_navNodeParents(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) - case "name": - return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) - case "fullName": - return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) - case "icon": - return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) - case "description": - return ec.fieldContext_NavigatorNodeInfo_description(ctx, field) - case "nodeType": - return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) - case "hasChildren": - return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) - case "object": - return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) - case "features": - return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) - case "nodeDetails": - return ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) - case "folder": - return ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) - case "inline": - return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) - case "navigable": - return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_navNodeParents_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_navNodeInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navNodeInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavNodeInfo(rctx, fc.Args["nodePath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_navNodeInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) - case "name": - return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) - case "fullName": - return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) - case "icon": - return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) - case "description": - return ec.fieldContext_NavigatorNodeInfo_description(ctx, field) - case "nodeType": - return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) - case "hasChildren": - return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) - case "object": - return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) - case "features": - return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) - case "nodeDetails": - return ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) - case "folder": - return ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) - case "inline": - return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) - case "navigable": - return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_navNodeInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_navRefreshNode(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navRefreshNode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavRefreshNode(rctx, fc.Args["nodePath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_navRefreshNode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_navRefreshNode_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_navGetStructContainers(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navGetStructContainers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavGetStructContainers(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(*string), fc.Args["catalog"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.DatabaseStructContainers) - fc.Result = res - return ec.marshalNDatabaseStructContainers2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseStructContainers(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_navGetStructContainers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "catalogList": - return ec.fieldContext_DatabaseStructContainers_catalogList(ctx, field) - case "schemaList": - return ec.fieldContext_DatabaseStructContainers_schemaList(ctx, field) - case "supportsCatalogChange": - return ec.fieldContext_DatabaseStructContainers_supportsCatalogChange(ctx, field) - case "supportsSchemaChange": - return ec.fieldContext_DatabaseStructContainers_supportsSchemaChange(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type DatabaseStructContainers", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_navGetStructContainers_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_rmListProjects(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_rmListProjects(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().RmListProjects(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.RMProject) - fc.Result = res - return ec.marshalNRMProject2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐRMProjectᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_rmListProjects(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_RMProject_id(ctx, field) - case "name": - return ec.fieldContext_RMProject_name(ctx, field) - case "description": - return ec.fieldContext_RMProject_description(ctx, field) - case "shared": - return ec.fieldContext_RMProject_shared(ctx, field) - case "createTime": - return ec.fieldContext_RMProject_createTime(ctx, field) - case "creator": - return ec.fieldContext_RMProject_creator(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type RMProject", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _Query_rmListResources(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_rmListResources(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().RmListResources(rctx, fc.Args["projectId"].(string), fc.Args["folder"].(*string), fc.Args["nameMask"].(*string), fc.Args["readProperties"].(*bool), fc.Args["readHistory"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.RMResource) - fc.Result = res - return ec.marshalNRMResource2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐRMResourceᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_rmListResources(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext_RMResource_name(ctx, field) - case "folder": - return ec.fieldContext_RMResource_folder(ctx, field) - case "length": - return ec.fieldContext_RMResource_length(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type RMResource", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_rmListResources_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_rmReadResourceAsString(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_rmReadResourceAsString(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().RmReadResourceAsString(rctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_rmReadResourceAsString(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_rmReadResourceAsString_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlDialectInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlDialectInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLDialectInfo(rctx, fc.Args["connectionId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.SQLDialectInfo) - fc.Result = res - return ec.marshalOSQLDialectInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDialectInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlDialectInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext_SQLDialectInfo_name(ctx, field) - case "dataTypes": - return ec.fieldContext_SQLDialectInfo_dataTypes(ctx, field) - case "functions": - return ec.fieldContext_SQLDialectInfo_functions(ctx, field) - case "reservedWords": - return ec.fieldContext_SQLDialectInfo_reservedWords(ctx, field) - case "quoteStrings": - return ec.fieldContext_SQLDialectInfo_quoteStrings(ctx, field) - case "singleLineComments": - return ec.fieldContext_SQLDialectInfo_singleLineComments(ctx, field) - case "multiLineComments": - return ec.fieldContext_SQLDialectInfo_multiLineComments(ctx, field) - case "catalogSeparator": - return ec.fieldContext_SQLDialectInfo_catalogSeparator(ctx, field) - case "structSeparator": - return ec.fieldContext_SQLDialectInfo_structSeparator(ctx, field) - case "scriptDelimiter": - return ec.fieldContext_SQLDialectInfo_scriptDelimiter(ctx, field) - case "supportsExplainExecutionPlan": - return ec.fieldContext_SQLDialectInfo_supportsExplainExecutionPlan(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLDialectInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlDialectInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlListContexts(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlListContexts(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLListContexts(rctx, fc.Args["connectionId"].(*string), fc.Args["contextId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLContextInfo) - fc.Result = res - return ec.marshalNSQLContextInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLContextInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlListContexts(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_SQLContextInfo_id(ctx, field) - case "connectionId": - return ec.fieldContext_SQLContextInfo_connectionId(ctx, field) - case "defaultCatalog": - return ec.fieldContext_SQLContextInfo_defaultCatalog(ctx, field) - case "defaultSchema": - return ec.fieldContext_SQLContextInfo_defaultSchema(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLContextInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlListContexts_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlCompletionProposals(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlCompletionProposals(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLCompletionProposals(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string), fc.Args["position"].(int), fc.Args["maxResults"].(*int), fc.Args["simpleMode"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.SQLCompletionProposal) - fc.Result = res - return ec.marshalOSQLCompletionProposal2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLCompletionProposal(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlCompletionProposals(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "displayString": - return ec.fieldContext_SQLCompletionProposal_displayString(ctx, field) - case "type": - return ec.fieldContext_SQLCompletionProposal_type(ctx, field) - case "score": - return ec.fieldContext_SQLCompletionProposal_score(ctx, field) - case "replacementString": - return ec.fieldContext_SQLCompletionProposal_replacementString(ctx, field) - case "replacementOffset": - return ec.fieldContext_SQLCompletionProposal_replacementOffset(ctx, field) - case "replacementLength": - return ec.fieldContext_SQLCompletionProposal_replacementLength(ctx, field) - case "cursorPosition": - return ec.fieldContext_SQLCompletionProposal_cursorPosition(ctx, field) - case "icon": - return ec.fieldContext_SQLCompletionProposal_icon(ctx, field) - case "nodePath": - return ec.fieldContext_SQLCompletionProposal_nodePath(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLCompletionProposal", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlCompletionProposals_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlFormatQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlFormatQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLFormatQuery(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlFormatQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlFormatQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlSupportedOperations(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlSupportedOperations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLSupportedOperations(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["attributeIndex"].(int)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DataTypeLogicalOperation) - fc.Result = res - return ec.marshalNDataTypeLogicalOperation2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTypeLogicalOperationᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlSupportedOperations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_DataTypeLogicalOperation_id(ctx, field) - case "expression": - return ec.fieldContext_DataTypeLogicalOperation_expression(ctx, field) - case "argumentCount": - return ec.fieldContext_DataTypeLogicalOperation_argumentCount(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type DataTypeLogicalOperation", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlSupportedOperations_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlEntityQueryGenerators(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlEntityQueryGenerators(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLEntityQueryGenerators(rctx, fc.Args["nodePathList"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLQueryGenerator) - fc.Result = res - return ec.marshalNSQLQueryGenerator2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLQueryGeneratorᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlEntityQueryGenerators(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_SQLQueryGenerator_id(ctx, field) - case "label": - return ec.fieldContext_SQLQueryGenerator_label(ctx, field) - case "description": - return ec.fieldContext_SQLQueryGenerator_description(ctx, field) - case "order": - return ec.fieldContext_SQLQueryGenerator_order(ctx, field) - case "multiObject": - return ec.fieldContext_SQLQueryGenerator_multiObject(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLQueryGenerator", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlEntityQueryGenerators_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlGenerateEntityQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlGenerateEntityQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLGenerateEntityQuery(rctx, fc.Args["generatorId"].(string), - func() interface{} { - if fc.Args["options"] == nil { - return nil - } - return fc.Args["options"].(interface{}) - }(), fc.Args["nodePathList"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlGenerateEntityQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlGenerateEntityQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlParseScript(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlParseScript(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLParseScript(rctx, fc.Args["connectionId"].(string), fc.Args["script"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLScriptInfo) - fc.Result = res - return ec.marshalNSQLScriptInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlParseScript(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "queries": - return ec.fieldContext_SQLScriptInfo_queries(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLScriptInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlParseScript_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_sqlParseQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlParseQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLParseQuery(rctx, fc.Args["connectionId"].(string), fc.Args["script"].(string), fc.Args["position"].(int)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLScriptQuery) - fc.Result = res - return ec.marshalNSQLScriptQuery2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptQuery(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_sqlParseQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "start": - return ec.fieldContext_SQLScriptQuery_start(ctx, field) - case "end": - return ec.fieldContext_SQLScriptQuery_end(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLScriptQuery", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_sqlParseQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query___type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.introspectType(fc.Args["name"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query___type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query___type_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query___schema(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query___schema(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.introspectSchema() - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Schema) - fc.Result = res - return ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query___schema(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "description": - return ec.fieldContext___Schema_description(ctx, field) - case "types": - return ec.fieldContext___Schema_types(ctx, field) - case "queryType": - return ec.fieldContext___Schema_queryType(ctx, field) - case "mutationType": - return ec.fieldContext___Schema_mutationType(ctx, field) - case "subscriptionType": - return ec.fieldContext___Schema_subscriptionType(ctx, field) - case "directives": - return ec.fieldContext___Schema_directives(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Schema", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _RMProject_id(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMProject_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMProject", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _RMProject_name(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMProject_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMProject", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _RMProject_description(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMProject_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMProject", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _RMProject_shared(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_shared(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Shared, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMProject_shared(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMProject", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _RMProject_createTime(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_createTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CreateTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(time.Time) - fc.Result = res - return ec.marshalNDateTime2timeᚐTime(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMProject_createTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMProject", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type DateTime does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _RMProject_creator(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_creator(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Creator, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMProject_creator(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMProject", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _RMResource_name(ctx context.Context, field graphql.CollectedField, obj *model.RMResource) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMResource_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMResource_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMResource", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _RMResource_folder(ctx context.Context, field graphql.CollectedField, obj *model.RMResource) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMResource_folder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Folder, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMResource_folder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMResource", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _RMResource_length(ctx context.Context, field graphql.CollectedField, obj *model.RMResource) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMResource_length(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Length, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_RMResource_length(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "RMResource", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_displayString(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_displayString(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayString, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_displayString(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_type(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_score(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_score(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Score, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_score(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_replacementString(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_replacementString(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReplacementString, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementString(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_replacementOffset(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_replacementOffset(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReplacementOffset, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementOffset(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_replacementLength(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_replacementLength(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReplacementLength, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementLength(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_cursorPosition(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_cursorPosition(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CursorPosition, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_cursorPosition(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_icon(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLCompletionProposal_nodePath(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_nodePath(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NodePath, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLCompletionProposal_nodePath(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLContextInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLContextInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLContextInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLContextInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLContextInfo_connectionId(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLContextInfo_connectionId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConnectionID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLContextInfo_connectionId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLContextInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLContextInfo_defaultCatalog(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLContextInfo_defaultCatalog(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultCatalog, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLContextInfo_defaultCatalog(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLContextInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLContextInfo_defaultSchema(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLContextInfo_defaultSchema(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultSchema, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLContextInfo_defaultSchema(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLContextInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_dataTypes(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_dataTypes(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataTypes, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNString2ᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_dataTypes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_functions(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_functions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Functions, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNString2ᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_functions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_reservedWords(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_reservedWords(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReservedWords, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNString2ᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_reservedWords(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_quoteStrings(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_quoteStrings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.QuoteStrings, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([][]*string) - fc.Result = res - return ec.marshalNString2ᚕᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_quoteStrings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_singleLineComments(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_singleLineComments(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SingleLineComments, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNString2ᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_singleLineComments(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_multiLineComments(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_multiLineComments(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MultiLineComments, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([][]*string) - fc.Result = res - return ec.marshalNString2ᚕᚕᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_multiLineComments(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_catalogSeparator(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_catalogSeparator(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CatalogSeparator, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_catalogSeparator(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_structSeparator(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_structSeparator(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StructSeparator, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_structSeparator(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_scriptDelimiter(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_scriptDelimiter(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ScriptDelimiter, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_scriptDelimiter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLDialectInfo_supportsExplainExecutionPlan(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_supportsExplainExecutionPlan(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsExplainExecutionPlan, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLDialectInfo_supportsExplainExecutionPlan(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLDialectInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecuteInfo_statusMessage(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecuteInfo_statusMessage(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StatusMessage, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecuteInfo_statusMessage(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecuteInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecuteInfo_duration(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecuteInfo_duration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Duration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecuteInfo_duration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecuteInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecuteInfo_filterText(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecuteInfo_filterText(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FilterText, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecuteInfo_filterText(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecuteInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecuteInfo_results(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecuteInfo_results(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Results, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLQueryResults) - fc.Result = res - return ec.marshalNSQLQueryResults2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLQueryResultsᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecuteInfo_results(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecuteInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "title": - return ec.fieldContext_SQLQueryResults_title(ctx, field) - case "updateRowCount": - return ec.fieldContext_SQLQueryResults_updateRowCount(ctx, field) - case "sourceQuery": - return ec.fieldContext_SQLQueryResults_sourceQuery(ctx, field) - case "dataFormat": - return ec.fieldContext_SQLQueryResults_dataFormat(ctx, field) - case "resultSet": - return ec.fieldContext_SQLQueryResults_resultSet(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLQueryResults", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlan_query(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlan) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlan_query(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Query, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlan_query(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlan", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlan_nodes(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlan) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlan_nodes(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Nodes, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLExecutionPlanNode) - fc.Result = res - return ec.marshalNSQLExecutionPlanNode2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecutionPlanNodeᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlan_nodes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlan", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_SQLExecutionPlanNode_id(ctx, field) - case "parentId": - return ec.fieldContext_SQLExecutionPlanNode_parentId(ctx, field) - case "kind": - return ec.fieldContext_SQLExecutionPlanNode_kind(ctx, field) - case "name": - return ec.fieldContext_SQLExecutionPlanNode_name(ctx, field) - case "type": - return ec.fieldContext_SQLExecutionPlanNode_type(ctx, field) - case "condition": - return ec.fieldContext_SQLExecutionPlanNode_condition(ctx, field) - case "description": - return ec.fieldContext_SQLExecutionPlanNode_description(ctx, field) - case "properties": - return ec.fieldContext_SQLExecutionPlanNode_properties(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLExecutionPlanNode", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlanNode_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlanNode", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlanNode_parentId(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_parentId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ParentID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_parentId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlanNode", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlanNode_kind(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_kind(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Kind, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_kind(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlanNode", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlanNode_name(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlanNode", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlanNode_type(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlanNode", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlanNode_condition(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_condition(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Condition, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_condition(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlanNode", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlanNode_description(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlanNode", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLExecutionPlanNode_properties(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLExecutionPlanNode", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryGenerator_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryGenerator_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryGenerator", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryGenerator_label(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryGenerator_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryGenerator", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryGenerator_description(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryGenerator_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryGenerator", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryGenerator_order(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_order(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Order, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryGenerator_order(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryGenerator", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryGenerator_multiObject(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_multiObject(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MultiObject, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryGenerator_multiObject(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryGenerator", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryResults_title(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_title(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Title, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryResults_title(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryResults", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryResults_updateRowCount(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_updateRowCount(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UpdateRowCount, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*float64) - fc.Result = res - return ec.marshalOFloat2ᚖfloat64(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryResults_updateRowCount(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryResults", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Float does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryResults_sourceQuery(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_sourceQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SourceQuery, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryResults_sourceQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryResults", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryResults_dataFormat(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_dataFormat(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataFormat, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.ResultDataFormat) - fc.Result = res - return ec.marshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryResults_dataFormat(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryResults", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ResultDataFormat does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryResults_resultSet(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_resultSet(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ResultSet, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.SQLResultSet) - fc.Result = res - return ec.marshalOSQLResultSet2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultSet(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLQueryResults_resultSet(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLQueryResults", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_SQLResultSet_id(ctx, field) - case "columns": - return ec.fieldContext_SQLResultSet_columns(ctx, field) - case "rows": - return ec.fieldContext_SQLResultSet_rows(ctx, field) - case "singleEntity": - return ec.fieldContext_SQLResultSet_singleEntity(ctx, field) - case "hasMoreData": - return ec.fieldContext_SQLResultSet_hasMoreData(ctx, field) - case "hasRowIdentifier": - return ec.fieldContext_SQLResultSet_hasRowIdentifier(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLResultSet", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_position(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_position(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Position, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_position(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_name(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_label(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_icon(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_entityName(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_entityName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EntityName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_entityName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_dataKind(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_dataKind(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataKind, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_dataKind(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_typeName(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_typeName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.TypeName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_typeName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_fullTypeName(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_fullTypeName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FullTypeName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_fullTypeName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_maxLength(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_maxLength(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MaxLength, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*float64) - fc.Result = res - return ec.marshalOFloat2ᚖfloat64(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_maxLength(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Float does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_scale(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_scale(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Scale, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_scale(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_precision(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_precision(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Precision, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_precision(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_required(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_required(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Required, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_required(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_readOnly(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_readOnly(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReadOnly, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_readOnly(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_readOnlyStatus(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_readOnlyStatus(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReadOnlyStatus, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_readOnlyStatus(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultColumn_supportedOperations(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_supportedOperations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportedOperations, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DataTypeLogicalOperation) - fc.Result = res - return ec.marshalNDataTypeLogicalOperation2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTypeLogicalOperationᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultColumn_supportedOperations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultColumn", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_DataTypeLogicalOperation_id(ctx, field) - case "expression": - return ec.fieldContext_DataTypeLogicalOperation_expression(ctx, field) - case "argumentCount": - return ec.fieldContext_DataTypeLogicalOperation_argumentCount(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type DataTypeLogicalOperation", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultSet_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultSet_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultSet_columns(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_columns(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Columns, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.SQLResultColumn) - fc.Result = res - return ec.marshalOSQLResultColumn2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultColumn(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultSet_columns(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "position": - return ec.fieldContext_SQLResultColumn_position(ctx, field) - case "name": - return ec.fieldContext_SQLResultColumn_name(ctx, field) - case "label": - return ec.fieldContext_SQLResultColumn_label(ctx, field) - case "icon": - return ec.fieldContext_SQLResultColumn_icon(ctx, field) - case "entityName": - return ec.fieldContext_SQLResultColumn_entityName(ctx, field) - case "dataKind": - return ec.fieldContext_SQLResultColumn_dataKind(ctx, field) - case "typeName": - return ec.fieldContext_SQLResultColumn_typeName(ctx, field) - case "fullTypeName": - return ec.fieldContext_SQLResultColumn_fullTypeName(ctx, field) - case "maxLength": - return ec.fieldContext_SQLResultColumn_maxLength(ctx, field) - case "scale": - return ec.fieldContext_SQLResultColumn_scale(ctx, field) - case "precision": - return ec.fieldContext_SQLResultColumn_precision(ctx, field) - case "required": - return ec.fieldContext_SQLResultColumn_required(ctx, field) - case "readOnly": - return ec.fieldContext_SQLResultColumn_readOnly(ctx, field) - case "readOnlyStatus": - return ec.fieldContext_SQLResultColumn_readOnlyStatus(ctx, field) - case "supportedOperations": - return ec.fieldContext_SQLResultColumn_supportedOperations(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLResultColumn", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultSet_rows(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_rows(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Rows, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([][]interface{}) - fc.Result = res - return ec.marshalOObject2ᚕᚕinterface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultSet_rows(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultSet_singleEntity(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_singleEntity(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SingleEntity, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultSet_singleEntity(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultSet_hasMoreData(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_hasMoreData(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HasMoreData, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultSet_hasMoreData(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLResultSet_hasRowIdentifier(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_hasRowIdentifier(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HasRowIdentifier, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLResultSet_hasRowIdentifier(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLResultSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLScriptInfo_queries(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLScriptInfo_queries(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Queries, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLScriptQuery) - fc.Result = res - return ec.marshalNSQLScriptQuery2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptQueryᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLScriptInfo_queries(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLScriptInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "start": - return ec.fieldContext_SQLScriptQuery_start(ctx, field) - case "end": - return ec.fieldContext_SQLScriptQuery_end(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLScriptQuery", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLScriptQuery_start(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptQuery) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLScriptQuery_start(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Start, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLScriptQuery_start(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLScriptQuery", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLScriptQuery_end(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptQuery) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLScriptQuery_end(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.End, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SQLScriptQuery_end(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SQLScriptQuery", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_name(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_version(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_version(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Version, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_version(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_workspaceId(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_workspaceId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.WorkspaceID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_workspaceId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_serverURL(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_serverURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_serverURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_rootURI(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_rootURI(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RootURI, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_rootURI(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_hostName(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_hostName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HostName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_hostName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_anonymousAccessEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_anonymousAccessEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AnonymousAccessEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_anonymousAccessEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_authenticationEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_authenticationEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthenticationEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_authenticationEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_supportsCustomConnections(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_supportsCustomConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsCustomConnections, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_supportsCustomConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_supportsConnectionBrowser(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_supportsConnectionBrowser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsConnectionBrowser, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_supportsConnectionBrowser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_supportsWorkspaces(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_supportsWorkspaces(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsWorkspaces, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_supportsWorkspaces(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_resourceManagerEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_resourceManagerEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ResourceManagerEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_resourceManagerEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_publicCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_publicCredentialsSaveEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PublicCredentialsSaveEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_publicCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_adminCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_adminCredentialsSaveEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AdminCredentialsSaveEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_adminCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_licenseRequired(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_licenseRequired(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LicenseRequired, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_licenseRequired(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_licenseValid(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_licenseValid(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LicenseValid, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_licenseValid(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_sessionExpireTime(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_sessionExpireTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SessionExpireTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_sessionExpireTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_localHostAddress(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_localHostAddress(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LocalHostAddress, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_localHostAddress(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_configurationMode(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_configurationMode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConfigurationMode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_configurationMode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_developmentMode(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_developmentMode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DevelopmentMode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_developmentMode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_redirectOnFederatedAuth(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_redirectOnFederatedAuth(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RedirectOnFederatedAuth, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_redirectOnFederatedAuth(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_enabledFeatures(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_enabledFeatures(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EnabledFeatures, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_enabledFeatures(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_enabledAuthProviders(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_enabledAuthProviders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EnabledAuthProviders, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_enabledAuthProviders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_supportedLanguages(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_supportedLanguages(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportedLanguages, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ServerLanguage) - fc.Result = res - return ec.marshalNServerLanguage2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerLanguageᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_supportedLanguages(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "isoCode": - return ec.fieldContext_ServerLanguage_isoCode(ctx, field) - case "displayName": - return ec.fieldContext_ServerLanguage_displayName(ctx, field) - case "nativeName": - return ec.fieldContext_ServerLanguage_nativeName(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerLanguage", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_services(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_services(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Services, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.WebServiceConfig) - fc.Result = res - return ec.marshalOWebServiceConfig2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐWebServiceConfig(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_services(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_WebServiceConfig_id(ctx, field) - case "name": - return ec.fieldContext_WebServiceConfig_name(ctx, field) - case "description": - return ec.fieldContext_WebServiceConfig_description(ctx, field) - case "bundleVersion": - return ec.fieldContext_WebServiceConfig_bundleVersion(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type WebServiceConfig", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_productConfiguration(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_productConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProductConfiguration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_productConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_productInfo(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_productInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProductInfo, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ProductInfo) - fc.Result = res - return ec.marshalNProductInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐProductInfo(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_productInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ProductInfo_id(ctx, field) - case "version": - return ec.fieldContext_ProductInfo_version(ctx, field) - case "name": - return ec.fieldContext_ProductInfo_name(ctx, field) - case "description": - return ec.fieldContext_ProductInfo_description(ctx, field) - case "buildTime": - return ec.fieldContext_ProductInfo_buildTime(ctx, field) - case "releaseTime": - return ec.fieldContext_ProductInfo_releaseTime(ctx, field) - case "licenseInfo": - return ec.fieldContext_ProductInfo_licenseInfo(ctx, field) - case "latestVersionInfo": - return ec.fieldContext_ProductInfo_latestVersionInfo(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ProductInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_defaultNavigatorSettings(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_defaultNavigatorSettings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultNavigatorSettings, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NavigatorSettings) - fc.Result = res - return ec.marshalNNavigatorSettings2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorSettings(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_defaultNavigatorSettings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "showSystemObjects": - return ec.fieldContext_NavigatorSettings_showSystemObjects(ctx, field) - case "showUtilityObjects": - return ec.fieldContext_NavigatorSettings_showUtilityObjects(ctx, field) - case "showOnlyEntities": - return ec.fieldContext_NavigatorSettings_showOnlyEntities(ctx, field) - case "mergeEntities": - return ec.fieldContext_NavigatorSettings_mergeEntities(ctx, field) - case "hideFolders": - return ec.fieldContext_NavigatorSettings_hideFolders(ctx, field) - case "hideSchemas": - return ec.fieldContext_NavigatorSettings_hideSchemas(ctx, field) - case "hideVirtualModel": - return ec.fieldContext_NavigatorSettings_hideVirtualModel(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type NavigatorSettings", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_disabledDrivers(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_disabledDrivers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisabledDrivers, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_disabledDrivers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerConfig_resourceQuotas(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_resourceQuotas(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ResourceQuotas, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerConfig_resourceQuotas(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerError_message(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerError_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerError", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerError_errorCode(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_errorCode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ErrorCode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerError_errorCode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerError", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerError_errorType(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_errorType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ErrorType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerError_errorType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerError", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerError_stackTrace(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_stackTrace(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StackTrace, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerError_stackTrace(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerError", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerError_causedBy(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_causedBy(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CausedBy, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.ServerError) - fc.Result = res - return ec.marshalOServerError2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerError(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerError_causedBy(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerError", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "message": - return ec.fieldContext_ServerError_message(ctx, field) - case "errorCode": - return ec.fieldContext_ServerError_errorCode(ctx, field) - case "errorType": - return ec.fieldContext_ServerError_errorType(ctx, field) - case "stackTrace": - return ec.fieldContext_ServerError_stackTrace(ctx, field) - case "causedBy": - return ec.fieldContext_ServerError_causedBy(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerError", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerLanguage_isoCode(ctx context.Context, field graphql.CollectedField, obj *model.ServerLanguage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerLanguage_isoCode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsoCode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerLanguage_isoCode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerLanguage", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerLanguage_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ServerLanguage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerLanguage_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerLanguage_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerLanguage", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerLanguage_nativeName(ctx context.Context, field graphql.CollectedField, obj *model.ServerLanguage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerLanguage_nativeName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NativeName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerLanguage_nativeName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerLanguage", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerMessage_time(ctx context.Context, field graphql.CollectedField, obj *model.ServerMessage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerMessage_time(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Time, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerMessage_time(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerMessage", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _ServerMessage_message(ctx context.Context, field graphql.CollectedField, obj *model.ServerMessage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerMessage_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_ServerMessage_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "ServerMessage", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_createTime(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_createTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CreateTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_createTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_lastAccessTime(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_lastAccessTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LastAccessTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_lastAccessTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_locale(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_locale(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Locale, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_locale(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_cacheExpired(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_cacheExpired(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CacheExpired, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_cacheExpired(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_serverMessages(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_serverMessages(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerMessages, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ServerMessage) - fc.Result = res - return ec.marshalOServerMessage2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerMessage(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_serverMessages(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "time": - return ec.fieldContext_ServerMessage_time(ctx, field) - case "message": - return ec.fieldContext_ServerMessage_message(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerMessage", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_connections(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_connections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Connections, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_connections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_actionParameters(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_actionParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ActionParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_actionParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserAuthToken_authProvider(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_authProvider(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthProvider, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserAuthToken_authProvider(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserAuthToken", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserAuthToken_authConfiguration(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_authConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthConfiguration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserAuthToken_authConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserAuthToken", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserAuthToken_loginTime(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_loginTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LoginTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(time.Time) - fc.Result = res - return ec.marshalNDateTime2timeᚐTime(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserAuthToken_loginTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserAuthToken", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type DateTime does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserAuthToken_userId(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_userId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserAuthToken_userId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserAuthToken", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserAuthToken_displayName(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserAuthToken_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserAuthToken", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserAuthToken_message(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserAuthToken_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserAuthToken", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserAuthToken_origin(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_origin(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Origin, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ObjectOrigin) - fc.Result = res - return ec.marshalNObjectOrigin2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectOrigin(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserAuthToken_origin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserAuthToken", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "type": - return ec.fieldContext_ObjectOrigin_type(ctx, field) - case "subType": - return ec.fieldContext_ObjectOrigin_subType(ctx, field) - case "displayName": - return ec.fieldContext_ObjectOrigin_displayName(ctx, field) - case "icon": - return ec.fieldContext_ObjectOrigin_icon(ctx, field) - case "configuration": - return ec.fieldContext_ObjectOrigin_configuration(ctx, field) - case "details": - return ec.fieldContext_ObjectOrigin_details(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectOrigin", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _UserInfo_userId(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_userId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserInfo_userId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserInfo_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserInfo_authRole(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_authRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthRole, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserInfo_authRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserInfo_authTokens(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_authTokens(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthTokens, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.UserAuthToken) - fc.Result = res - return ec.marshalNUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserAuthTokenᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserInfo_authTokens(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "authProvider": - return ec.fieldContext_UserAuthToken_authProvider(ctx, field) - case "authConfiguration": - return ec.fieldContext_UserAuthToken_authConfiguration(ctx, field) - case "loginTime": - return ec.fieldContext_UserAuthToken_loginTime(ctx, field) - case "userId": - return ec.fieldContext_UserAuthToken_userId(ctx, field) - case "displayName": - return ec.fieldContext_UserAuthToken_displayName(ctx, field) - case "message": - return ec.fieldContext_UserAuthToken_message(ctx, field) - case "origin": - return ec.fieldContext_UserAuthToken_origin(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type UserAuthToken", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _UserInfo_linkedAuthProviders(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_linkedAuthProviders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LinkedAuthProviders, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserInfo_linkedAuthProviders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserInfo_metaParameters(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_metaParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MetaParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserInfo_metaParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _UserInfo_configurationParameters(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_configurationParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConfigurationParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_UserInfo_configurationParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "UserInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebFeatureSet_id(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebFeatureSet_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebFeatureSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebFeatureSet_label(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebFeatureSet_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebFeatureSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebFeatureSet_description(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebFeatureSet_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebFeatureSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebFeatureSet_icon(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebFeatureSet_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebFeatureSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebFeatureSet_enabled(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_enabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Enabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebFeatureSet_enabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebFeatureSet", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebServiceConfig_id(ctx context.Context, field graphql.CollectedField, obj *model.WebServiceConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebServiceConfig_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebServiceConfig_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebServiceConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebServiceConfig_name(ctx context.Context, field graphql.CollectedField, obj *model.WebServiceConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebServiceConfig_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebServiceConfig_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebServiceConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebServiceConfig_description(ctx context.Context, field graphql.CollectedField, obj *model.WebServiceConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebServiceConfig_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebServiceConfig_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebServiceConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _WebServiceConfig_bundleVersion(ctx context.Context, field graphql.CollectedField, obj *model.WebServiceConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebServiceConfig_bundleVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.BundleVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_WebServiceConfig_bundleVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "WebServiceConfig", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Directive_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Directive", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Directive_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Directive_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Directive", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Directive_locations(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_locations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Locations, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalN__DirectiveLocation2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Directive_locations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Directive", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type __DirectiveLocation does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Directive_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_args(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Args, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Directive_args(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Directive", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext___InputValue_name(ctx, field) - case "description": - return ec.fieldContext___InputValue_description(ctx, field) - case "type": - return ec.fieldContext___InputValue_type(ctx, field) - case "defaultValue": - return ec.fieldContext___InputValue_defaultValue(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_isRepeatable(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsRepeatable, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Directive", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___EnumValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___EnumValue_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___EnumValue_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__EnumValue", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___EnumValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___EnumValue_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___EnumValue_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__EnumValue", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___EnumValue_isDeprecated(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsDeprecated(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__EnumValue", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___EnumValue_deprecationReason(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DeprecationReason(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__EnumValue", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Field_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Field_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Field", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Field_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Field_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Field", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Field_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_args(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Args, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Field_args(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Field", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext___InputValue_name(ctx, field) - case "description": - return ec.fieldContext___InputValue_description(ctx, field) - case "type": - return ec.fieldContext___InputValue_type(ctx, field) - case "defaultValue": - return ec.fieldContext___InputValue_defaultValue(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Field_type(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Field_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Field", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Field_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_isDeprecated(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsDeprecated(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Field_isDeprecated(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Field", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Field_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_deprecationReason(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DeprecationReason(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Field_deprecationReason(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Field", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___InputValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___InputValue_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___InputValue_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__InputValue", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___InputValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___InputValue_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___InputValue_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__InputValue", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___InputValue_type(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___InputValue_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___InputValue_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__InputValue", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___InputValue_defaultValue(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultValue, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__InputValue", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Schema_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Schema_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Schema", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Schema_types(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_types(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Types(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Schema_types(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Schema", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Schema_queryType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_queryType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.QueryType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Schema_queryType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Schema", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Schema_mutationType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_mutationType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MutationType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Schema_mutationType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Schema", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_subscriptionType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubscriptionType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Schema", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Schema_directives(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_directives(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Directives(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.Directive) - fc.Result = res - return ec.marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Schema_directives(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Schema", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext___Directive_name(ctx, field) - case "description": - return ec.fieldContext___Directive_description(ctx, field) - case "locations": - return ec.fieldContext___Directive_locations(ctx, field) - case "args": - return ec.fieldContext___Directive_args(ctx, field) - case "isRepeatable": - return ec.fieldContext___Directive_isRepeatable(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Directive", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Type_kind(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_kind(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Kind(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalN__TypeKind2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_kind(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type __TypeKind does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Type_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Type_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) ___Type_fields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_fields(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Fields(fc.Args["includeDeprecated"].(bool)), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Field) - fc.Result = res - return ec.marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_fields(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext___Field_name(ctx, field) - case "description": - return ec.fieldContext___Field_description(ctx, field) - case "args": - return ec.fieldContext___Field_args(ctx, field) - case "type": - return ec.fieldContext___Field_type(ctx, field) - case "isDeprecated": - return ec.fieldContext___Field_isDeprecated(ctx, field) - case "deprecationReason": - return ec.fieldContext___Field_deprecationReason(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Field", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field___Type_fields_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) ___Type_interfaces(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_interfaces(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Interfaces(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_interfaces(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Type_possibleTypes(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_possibleTypes(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PossibleTypes(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_possibleTypes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Type_enumValues(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_enumValues(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EnumValues(fc.Args["includeDeprecated"].(bool)), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.EnumValue) - fc.Result = res - return ec.marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_enumValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext___EnumValue_name(ctx, field) - case "description": - return ec.fieldContext___EnumValue_description(ctx, field) - case "isDeprecated": - return ec.fieldContext___EnumValue_isDeprecated(ctx, field) - case "deprecationReason": - return ec.fieldContext___EnumValue_deprecationReason(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __EnumValue", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field___Type_enumValues_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) ___Type_inputFields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_inputFields(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.InputFields(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_inputFields(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "name": - return ec.fieldContext___InputValue_name(ctx, field) - case "description": - return ec.fieldContext___InputValue_description(ctx, field) - case "type": - return ec.fieldContext___InputValue_type(ctx, field) - case "defaultValue": - return ec.fieldContext___InputValue_defaultValue(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_ofType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.OfType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_ofType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "kind": - return ec.fieldContext___Type_kind(ctx, field) - case "name": - return ec.fieldContext___Type_name(ctx, field) - case "description": - return ec.fieldContext___Type_description(ctx, field) - case "fields": - return ec.fieldContext___Type_fields(ctx, field) - case "interfaces": - return ec.fieldContext___Type_interfaces(ctx, field) - case "possibleTypes": - return ec.fieldContext___Type_possibleTypes(ctx, field) - case "enumValues": - return ec.fieldContext___Type_enumValues(ctx, field) - case "inputFields": - return ec.fieldContext___Type_inputFields(ctx, field) - case "ofType": - return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) ___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_specifiedByURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SpecifiedByURL(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Type", - Field: field, - IsMethod: true, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -// endregion **************************** field.gotpl ***************************** - -// region **************************** input.gotpl ***************************** - -func (ec *executionContext) unmarshalInputConnectionConfig(ctx context.Context, obj interface{}) (model.ConnectionConfig, error) { - var it model.ConnectionConfig - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"connectionId", "name", "description", "templateId", "driverId", "host", "port", "serverName", "databaseName", "url", "properties", "template", "readOnly", "saveCredentials", "authModelId", "credentials", "providerProperties", "networkHandlersConfig", "dataSourceId", "userName", "userPassword", "folder"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "connectionId": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - it.ConnectionID, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "name": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - it.Name, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "description": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - it.Description, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "templateId": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("templateId")) - it.TemplateID, err = ec.unmarshalOID2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "driverId": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("driverId")) - it.DriverID, err = ec.unmarshalOID2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "host": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("host")) - it.Host, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "port": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("port")) - it.Port, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "serverName": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("serverName")) - it.ServerName, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "databaseName": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("databaseName")) - it.DatabaseName, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "url": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("url")) - it.URL, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "properties": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("properties")) - it.Properties, err = ec.unmarshalOObject2interface(ctx, v) - if err != nil { - return it, err - } - case "template": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("template")) - it.Template, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "readOnly": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("readOnly")) - it.ReadOnly, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "saveCredentials": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("saveCredentials")) - it.SaveCredentials, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "authModelId": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("authModelId")) - it.AuthModelID, err = ec.unmarshalOID2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "credentials": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("credentials")) - it.Credentials, err = ec.unmarshalOObject2interface(ctx, v) - if err != nil { - return it, err - } - case "providerProperties": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerProperties")) - it.ProviderProperties, err = ec.unmarshalOObject2interface(ctx, v) - if err != nil { - return it, err - } - case "networkHandlersConfig": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("networkHandlersConfig")) - it.NetworkHandlersConfig, err = ec.unmarshalONetworkHandlerConfigInput2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigInputᚄ(ctx, v) - if err != nil { - return it, err - } - case "dataSourceId": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataSourceId")) - it.DataSourceID, err = ec.unmarshalOID2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "userName": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userName")) - it.UserName, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "userPassword": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userPassword")) - it.UserPassword, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "folder": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folder")) - it.Folder, err = ec.unmarshalOID2ᚖstring(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputDataTransferParameters(ctx context.Context, obj interface{}) (model.DataTransferParameters, error) { - var it model.DataTransferParameters - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"processorId", "settings", "processorProperties", "filter"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "processorId": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("processorId")) - it.ProcessorID, err = ec.unmarshalNID2string(ctx, v) - if err != nil { - return it, err - } - case "settings": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("settings")) - it.Settings, err = ec.unmarshalOObject2interface(ctx, v) - if err != nil { - return it, err - } - case "processorProperties": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("processorProperties")) - it.ProcessorProperties, err = ec.unmarshalNObject2interface(ctx, v) - if err != nil { - return it, err - } - case "filter": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filter")) - it.Filter, err = ec.unmarshalOSQLDataFilter2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDataFilter(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputNavigatorSettingsInput(ctx context.Context, obj interface{}) (model.NavigatorSettingsInput, error) { - var it model.NavigatorSettingsInput - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"showSystemObjects", "showUtilityObjects", "showOnlyEntities", "mergeEntities", "hideFolders", "hideSchemas", "hideVirtualModel"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "showSystemObjects": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("showSystemObjects")) - it.ShowSystemObjects, err = ec.unmarshalNBoolean2bool(ctx, v) - if err != nil { - return it, err - } - case "showUtilityObjects": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("showUtilityObjects")) - it.ShowUtilityObjects, err = ec.unmarshalNBoolean2bool(ctx, v) - if err != nil { - return it, err - } - case "showOnlyEntities": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("showOnlyEntities")) - it.ShowOnlyEntities, err = ec.unmarshalNBoolean2bool(ctx, v) - if err != nil { - return it, err - } - case "mergeEntities": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("mergeEntities")) - it.MergeEntities, err = ec.unmarshalNBoolean2bool(ctx, v) - if err != nil { - return it, err - } - case "hideFolders": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hideFolders")) - it.HideFolders, err = ec.unmarshalNBoolean2bool(ctx, v) - if err != nil { - return it, err - } - case "hideSchemas": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hideSchemas")) - it.HideSchemas, err = ec.unmarshalNBoolean2bool(ctx, v) - if err != nil { - return it, err - } - case "hideVirtualModel": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hideVirtualModel")) - it.HideVirtualModel, err = ec.unmarshalNBoolean2bool(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputNetworkHandlerConfigInput(ctx context.Context, obj interface{}) (model.NetworkHandlerConfigInput, error) { - var it model.NetworkHandlerConfigInput - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"id", "enabled", "authType", "userName", "password", "key", "savePassword", "properties"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "id": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - it.ID, err = ec.unmarshalNID2string(ctx, v) - if err != nil { - return it, err - } - case "enabled": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabled")) - it.Enabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "authType": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("authType")) - it.AuthType, err = ec.unmarshalONetworkHandlerAuthType2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerAuthType(ctx, v) - if err != nil { - return it, err - } - case "userName": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userName")) - it.UserName, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "password": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("password")) - it.Password, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "key": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("key")) - it.Key, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "savePassword": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("savePassword")) - it.SavePassword, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "properties": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("properties")) - it.Properties, err = ec.unmarshalOObject2interface(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputObjectPropertyFilter(ctx context.Context, obj interface{}) (model.ObjectPropertyFilter, error) { - var it model.ObjectPropertyFilter - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"ids", "features", "categories", "dataTypes"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "ids": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("ids")) - it.Ids, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - case "features": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("features")) - it.Features, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - case "categories": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categories")) - it.Categories, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - case "dataTypes": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataTypes")) - it.DataTypes, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputSQLDataFilter(ctx context.Context, obj interface{}) (model.SQLDataFilter, error) { - var it model.SQLDataFilter - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"offset", "limit", "constraints", "where", "orderBy"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "offset": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("offset")) - it.Offset, err = ec.unmarshalOFloat2ᚖfloat64(ctx, v) - if err != nil { - return it, err - } - case "limit": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("limit")) - it.Limit, err = ec.unmarshalOInt2ᚖint(ctx, v) - if err != nil { - return it, err - } - case "constraints": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("constraints")) - it.Constraints, err = ec.unmarshalOSQLDataFilterConstraint2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDataFilterConstraint(ctx, v) - if err != nil { - return it, err - } - case "where": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) - it.Where, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "orderBy": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) - it.OrderBy, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputSQLDataFilterConstraint(ctx context.Context, obj interface{}) (model.SQLDataFilterConstraint, error) { - var it model.SQLDataFilterConstraint - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"attributePosition", "orderPosition", "orderAsc", "criteria", "operator", "value"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "attributePosition": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("attributePosition")) - it.AttributePosition, err = ec.unmarshalNInt2int(ctx, v) - if err != nil { - return it, err - } - case "orderPosition": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("orderPosition")) - it.OrderPosition, err = ec.unmarshalOInt2ᚖint(ctx, v) - if err != nil { - return it, err - } - case "orderAsc": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("orderAsc")) - it.OrderAsc, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "criteria": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("criteria")) - it.Criteria, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "operator": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("operator")) - it.Operator, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "value": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("value")) - it.Value, err = ec.unmarshalOObject2interface(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputSQLResultRow(ctx context.Context, obj interface{}) (model.SQLResultRow, error) { - var it model.SQLResultRow - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"data", "updateValues"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "data": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("data")) - it.Data, err = ec.unmarshalNObject2ᚕinterface(ctx, v) - if err != nil { - return it, err - } - case "updateValues": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("updateValues")) - it.UpdateValues, err = ec.unmarshalOObject2interface(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -func (ec *executionContext) unmarshalInputServerConfigInput(ctx context.Context, obj interface{}) (model.ServerConfigInput, error) { - var it model.ServerConfigInput - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - - fieldsInOrder := [...]string{"serverName", "serverURL", "adminName", "adminPassword", "anonymousAccessEnabled", "authenticationEnabled", "customConnectionsEnabled", "publicCredentialsSaveEnabled", "adminCredentialsSaveEnabled", "resourceManagerEnabled", "enabledFeatures", "enabledAuthProviders", "disabledDrivers", "sessionExpireTime"} - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - case "serverName": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("serverName")) - it.ServerName, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "serverURL": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("serverURL")) - it.ServerURL, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "adminName": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("adminName")) - it.AdminName, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "adminPassword": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("adminPassword")) - it.AdminPassword, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "anonymousAccessEnabled": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("anonymousAccessEnabled")) - it.AnonymousAccessEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "authenticationEnabled": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("authenticationEnabled")) - it.AuthenticationEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "customConnectionsEnabled": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("customConnectionsEnabled")) - it.CustomConnectionsEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "publicCredentialsSaveEnabled": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("publicCredentialsSaveEnabled")) - it.PublicCredentialsSaveEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "adminCredentialsSaveEnabled": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("adminCredentialsSaveEnabled")) - it.AdminCredentialsSaveEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "resourceManagerEnabled": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourceManagerEnabled")) - it.ResourceManagerEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) - if err != nil { - return it, err - } - case "enabledFeatures": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabledFeatures")) - it.EnabledFeatures, err = ec.unmarshalOID2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - case "enabledAuthProviders": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabledAuthProviders")) - it.EnabledAuthProviders, err = ec.unmarshalOID2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - case "disabledDrivers": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("disabledDrivers")) - it.DisabledDrivers, err = ec.unmarshalOID2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - case "sessionExpireTime": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("sessionExpireTime")) - it.SessionExpireTime, err = ec.unmarshalOInt2ᚖint(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - -// endregion **************************** input.gotpl ***************************** - -// region ************************** interface.gotpl *************************** - -// endregion ************************** interface.gotpl *************************** - -// region **************************** object.gotpl **************************** - -var adminAuthProviderConfigurationImplementors = []string{"AdminAuthProviderConfiguration"} - -func (ec *executionContext) _AdminAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, obj *model.AdminAuthProviderConfiguration) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, adminAuthProviderConfigurationImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AdminAuthProviderConfiguration") - case "providerId": - - out.Values[i] = ec._AdminAuthProviderConfiguration_providerId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "id": - - out.Values[i] = ec._AdminAuthProviderConfiguration_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "displayName": - - out.Values[i] = ec._AdminAuthProviderConfiguration_displayName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "disabled": - - out.Values[i] = ec._AdminAuthProviderConfiguration_disabled(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "iconURL": - - out.Values[i] = ec._AdminAuthProviderConfiguration_iconURL(ctx, field, obj) - - case "description": - - out.Values[i] = ec._AdminAuthProviderConfiguration_description(ctx, field, obj) - - case "parameters": - - out.Values[i] = ec._AdminAuthProviderConfiguration_parameters(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "signInLink": - - out.Values[i] = ec._AdminAuthProviderConfiguration_signInLink(ctx, field, obj) - - case "signOutLink": - - out.Values[i] = ec._AdminAuthProviderConfiguration_signOutLink(ctx, field, obj) - - case "redirectLink": - - out.Values[i] = ec._AdminAuthProviderConfiguration_redirectLink(ctx, field, obj) - - case "metadataLink": - - out.Values[i] = ec._AdminAuthProviderConfiguration_metadataLink(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var adminConnectionGrantInfoImplementors = []string{"AdminConnectionGrantInfo"} - -func (ec *executionContext) _AdminConnectionGrantInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminConnectionGrantInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, adminConnectionGrantInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AdminConnectionGrantInfo") - case "connectionId": - - out.Values[i] = ec._AdminConnectionGrantInfo_connectionId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "dataSourceId": - - out.Values[i] = ec._AdminConnectionGrantInfo_dataSourceId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "subjectId": - - out.Values[i] = ec._AdminConnectionGrantInfo_subjectId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "subjectType": - - out.Values[i] = ec._AdminConnectionGrantInfo_subjectType(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var adminConnectionSearchInfoImplementors = []string{"AdminConnectionSearchInfo"} - -func (ec *executionContext) _AdminConnectionSearchInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminConnectionSearchInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, adminConnectionSearchInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AdminConnectionSearchInfo") - case "displayName": - - out.Values[i] = ec._AdminConnectionSearchInfo_displayName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "host": - - out.Values[i] = ec._AdminConnectionSearchInfo_host(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "port": - - out.Values[i] = ec._AdminConnectionSearchInfo_port(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "possibleDrivers": - - out.Values[i] = ec._AdminConnectionSearchInfo_possibleDrivers(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "defaultDriver": - - out.Values[i] = ec._AdminConnectionSearchInfo_defaultDriver(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var adminPermissionInfoImplementors = []string{"AdminPermissionInfo"} - -func (ec *executionContext) _AdminPermissionInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminPermissionInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, adminPermissionInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AdminPermissionInfo") - case "id": - - out.Values[i] = ec._AdminPermissionInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "label": - - out.Values[i] = ec._AdminPermissionInfo_label(ctx, field, obj) - - case "description": - - out.Values[i] = ec._AdminPermissionInfo_description(ctx, field, obj) - - case "provider": - - out.Values[i] = ec._AdminPermissionInfo_provider(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "category": - - out.Values[i] = ec._AdminPermissionInfo_category(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var adminRoleInfoImplementors = []string{"AdminRoleInfo"} - -func (ec *executionContext) _AdminRoleInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminRoleInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, adminRoleInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AdminRoleInfo") - case "roleId": - - out.Values[i] = ec._AdminRoleInfo_roleId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "roleName": - - out.Values[i] = ec._AdminRoleInfo_roleName(ctx, field, obj) - - case "description": - - out.Values[i] = ec._AdminRoleInfo_description(ctx, field, obj) - - case "grantedUsers": - - out.Values[i] = ec._AdminRoleInfo_grantedUsers(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "grantedConnections": - - out.Values[i] = ec._AdminRoleInfo_grantedConnections(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "rolePermissions": - - out.Values[i] = ec._AdminRoleInfo_rolePermissions(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var adminUserInfoImplementors = []string{"AdminUserInfo"} - -func (ec *executionContext) _AdminUserInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminUserInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, adminUserInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AdminUserInfo") - case "userId": - - out.Values[i] = ec._AdminUserInfo_userId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "metaParameters": - - out.Values[i] = ec._AdminUserInfo_metaParameters(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "configurationParameters": - - out.Values[i] = ec._AdminUserInfo_configurationParameters(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "grantedRoles": - - out.Values[i] = ec._AdminUserInfo_grantedRoles(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "grantedConnections": - - out.Values[i] = ec._AdminUserInfo_grantedConnections(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "origins": - - out.Values[i] = ec._AdminUserInfo_origins(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "linkedAuthProviders": - - out.Values[i] = ec._AdminUserInfo_linkedAuthProviders(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "enabled": - - out.Values[i] = ec._AdminUserInfo_enabled(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var asyncTaskInfoImplementors = []string{"AsyncTaskInfo"} - -func (ec *executionContext) _AsyncTaskInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AsyncTaskInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, asyncTaskInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AsyncTaskInfo") - case "id": - - out.Values[i] = ec._AsyncTaskInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._AsyncTaskInfo_name(ctx, field, obj) - - case "running": - - out.Values[i] = ec._AsyncTaskInfo_running(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "status": - - out.Values[i] = ec._AsyncTaskInfo_status(ctx, field, obj) - - case "error": - - out.Values[i] = ec._AsyncTaskInfo_error(ctx, field, obj) - - case "result": - - out.Values[i] = ec._AsyncTaskInfo_result(ctx, field, obj) - - case "taskResult": - - out.Values[i] = ec._AsyncTaskInfo_taskResult(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var authCredentialInfoImplementors = []string{"AuthCredentialInfo"} - -func (ec *executionContext) _AuthCredentialInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AuthCredentialInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, authCredentialInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AuthCredentialInfo") - case "id": - - out.Values[i] = ec._AuthCredentialInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "displayName": - - out.Values[i] = ec._AuthCredentialInfo_displayName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._AuthCredentialInfo_description(ctx, field, obj) - - case "admin": - - out.Values[i] = ec._AuthCredentialInfo_admin(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "user": - - out.Values[i] = ec._AuthCredentialInfo_user(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "identifying": - - out.Values[i] = ec._AuthCredentialInfo_identifying(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "possibleValues": - - out.Values[i] = ec._AuthCredentialInfo_possibleValues(ctx, field, obj) - - case "encryption": - - out.Values[i] = ec._AuthCredentialInfo_encryption(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var authInfoImplementors = []string{"AuthInfo"} - -func (ec *executionContext) _AuthInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AuthInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, authInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AuthInfo") - case "redirectLink": - - out.Values[i] = ec._AuthInfo_redirectLink(ctx, field, obj) - - case "authId": - - out.Values[i] = ec._AuthInfo_authId(ctx, field, obj) - - case "authStatus": - - out.Values[i] = ec._AuthInfo_authStatus(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "userTokens": - - out.Values[i] = ec._AuthInfo_userTokens(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var authProviderConfigurationImplementors = []string{"AuthProviderConfiguration"} - -func (ec *executionContext) _AuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, obj *model.AuthProviderConfiguration) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, authProviderConfigurationImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AuthProviderConfiguration") - case "id": - - out.Values[i] = ec._AuthProviderConfiguration_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "displayName": - - out.Values[i] = ec._AuthProviderConfiguration_displayName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "disabled": - - out.Values[i] = ec._AuthProviderConfiguration_disabled(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "iconURL": - - out.Values[i] = ec._AuthProviderConfiguration_iconURL(ctx, field, obj) - - case "description": - - out.Values[i] = ec._AuthProviderConfiguration_description(ctx, field, obj) - - case "signInLink": - - out.Values[i] = ec._AuthProviderConfiguration_signInLink(ctx, field, obj) - - case "signOutLink": - - out.Values[i] = ec._AuthProviderConfiguration_signOutLink(ctx, field, obj) - - case "metadataLink": - - out.Values[i] = ec._AuthProviderConfiguration_metadataLink(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var authProviderCredentialsProfileImplementors = []string{"AuthProviderCredentialsProfile"} - -func (ec *executionContext) _AuthProviderCredentialsProfile(ctx context.Context, sel ast.SelectionSet, obj *model.AuthProviderCredentialsProfile) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, authProviderCredentialsProfileImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AuthProviderCredentialsProfile") - case "id": - - out.Values[i] = ec._AuthProviderCredentialsProfile_id(ctx, field, obj) - - case "label": - - out.Values[i] = ec._AuthProviderCredentialsProfile_label(ctx, field, obj) - - case "description": - - out.Values[i] = ec._AuthProviderCredentialsProfile_description(ctx, field, obj) - - case "credentialParameters": - - out.Values[i] = ec._AuthProviderCredentialsProfile_credentialParameters(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var authProviderInfoImplementors = []string{"AuthProviderInfo"} - -func (ec *executionContext) _AuthProviderInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AuthProviderInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, authProviderInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("AuthProviderInfo") - case "id": - - out.Values[i] = ec._AuthProviderInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "label": - - out.Values[i] = ec._AuthProviderInfo_label(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "icon": - - out.Values[i] = ec._AuthProviderInfo_icon(ctx, field, obj) - - case "description": - - out.Values[i] = ec._AuthProviderInfo_description(ctx, field, obj) - - case "defaultProvider": - - out.Values[i] = ec._AuthProviderInfo_defaultProvider(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "configurable": - - out.Values[i] = ec._AuthProviderInfo_configurable(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "configurations": - - out.Values[i] = ec._AuthProviderInfo_configurations(ctx, field, obj) - - case "credentialProfiles": - - out.Values[i] = ec._AuthProviderInfo_credentialProfiles(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "requiredFeatures": - - out.Values[i] = ec._AuthProviderInfo_requiredFeatures(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var connectionFolderInfoImplementors = []string{"ConnectionFolderInfo"} - -func (ec *executionContext) _ConnectionFolderInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ConnectionFolderInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, connectionFolderInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ConnectionFolderInfo") - case "id": - - out.Values[i] = ec._ConnectionFolderInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._ConnectionFolderInfo_description(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var connectionInfoImplementors = []string{"ConnectionInfo"} - -func (ec *executionContext) _ConnectionInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ConnectionInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, connectionInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ConnectionInfo") - case "id": - - out.Values[i] = ec._ConnectionInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "driverId": - - out.Values[i] = ec._ConnectionInfo_driverId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._ConnectionInfo_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._ConnectionInfo_description(ctx, field, obj) - - case "host": - - out.Values[i] = ec._ConnectionInfo_host(ctx, field, obj) - - case "port": - - out.Values[i] = ec._ConnectionInfo_port(ctx, field, obj) - - case "serverName": - - out.Values[i] = ec._ConnectionInfo_serverName(ctx, field, obj) - - case "databaseName": - - out.Values[i] = ec._ConnectionInfo_databaseName(ctx, field, obj) - - case "url": - - out.Values[i] = ec._ConnectionInfo_url(ctx, field, obj) - - case "properties": - - out.Values[i] = ec._ConnectionInfo_properties(ctx, field, obj) - - case "template": - - out.Values[i] = ec._ConnectionInfo_template(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "connected": - - out.Values[i] = ec._ConnectionInfo_connected(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "provided": - - out.Values[i] = ec._ConnectionInfo_provided(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "readOnly": - - out.Values[i] = ec._ConnectionInfo_readOnly(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "useUrl": - - out.Values[i] = ec._ConnectionInfo_useUrl(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "saveCredentials": - - out.Values[i] = ec._ConnectionInfo_saveCredentials(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "folder": - - out.Values[i] = ec._ConnectionInfo_folder(ctx, field, obj) - - case "nodePath": - - out.Values[i] = ec._ConnectionInfo_nodePath(ctx, field, obj) - - case "connectTime": - - out.Values[i] = ec._ConnectionInfo_connectTime(ctx, field, obj) - - case "connectionError": - - out.Values[i] = ec._ConnectionInfo_connectionError(ctx, field, obj) - - case "serverVersion": - - out.Values[i] = ec._ConnectionInfo_serverVersion(ctx, field, obj) - - case "clientVersion": - - out.Values[i] = ec._ConnectionInfo_clientVersion(ctx, field, obj) - - case "origin": - - out.Values[i] = ec._ConnectionInfo_origin(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "authNeeded": - - out.Values[i] = ec._ConnectionInfo_authNeeded(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "authModel": - - out.Values[i] = ec._ConnectionInfo_authModel(ctx, field, obj) - - case "authProperties": - - out.Values[i] = ec._ConnectionInfo_authProperties(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "providerProperties": - - out.Values[i] = ec._ConnectionInfo_providerProperties(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "networkHandlersConfig": - - out.Values[i] = ec._ConnectionInfo_networkHandlersConfig(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "features": - - out.Values[i] = ec._ConnectionInfo_features(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "navigatorSettings": - - out.Values[i] = ec._ConnectionInfo_navigatorSettings(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "supportedDataFormats": - - out.Values[i] = ec._ConnectionInfo_supportedDataFormats(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var dataTransferProcessorInfoImplementors = []string{"DataTransferProcessorInfo"} - -func (ec *executionContext) _DataTransferProcessorInfo(ctx context.Context, sel ast.SelectionSet, obj *model.DataTransferProcessorInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, dataTransferProcessorInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("DataTransferProcessorInfo") - case "id": - - out.Values[i] = ec._DataTransferProcessorInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._DataTransferProcessorInfo_name(ctx, field, obj) - - case "description": - - out.Values[i] = ec._DataTransferProcessorInfo_description(ctx, field, obj) - - case "fileExtension": - - out.Values[i] = ec._DataTransferProcessorInfo_fileExtension(ctx, field, obj) - - case "appFileExtension": - - out.Values[i] = ec._DataTransferProcessorInfo_appFileExtension(ctx, field, obj) - - case "appName": - - out.Values[i] = ec._DataTransferProcessorInfo_appName(ctx, field, obj) - - case "order": - - out.Values[i] = ec._DataTransferProcessorInfo_order(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "icon": - - out.Values[i] = ec._DataTransferProcessorInfo_icon(ctx, field, obj) - - case "properties": - - out.Values[i] = ec._DataTransferProcessorInfo_properties(ctx, field, obj) - - case "isBinary": - - out.Values[i] = ec._DataTransferProcessorInfo_isBinary(ctx, field, obj) - - case "isHTML": - - out.Values[i] = ec._DataTransferProcessorInfo_isHTML(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var dataTypeLogicalOperationImplementors = []string{"DataTypeLogicalOperation"} - -func (ec *executionContext) _DataTypeLogicalOperation(ctx context.Context, sel ast.SelectionSet, obj *model.DataTypeLogicalOperation) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, dataTypeLogicalOperationImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("DataTypeLogicalOperation") - case "id": - - out.Values[i] = ec._DataTypeLogicalOperation_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "expression": - - out.Values[i] = ec._DataTypeLogicalOperation_expression(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "argumentCount": - - out.Values[i] = ec._DataTypeLogicalOperation_argumentCount(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var databaseAuthModelImplementors = []string{"DatabaseAuthModel"} - -func (ec *executionContext) _DatabaseAuthModel(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseAuthModel) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, databaseAuthModelImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("DatabaseAuthModel") - case "id": - - out.Values[i] = ec._DatabaseAuthModel_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "displayName": - - out.Values[i] = ec._DatabaseAuthModel_displayName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._DatabaseAuthModel_description(ctx, field, obj) - - case "icon": - - out.Values[i] = ec._DatabaseAuthModel_icon(ctx, field, obj) - - case "requiresLocalConfiguration": - - out.Values[i] = ec._DatabaseAuthModel_requiresLocalConfiguration(ctx, field, obj) - - case "properties": - - out.Values[i] = ec._DatabaseAuthModel_properties(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var databaseCatalogImplementors = []string{"DatabaseCatalog"} - -func (ec *executionContext) _DatabaseCatalog(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseCatalog) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, databaseCatalogImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("DatabaseCatalog") - case "catalog": - - out.Values[i] = ec._DatabaseCatalog_catalog(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "schemaList": - - out.Values[i] = ec._DatabaseCatalog_schemaList(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var databaseDocumentImplementors = []string{"DatabaseDocument"} - -func (ec *executionContext) _DatabaseDocument(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseDocument) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, databaseDocumentImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("DatabaseDocument") - case "id": - - out.Values[i] = ec._DatabaseDocument_id(ctx, field, obj) - - case "contentType": - - out.Values[i] = ec._DatabaseDocument_contentType(ctx, field, obj) - - case "properties": - - out.Values[i] = ec._DatabaseDocument_properties(ctx, field, obj) - - case "data": - - out.Values[i] = ec._DatabaseDocument_data(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var databaseObjectInfoImplementors = []string{"DatabaseObjectInfo"} - -func (ec *executionContext) _DatabaseObjectInfo(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseObjectInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, databaseObjectInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("DatabaseObjectInfo") - case "name": - - out.Values[i] = ec._DatabaseObjectInfo_name(ctx, field, obj) - - case "description": - - out.Values[i] = ec._DatabaseObjectInfo_description(ctx, field, obj) - - case "type": - - out.Values[i] = ec._DatabaseObjectInfo_type(ctx, field, obj) - - case "properties": - - out.Values[i] = ec._DatabaseObjectInfo_properties(ctx, field, obj) - - case "ordinalPosition": - - out.Values[i] = ec._DatabaseObjectInfo_ordinalPosition(ctx, field, obj) - - case "fullyQualifiedName": - - out.Values[i] = ec._DatabaseObjectInfo_fullyQualifiedName(ctx, field, obj) - - case "overloadedName": - - out.Values[i] = ec._DatabaseObjectInfo_overloadedName(ctx, field, obj) - - case "uniqueName": - - out.Values[i] = ec._DatabaseObjectInfo_uniqueName(ctx, field, obj) - - case "state": - - out.Values[i] = ec._DatabaseObjectInfo_state(ctx, field, obj) - - case "features": - - out.Values[i] = ec._DatabaseObjectInfo_features(ctx, field, obj) - - case "editors": - - out.Values[i] = ec._DatabaseObjectInfo_editors(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var databaseStructContainersImplementors = []string{"DatabaseStructContainers"} - -func (ec *executionContext) _DatabaseStructContainers(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseStructContainers) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, databaseStructContainersImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("DatabaseStructContainers") - case "catalogList": - - out.Values[i] = ec._DatabaseStructContainers_catalogList(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "schemaList": - - out.Values[i] = ec._DatabaseStructContainers_schemaList(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "supportsCatalogChange": - - out.Values[i] = ec._DatabaseStructContainers_supportsCatalogChange(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "supportsSchemaChange": - - out.Values[i] = ec._DatabaseStructContainers_supportsSchemaChange(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var driverInfoImplementors = []string{"DriverInfo"} - -func (ec *executionContext) _DriverInfo(ctx context.Context, sel ast.SelectionSet, obj *model.DriverInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, driverInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("DriverInfo") - case "id": - - out.Values[i] = ec._DriverInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._DriverInfo_name(ctx, field, obj) - - case "description": - - out.Values[i] = ec._DriverInfo_description(ctx, field, obj) - - case "icon": - - out.Values[i] = ec._DriverInfo_icon(ctx, field, obj) - - case "iconBig": - - out.Values[i] = ec._DriverInfo_iconBig(ctx, field, obj) - - case "providerId": - - out.Values[i] = ec._DriverInfo_providerId(ctx, field, obj) - - case "driverClassName": - - out.Values[i] = ec._DriverInfo_driverClassName(ctx, field, obj) - - case "defaultHost": - - out.Values[i] = ec._DriverInfo_defaultHost(ctx, field, obj) - - case "defaultPort": - - out.Values[i] = ec._DriverInfo_defaultPort(ctx, field, obj) - - case "defaultDatabase": - - out.Values[i] = ec._DriverInfo_defaultDatabase(ctx, field, obj) - - case "defaultServer": - - out.Values[i] = ec._DriverInfo_defaultServer(ctx, field, obj) - - case "defaultUser": - - out.Values[i] = ec._DriverInfo_defaultUser(ctx, field, obj) - - case "sampleURL": - - out.Values[i] = ec._DriverInfo_sampleURL(ctx, field, obj) - - case "driverInfoURL": - - out.Values[i] = ec._DriverInfo_driverInfoURL(ctx, field, obj) - - case "driverPropertiesURL": - - out.Values[i] = ec._DriverInfo_driverPropertiesURL(ctx, field, obj) - - case "embedded": - - out.Values[i] = ec._DriverInfo_embedded(ctx, field, obj) - - case "enabled": - - out.Values[i] = ec._DriverInfo_enabled(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "requiresServerName": - - out.Values[i] = ec._DriverInfo_requiresServerName(ctx, field, obj) - - case "allowsEmptyPassword": - - out.Values[i] = ec._DriverInfo_allowsEmptyPassword(ctx, field, obj) - - case "licenseRequired": - - out.Values[i] = ec._DriverInfo_licenseRequired(ctx, field, obj) - - case "license": - - out.Values[i] = ec._DriverInfo_license(ctx, field, obj) - - case "custom": - - out.Values[i] = ec._DriverInfo_custom(ctx, field, obj) - - case "promotedScore": - - out.Values[i] = ec._DriverInfo_promotedScore(ctx, field, obj) - - case "driverProperties": - - out.Values[i] = ec._DriverInfo_driverProperties(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "driverParameters": - - out.Values[i] = ec._DriverInfo_driverParameters(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "providerProperties": - - out.Values[i] = ec._DriverInfo_providerProperties(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "anonymousAccess": - - out.Values[i] = ec._DriverInfo_anonymousAccess(ctx, field, obj) - - case "defaultAuthModel": - - out.Values[i] = ec._DriverInfo_defaultAuthModel(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "applicableAuthModels": - - out.Values[i] = ec._DriverInfo_applicableAuthModels(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "applicableNetworkHandlers": - - out.Values[i] = ec._DriverInfo_applicableNetworkHandlers(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var logEntryImplementors = []string{"LogEntry"} - -func (ec *executionContext) _LogEntry(ctx context.Context, sel ast.SelectionSet, obj *model.LogEntry) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, logEntryImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("LogEntry") - case "time": - - out.Values[i] = ec._LogEntry_time(ctx, field, obj) - - case "type": - - out.Values[i] = ec._LogEntry_type(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "message": - - out.Values[i] = ec._LogEntry_message(ctx, field, obj) - - case "stackTrace": - - out.Values[i] = ec._LogEntry_stackTrace(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var mutationImplementors = []string{"Mutation"} - -func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, mutationImplementors) - ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ - Object: "Mutation", - }) - - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ - Object: field.Name, - Field: field, - }) - - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Mutation") - case "setUserConfigurationParameter": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_setUserConfigurationParameter(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "openSession": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_openSession(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "closeSession": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_closeSession(ctx, field) - }) - - case "touchSession": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_touchSession(ctx, field) - }) - - case "refreshSessionConnections": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_refreshSessionConnections(ctx, field) - }) - - case "changeSessionLanguage": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_changeSessionLanguage(ctx, field) - }) - - case "createConnection": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_createConnection(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "updateConnection": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_updateConnection(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "deleteConnection": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_deleteConnection(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "createConnectionFromTemplate": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_createConnectionFromTemplate(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "createConnectionFolder": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_createConnectionFolder(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "deleteConnectionFolder": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_deleteConnectionFolder(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "copyConnectionFromNode": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_copyConnectionFromNode(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "testConnection": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_testConnection(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "testNetworkHandler": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_testNetworkHandler(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "initConnection": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_initConnection(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "closeConnection": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_closeConnection(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "setConnectionNavigatorSettings": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_setConnectionNavigatorSettings(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "asyncTaskCancel": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncTaskCancel(ctx, field) - }) - - case "asyncTaskInfo": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncTaskInfo(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "openConnection": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_openConnection(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "asyncTaskStatus": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncTaskStatus(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "navRenameNode": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_navRenameNode(ctx, field) - }) - - case "navDeleteNodes": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_navDeleteNodes(ctx, field) - }) - - case "navMoveNodesToFolder": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_navMoveNodesToFolder(ctx, field) - }) - - case "rmCreateResource": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_rmCreateResource(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "rmMoveResource": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_rmMoveResource(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "rmDeleteResource": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_rmDeleteResource(ctx, field) - }) - - case "rmWriteResourceStringContent": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_rmWriteResourceStringContent(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "sqlContextCreate": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_sqlContextCreate(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "sqlContextSetDefaults": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_sqlContextSetDefaults(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "sqlContextDestroy": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_sqlContextDestroy(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "asyncSqlExecuteQuery": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncSqlExecuteQuery(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "asyncReadDataFromContainer": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncReadDataFromContainer(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "sqlResultClose": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_sqlResultClose(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "updateResultsDataBatch": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_updateResultsDataBatch(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "updateResultsDataBatchScript": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_updateResultsDataBatchScript(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "readLobValue": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_readLobValue(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "asyncSqlExecuteResults": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncSqlExecuteResults(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "asyncSqlExplainExecutionPlan": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncSqlExplainExecutionPlan(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "asyncSqlExplainExecutionPlanResult": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncSqlExplainExecutionPlanResult(ctx, field) - }) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var navigatorNodeInfoImplementors = []string{"NavigatorNodeInfo"} - -func (ec *executionContext) _NavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, obj *model.NavigatorNodeInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, navigatorNodeInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("NavigatorNodeInfo") - case "id": - - out.Values[i] = ec._NavigatorNodeInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._NavigatorNodeInfo_name(ctx, field, obj) - - case "fullName": - - out.Values[i] = ec._NavigatorNodeInfo_fullName(ctx, field, obj) - - case "icon": - - out.Values[i] = ec._NavigatorNodeInfo_icon(ctx, field, obj) - - case "description": - - out.Values[i] = ec._NavigatorNodeInfo_description(ctx, field, obj) - - case "nodeType": - - out.Values[i] = ec._NavigatorNodeInfo_nodeType(ctx, field, obj) - - case "hasChildren": - - out.Values[i] = ec._NavigatorNodeInfo_hasChildren(ctx, field, obj) - - case "object": - - out.Values[i] = ec._NavigatorNodeInfo_object(ctx, field, obj) - - case "features": - - out.Values[i] = ec._NavigatorNodeInfo_features(ctx, field, obj) - - case "nodeDetails": - - out.Values[i] = ec._NavigatorNodeInfo_nodeDetails(ctx, field, obj) - - case "folder": - - out.Values[i] = ec._NavigatorNodeInfo_folder(ctx, field, obj) - - case "inline": - - out.Values[i] = ec._NavigatorNodeInfo_inline(ctx, field, obj) - - case "navigable": - - out.Values[i] = ec._NavigatorNodeInfo_navigable(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var navigatorSettingsImplementors = []string{"NavigatorSettings"} - -func (ec *executionContext) _NavigatorSettings(ctx context.Context, sel ast.SelectionSet, obj *model.NavigatorSettings) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, navigatorSettingsImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("NavigatorSettings") - case "showSystemObjects": - - out.Values[i] = ec._NavigatorSettings_showSystemObjects(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "showUtilityObjects": - - out.Values[i] = ec._NavigatorSettings_showUtilityObjects(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "showOnlyEntities": - - out.Values[i] = ec._NavigatorSettings_showOnlyEntities(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "mergeEntities": - - out.Values[i] = ec._NavigatorSettings_mergeEntities(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "hideFolders": - - out.Values[i] = ec._NavigatorSettings_hideFolders(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "hideSchemas": - - out.Values[i] = ec._NavigatorSettings_hideSchemas(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "hideVirtualModel": - - out.Values[i] = ec._NavigatorSettings_hideVirtualModel(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var networkEndpointInfoImplementors = []string{"NetworkEndpointInfo"} - -func (ec *executionContext) _NetworkEndpointInfo(ctx context.Context, sel ast.SelectionSet, obj *model.NetworkEndpointInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, networkEndpointInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("NetworkEndpointInfo") - case "message": - - out.Values[i] = ec._NetworkEndpointInfo_message(ctx, field, obj) - - case "clientVersion": - - out.Values[i] = ec._NetworkEndpointInfo_clientVersion(ctx, field, obj) - - case "serverVersion": - - out.Values[i] = ec._NetworkEndpointInfo_serverVersion(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var networkHandlerConfigImplementors = []string{"NetworkHandlerConfig"} - -func (ec *executionContext) _NetworkHandlerConfig(ctx context.Context, sel ast.SelectionSet, obj *model.NetworkHandlerConfig) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, networkHandlerConfigImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("NetworkHandlerConfig") - case "id": - - out.Values[i] = ec._NetworkHandlerConfig_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "enabled": - - out.Values[i] = ec._NetworkHandlerConfig_enabled(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "authType": - - out.Values[i] = ec._NetworkHandlerConfig_authType(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "userName": - - out.Values[i] = ec._NetworkHandlerConfig_userName(ctx, field, obj) - - case "password": - - out.Values[i] = ec._NetworkHandlerConfig_password(ctx, field, obj) - - case "key": - - out.Values[i] = ec._NetworkHandlerConfig_key(ctx, field, obj) - - case "savePassword": - - out.Values[i] = ec._NetworkHandlerConfig_savePassword(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "properties": - - out.Values[i] = ec._NetworkHandlerConfig_properties(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var networkHandlerDescriptorImplementors = []string{"NetworkHandlerDescriptor"} - -func (ec *executionContext) _NetworkHandlerDescriptor(ctx context.Context, sel ast.SelectionSet, obj *model.NetworkHandlerDescriptor) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, networkHandlerDescriptorImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("NetworkHandlerDescriptor") - case "id": - - out.Values[i] = ec._NetworkHandlerDescriptor_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "codeName": - - out.Values[i] = ec._NetworkHandlerDescriptor_codeName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "label": - - out.Values[i] = ec._NetworkHandlerDescriptor_label(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._NetworkHandlerDescriptor_description(ctx, field, obj) - - case "secured": - - out.Values[i] = ec._NetworkHandlerDescriptor_secured(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "type": - - out.Values[i] = ec._NetworkHandlerDescriptor_type(ctx, field, obj) - - case "properties": - - out.Values[i] = ec._NetworkHandlerDescriptor_properties(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var objectDescriptorImplementors = []string{"ObjectDescriptor"} - -func (ec *executionContext) _ObjectDescriptor(ctx context.Context, sel ast.SelectionSet, obj *model.ObjectDescriptor) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, objectDescriptorImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ObjectDescriptor") - case "id": - - out.Values[i] = ec._ObjectDescriptor_id(ctx, field, obj) - - case "displayName": - - out.Values[i] = ec._ObjectDescriptor_displayName(ctx, field, obj) - - case "fullName": - - out.Values[i] = ec._ObjectDescriptor_fullName(ctx, field, obj) - - case "uniqueName": - - out.Values[i] = ec._ObjectDescriptor_uniqueName(ctx, field, obj) - - case "description": - - out.Values[i] = ec._ObjectDescriptor_description(ctx, field, obj) - - case "value": - - out.Values[i] = ec._ObjectDescriptor_value(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var objectDetailsImplementors = []string{"ObjectDetails"} - -func (ec *executionContext) _ObjectDetails(ctx context.Context, sel ast.SelectionSet, obj *model.ObjectDetails) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, objectDetailsImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ObjectDetails") - case "id": - - out.Values[i] = ec._ObjectDetails_id(ctx, field, obj) - - case "displayName": - - out.Values[i] = ec._ObjectDetails_displayName(ctx, field, obj) - - case "description": - - out.Values[i] = ec._ObjectDetails_description(ctx, field, obj) - - case "value": - - out.Values[i] = ec._ObjectDetails_value(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var objectOriginImplementors = []string{"ObjectOrigin"} - -func (ec *executionContext) _ObjectOrigin(ctx context.Context, sel ast.SelectionSet, obj *model.ObjectOrigin) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, objectOriginImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ObjectOrigin") - case "type": - - out.Values[i] = ec._ObjectOrigin_type(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "subType": - - out.Values[i] = ec._ObjectOrigin_subType(ctx, field, obj) - - case "displayName": - - out.Values[i] = ec._ObjectOrigin_displayName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "icon": - - out.Values[i] = ec._ObjectOrigin_icon(ctx, field, obj) - - case "configuration": - - out.Values[i] = ec._ObjectOrigin_configuration(ctx, field, obj) - - case "details": - - out.Values[i] = ec._ObjectOrigin_details(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var objectPropertyInfoImplementors = []string{"ObjectPropertyInfo"} - -func (ec *executionContext) _ObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ObjectPropertyInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, objectPropertyInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ObjectPropertyInfo") - case "id": - - out.Values[i] = ec._ObjectPropertyInfo_id(ctx, field, obj) - - case "displayName": - - out.Values[i] = ec._ObjectPropertyInfo_displayName(ctx, field, obj) - - case "description": - - out.Values[i] = ec._ObjectPropertyInfo_description(ctx, field, obj) - - case "category": - - out.Values[i] = ec._ObjectPropertyInfo_category(ctx, field, obj) - - case "dataType": - - out.Values[i] = ec._ObjectPropertyInfo_dataType(ctx, field, obj) - - case "value": - - out.Values[i] = ec._ObjectPropertyInfo_value(ctx, field, obj) - - case "validValues": - - out.Values[i] = ec._ObjectPropertyInfo_validValues(ctx, field, obj) - - case "defaultValue": - - out.Values[i] = ec._ObjectPropertyInfo_defaultValue(ctx, field, obj) - - case "length": - - out.Values[i] = ec._ObjectPropertyInfo_length(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "features": - - out.Values[i] = ec._ObjectPropertyInfo_features(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "order": - - out.Values[i] = ec._ObjectPropertyInfo_order(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var productInfoImplementors = []string{"ProductInfo"} - -func (ec *executionContext) _ProductInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ProductInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, productInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ProductInfo") - case "id": - - out.Values[i] = ec._ProductInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "version": - - out.Values[i] = ec._ProductInfo_version(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._ProductInfo_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._ProductInfo_description(ctx, field, obj) - - case "buildTime": - - out.Values[i] = ec._ProductInfo_buildTime(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "releaseTime": - - out.Values[i] = ec._ProductInfo_releaseTime(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "licenseInfo": - - out.Values[i] = ec._ProductInfo_licenseInfo(ctx, field, obj) - - case "latestVersionInfo": - - out.Values[i] = ec._ProductInfo_latestVersionInfo(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var queryImplementors = []string{"Query"} - -func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, queryImplementors) - ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ - Object: "Query", - }) - - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ - Object: field.Name, - Field: field, - }) - - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Query") - case "listUsers": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_listUsers(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listRoles": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_listRoles(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listPermissions": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_listPermissions(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "createUser": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_createUser(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteUser": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_deleteUser(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "createRole": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_createRole(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "updateRole": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_updateRole(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteRole": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_deleteRole(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "grantUserRole": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_grantUserRole(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "revokeUserRole": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_revokeUserRole(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setSubjectPermissions": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_setSubjectPermissions(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setUserCredentials": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_setUserCredentials(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "enableUser": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_enableUser(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "allConnections": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_allConnections(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "searchConnections": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_searchConnections(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "createConnectionConfiguration": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_createConnectionConfiguration(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "copyConnectionConfiguration": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_copyConnectionConfiguration(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "updateConnectionConfiguration": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_updateConnectionConfiguration(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteConnectionConfiguration": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_deleteConnectionConfiguration(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "getConnectionSubjectAccess": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_getConnectionSubjectAccess(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setConnectionSubjectAccess": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_setConnectionSubjectAccess(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "getSubjectConnectionAccess": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_getSubjectConnectionAccess(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setSubjectConnectionAccess": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_setSubjectConnectionAccess(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listFeatureSets": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_listFeatureSets(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listAuthProviderConfigurationParameters": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_listAuthProviderConfigurationParameters(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listAuthProviderConfigurations": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_listAuthProviderConfigurations(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "saveAuthProviderConfiguration": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_saveAuthProviderConfiguration(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteAuthProviderConfiguration": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_deleteAuthProviderConfiguration(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "saveUserMetaParameter": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_saveUserMetaParameter(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteUserMetaParameter": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_deleteUserMetaParameter(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setUserMetaParameterValues": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_setUserMetaParameterValues(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "configureServer": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_configureServer(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setDefaultNavigatorSettings": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_setDefaultNavigatorSettings(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authLogin": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_authLogin(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authUpdateStatus": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_authUpdateStatus(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authLogout": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_authLogout(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "activeUser": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_activeUser(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authProviders": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_authProviders(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authChangeLocalPassword": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_authChangeLocalPassword(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listUserProfileProperties": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_listUserProfileProperties(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "serverConfig": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_serverConfig(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sessionState": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sessionState(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sessionPermissions": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sessionPermissions(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "driverList": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_driverList(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authModels": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_authModels(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "networkHandlers": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_networkHandlers(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "userConnections": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_userConnections(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "templateConnections": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_templateConnections(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "connectionFolders": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_connectionFolders(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "connectionState": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_connectionState(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "connectionInfo": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_connectionInfo(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "readSessionLog": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_readSessionLog(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "dataTransferAvailableStreamProcessors": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_dataTransferAvailableStreamProcessors(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "dataTransferExportDataFromContainer": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_dataTransferExportDataFromContainer(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "dataTransferExportDataFromResults": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_dataTransferExportDataFromResults(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "dataTransferRemoveDataFile": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_dataTransferRemoveDataFile(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "metadataGetNodeDDL": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_metadataGetNodeDDL(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navNodeChildren": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_navNodeChildren(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navNodeParents": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_navNodeParents(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navNodeInfo": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_navNodeInfo(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navRefreshNode": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_navRefreshNode(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navGetStructContainers": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_navGetStructContainers(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "rmListProjects": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_rmListProjects(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "rmListResources": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_rmListResources(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "rmReadResourceAsString": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_rmReadResourceAsString(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlDialectInfo": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlDialectInfo(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlListContexts": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlListContexts(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlCompletionProposals": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlCompletionProposals(ctx, field) - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlFormatQuery": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlFormatQuery(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlSupportedOperations": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlSupportedOperations(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlEntityQueryGenerators": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlEntityQueryGenerators(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlGenerateEntityQuery": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlGenerateEntityQuery(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlParseScript": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlParseScript(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sqlParseQuery": - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._Query_sqlParseQuery(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } - return res - } - - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "__type": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Query___type(ctx, field) - }) - - case "__schema": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Query___schema(ctx, field) - }) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var rMProjectImplementors = []string{"RMProject"} - -func (ec *executionContext) _RMProject(ctx context.Context, sel ast.SelectionSet, obj *model.RMProject) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, rMProjectImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("RMProject") - case "id": - - out.Values[i] = ec._RMProject_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._RMProject_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._RMProject_description(ctx, field, obj) - - case "shared": - - out.Values[i] = ec._RMProject_shared(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "createTime": - - out.Values[i] = ec._RMProject_createTime(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "creator": - - out.Values[i] = ec._RMProject_creator(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var rMResourceImplementors = []string{"RMResource"} - -func (ec *executionContext) _RMResource(ctx context.Context, sel ast.SelectionSet, obj *model.RMResource) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, rMResourceImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("RMResource") - case "name": - - out.Values[i] = ec._RMResource_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "folder": - - out.Values[i] = ec._RMResource_folder(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "length": - - out.Values[i] = ec._RMResource_length(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLCompletionProposalImplementors = []string{"SQLCompletionProposal"} - -func (ec *executionContext) _SQLCompletionProposal(ctx context.Context, sel ast.SelectionSet, obj *model.SQLCompletionProposal) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLCompletionProposalImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLCompletionProposal") - case "displayString": - - out.Values[i] = ec._SQLCompletionProposal_displayString(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "type": - - out.Values[i] = ec._SQLCompletionProposal_type(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "score": - - out.Values[i] = ec._SQLCompletionProposal_score(ctx, field, obj) - - case "replacementString": - - out.Values[i] = ec._SQLCompletionProposal_replacementString(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "replacementOffset": - - out.Values[i] = ec._SQLCompletionProposal_replacementOffset(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "replacementLength": - - out.Values[i] = ec._SQLCompletionProposal_replacementLength(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "cursorPosition": - - out.Values[i] = ec._SQLCompletionProposal_cursorPosition(ctx, field, obj) - - case "icon": - - out.Values[i] = ec._SQLCompletionProposal_icon(ctx, field, obj) - - case "nodePath": - - out.Values[i] = ec._SQLCompletionProposal_nodePath(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLContextInfoImplementors = []string{"SQLContextInfo"} - -func (ec *executionContext) _SQLContextInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SQLContextInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLContextInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLContextInfo") - case "id": - - out.Values[i] = ec._SQLContextInfo_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "connectionId": - - out.Values[i] = ec._SQLContextInfo_connectionId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "defaultCatalog": - - out.Values[i] = ec._SQLContextInfo_defaultCatalog(ctx, field, obj) - - case "defaultSchema": - - out.Values[i] = ec._SQLContextInfo_defaultSchema(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLDialectInfoImplementors = []string{"SQLDialectInfo"} - -func (ec *executionContext) _SQLDialectInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SQLDialectInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLDialectInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLDialectInfo") - case "name": - - out.Values[i] = ec._SQLDialectInfo_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "dataTypes": - - out.Values[i] = ec._SQLDialectInfo_dataTypes(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "functions": - - out.Values[i] = ec._SQLDialectInfo_functions(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "reservedWords": - - out.Values[i] = ec._SQLDialectInfo_reservedWords(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "quoteStrings": - - out.Values[i] = ec._SQLDialectInfo_quoteStrings(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "singleLineComments": - - out.Values[i] = ec._SQLDialectInfo_singleLineComments(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "multiLineComments": - - out.Values[i] = ec._SQLDialectInfo_multiLineComments(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "catalogSeparator": - - out.Values[i] = ec._SQLDialectInfo_catalogSeparator(ctx, field, obj) - - case "structSeparator": - - out.Values[i] = ec._SQLDialectInfo_structSeparator(ctx, field, obj) - - case "scriptDelimiter": - - out.Values[i] = ec._SQLDialectInfo_scriptDelimiter(ctx, field, obj) - - case "supportsExplainExecutionPlan": - - out.Values[i] = ec._SQLDialectInfo_supportsExplainExecutionPlan(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLExecuteInfoImplementors = []string{"SQLExecuteInfo"} - -func (ec *executionContext) _SQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SQLExecuteInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLExecuteInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLExecuteInfo") - case "statusMessage": - - out.Values[i] = ec._SQLExecuteInfo_statusMessage(ctx, field, obj) - - case "duration": - - out.Values[i] = ec._SQLExecuteInfo_duration(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "filterText": - - out.Values[i] = ec._SQLExecuteInfo_filterText(ctx, field, obj) - - case "results": - - out.Values[i] = ec._SQLExecuteInfo_results(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLExecutionPlanImplementors = []string{"SQLExecutionPlan"} - -func (ec *executionContext) _SQLExecutionPlan(ctx context.Context, sel ast.SelectionSet, obj *model.SQLExecutionPlan) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLExecutionPlanImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLExecutionPlan") - case "query": - - out.Values[i] = ec._SQLExecutionPlan_query(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "nodes": - - out.Values[i] = ec._SQLExecutionPlan_nodes(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLExecutionPlanNodeImplementors = []string{"SQLExecutionPlanNode"} - -func (ec *executionContext) _SQLExecutionPlanNode(ctx context.Context, sel ast.SelectionSet, obj *model.SQLExecutionPlanNode) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLExecutionPlanNodeImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLExecutionPlanNode") - case "id": - - out.Values[i] = ec._SQLExecutionPlanNode_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "parentId": - - out.Values[i] = ec._SQLExecutionPlanNode_parentId(ctx, field, obj) - - case "kind": - - out.Values[i] = ec._SQLExecutionPlanNode_kind(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._SQLExecutionPlanNode_name(ctx, field, obj) - - case "type": - - out.Values[i] = ec._SQLExecutionPlanNode_type(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "condition": - - out.Values[i] = ec._SQLExecutionPlanNode_condition(ctx, field, obj) - - case "description": - - out.Values[i] = ec._SQLExecutionPlanNode_description(ctx, field, obj) - - case "properties": - - out.Values[i] = ec._SQLExecutionPlanNode_properties(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLQueryGeneratorImplementors = []string{"SQLQueryGenerator"} - -func (ec *executionContext) _SQLQueryGenerator(ctx context.Context, sel ast.SelectionSet, obj *model.SQLQueryGenerator) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLQueryGeneratorImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLQueryGenerator") - case "id": - - out.Values[i] = ec._SQLQueryGenerator_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "label": - - out.Values[i] = ec._SQLQueryGenerator_label(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._SQLQueryGenerator_description(ctx, field, obj) - - case "order": - - out.Values[i] = ec._SQLQueryGenerator_order(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "multiObject": - - out.Values[i] = ec._SQLQueryGenerator_multiObject(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLQueryResultsImplementors = []string{"SQLQueryResults"} - -func (ec *executionContext) _SQLQueryResults(ctx context.Context, sel ast.SelectionSet, obj *model.SQLQueryResults) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLQueryResultsImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLQueryResults") - case "title": - - out.Values[i] = ec._SQLQueryResults_title(ctx, field, obj) - - case "updateRowCount": - - out.Values[i] = ec._SQLQueryResults_updateRowCount(ctx, field, obj) - - case "sourceQuery": - - out.Values[i] = ec._SQLQueryResults_sourceQuery(ctx, field, obj) - - case "dataFormat": - - out.Values[i] = ec._SQLQueryResults_dataFormat(ctx, field, obj) - - case "resultSet": - - out.Values[i] = ec._SQLQueryResults_resultSet(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLResultColumnImplementors = []string{"SQLResultColumn"} - -func (ec *executionContext) _SQLResultColumn(ctx context.Context, sel ast.SelectionSet, obj *model.SQLResultColumn) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLResultColumnImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLResultColumn") - case "position": - - out.Values[i] = ec._SQLResultColumn_position(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._SQLResultColumn_name(ctx, field, obj) - - case "label": - - out.Values[i] = ec._SQLResultColumn_label(ctx, field, obj) - - case "icon": - - out.Values[i] = ec._SQLResultColumn_icon(ctx, field, obj) - - case "entityName": - - out.Values[i] = ec._SQLResultColumn_entityName(ctx, field, obj) - - case "dataKind": - - out.Values[i] = ec._SQLResultColumn_dataKind(ctx, field, obj) - - case "typeName": - - out.Values[i] = ec._SQLResultColumn_typeName(ctx, field, obj) - - case "fullTypeName": - - out.Values[i] = ec._SQLResultColumn_fullTypeName(ctx, field, obj) - - case "maxLength": - - out.Values[i] = ec._SQLResultColumn_maxLength(ctx, field, obj) - - case "scale": - - out.Values[i] = ec._SQLResultColumn_scale(ctx, field, obj) - - case "precision": - - out.Values[i] = ec._SQLResultColumn_precision(ctx, field, obj) - - case "required": - - out.Values[i] = ec._SQLResultColumn_required(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "readOnly": - - out.Values[i] = ec._SQLResultColumn_readOnly(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "readOnlyStatus": - - out.Values[i] = ec._SQLResultColumn_readOnlyStatus(ctx, field, obj) - - case "supportedOperations": - - out.Values[i] = ec._SQLResultColumn_supportedOperations(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLResultSetImplementors = []string{"SQLResultSet"} - -func (ec *executionContext) _SQLResultSet(ctx context.Context, sel ast.SelectionSet, obj *model.SQLResultSet) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLResultSetImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLResultSet") - case "id": - - out.Values[i] = ec._SQLResultSet_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "columns": - - out.Values[i] = ec._SQLResultSet_columns(ctx, field, obj) - - case "rows": - - out.Values[i] = ec._SQLResultSet_rows(ctx, field, obj) - - case "singleEntity": - - out.Values[i] = ec._SQLResultSet_singleEntity(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "hasMoreData": - - out.Values[i] = ec._SQLResultSet_hasMoreData(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "hasRowIdentifier": - - out.Values[i] = ec._SQLResultSet_hasRowIdentifier(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLScriptInfoImplementors = []string{"SQLScriptInfo"} - -func (ec *executionContext) _SQLScriptInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SQLScriptInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLScriptInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLScriptInfo") - case "queries": - - out.Values[i] = ec._SQLScriptInfo_queries(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sQLScriptQueryImplementors = []string{"SQLScriptQuery"} - -func (ec *executionContext) _SQLScriptQuery(ctx context.Context, sel ast.SelectionSet, obj *model.SQLScriptQuery) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sQLScriptQueryImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SQLScriptQuery") - case "start": - - out.Values[i] = ec._SQLScriptQuery_start(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "end": - - out.Values[i] = ec._SQLScriptQuery_end(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var serverConfigImplementors = []string{"ServerConfig"} - -func (ec *executionContext) _ServerConfig(ctx context.Context, sel ast.SelectionSet, obj *model.ServerConfig) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, serverConfigImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ServerConfig") - case "name": - - out.Values[i] = ec._ServerConfig_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "version": - - out.Values[i] = ec._ServerConfig_version(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "workspaceId": - - out.Values[i] = ec._ServerConfig_workspaceId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "serverURL": - - out.Values[i] = ec._ServerConfig_serverURL(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "rootURI": - - out.Values[i] = ec._ServerConfig_rootURI(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "hostName": - - out.Values[i] = ec._ServerConfig_hostName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "anonymousAccessEnabled": - - out.Values[i] = ec._ServerConfig_anonymousAccessEnabled(ctx, field, obj) - - case "authenticationEnabled": - - out.Values[i] = ec._ServerConfig_authenticationEnabled(ctx, field, obj) - - case "supportsCustomConnections": - - out.Values[i] = ec._ServerConfig_supportsCustomConnections(ctx, field, obj) - - case "supportsConnectionBrowser": - - out.Values[i] = ec._ServerConfig_supportsConnectionBrowser(ctx, field, obj) - - case "supportsWorkspaces": - - out.Values[i] = ec._ServerConfig_supportsWorkspaces(ctx, field, obj) - - case "resourceManagerEnabled": - - out.Values[i] = ec._ServerConfig_resourceManagerEnabled(ctx, field, obj) - - case "publicCredentialsSaveEnabled": - - out.Values[i] = ec._ServerConfig_publicCredentialsSaveEnabled(ctx, field, obj) - - case "adminCredentialsSaveEnabled": - - out.Values[i] = ec._ServerConfig_adminCredentialsSaveEnabled(ctx, field, obj) - - case "licenseRequired": - - out.Values[i] = ec._ServerConfig_licenseRequired(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "licenseValid": - - out.Values[i] = ec._ServerConfig_licenseValid(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "sessionExpireTime": - - out.Values[i] = ec._ServerConfig_sessionExpireTime(ctx, field, obj) - - case "localHostAddress": - - out.Values[i] = ec._ServerConfig_localHostAddress(ctx, field, obj) - - case "configurationMode": - - out.Values[i] = ec._ServerConfig_configurationMode(ctx, field, obj) - - case "developmentMode": - - out.Values[i] = ec._ServerConfig_developmentMode(ctx, field, obj) - - case "redirectOnFederatedAuth": - - out.Values[i] = ec._ServerConfig_redirectOnFederatedAuth(ctx, field, obj) - - case "enabledFeatures": - - out.Values[i] = ec._ServerConfig_enabledFeatures(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "enabledAuthProviders": - - out.Values[i] = ec._ServerConfig_enabledAuthProviders(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "supportedLanguages": - - out.Values[i] = ec._ServerConfig_supportedLanguages(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "services": - - out.Values[i] = ec._ServerConfig_services(ctx, field, obj) - - case "productConfiguration": - - out.Values[i] = ec._ServerConfig_productConfiguration(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "productInfo": - - out.Values[i] = ec._ServerConfig_productInfo(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "defaultNavigatorSettings": - - out.Values[i] = ec._ServerConfig_defaultNavigatorSettings(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "disabledDrivers": - - out.Values[i] = ec._ServerConfig_disabledDrivers(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "resourceQuotas": - - out.Values[i] = ec._ServerConfig_resourceQuotas(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var serverErrorImplementors = []string{"ServerError"} - -func (ec *executionContext) _ServerError(ctx context.Context, sel ast.SelectionSet, obj *model.ServerError) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, serverErrorImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ServerError") - case "message": - - out.Values[i] = ec._ServerError_message(ctx, field, obj) - - case "errorCode": - - out.Values[i] = ec._ServerError_errorCode(ctx, field, obj) - - case "errorType": - - out.Values[i] = ec._ServerError_errorType(ctx, field, obj) - - case "stackTrace": - - out.Values[i] = ec._ServerError_stackTrace(ctx, field, obj) - - case "causedBy": - - out.Values[i] = ec._ServerError_causedBy(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var serverLanguageImplementors = []string{"ServerLanguage"} - -func (ec *executionContext) _ServerLanguage(ctx context.Context, sel ast.SelectionSet, obj *model.ServerLanguage) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, serverLanguageImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ServerLanguage") - case "isoCode": - - out.Values[i] = ec._ServerLanguage_isoCode(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "displayName": - - out.Values[i] = ec._ServerLanguage_displayName(ctx, field, obj) - - case "nativeName": - - out.Values[i] = ec._ServerLanguage_nativeName(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var serverMessageImplementors = []string{"ServerMessage"} - -func (ec *executionContext) _ServerMessage(ctx context.Context, sel ast.SelectionSet, obj *model.ServerMessage) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, serverMessageImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("ServerMessage") - case "time": - - out.Values[i] = ec._ServerMessage_time(ctx, field, obj) - - case "message": - - out.Values[i] = ec._ServerMessage_message(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var sessionInfoImplementors = []string{"SessionInfo"} - -func (ec *executionContext) _SessionInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SessionInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sessionInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("SessionInfo") - case "createTime": - - out.Values[i] = ec._SessionInfo_createTime(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "lastAccessTime": - - out.Values[i] = ec._SessionInfo_lastAccessTime(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "locale": - - out.Values[i] = ec._SessionInfo_locale(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "cacheExpired": - - out.Values[i] = ec._SessionInfo_cacheExpired(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "serverMessages": - - out.Values[i] = ec._SessionInfo_serverMessages(ctx, field, obj) - - case "connections": - - out.Values[i] = ec._SessionInfo_connections(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "actionParameters": - - out.Values[i] = ec._SessionInfo_actionParameters(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var userAuthTokenImplementors = []string{"UserAuthToken"} - -func (ec *executionContext) _UserAuthToken(ctx context.Context, sel ast.SelectionSet, obj *model.UserAuthToken) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, userAuthTokenImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("UserAuthToken") - case "authProvider": - - out.Values[i] = ec._UserAuthToken_authProvider(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "authConfiguration": - - out.Values[i] = ec._UserAuthToken_authConfiguration(ctx, field, obj) - - case "loginTime": - - out.Values[i] = ec._UserAuthToken_loginTime(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "userId": - - out.Values[i] = ec._UserAuthToken_userId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "displayName": - - out.Values[i] = ec._UserAuthToken_displayName(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "message": - - out.Values[i] = ec._UserAuthToken_message(ctx, field, obj) - - case "origin": - - out.Values[i] = ec._UserAuthToken_origin(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var userInfoImplementors = []string{"UserInfo"} - -func (ec *executionContext) _UserInfo(ctx context.Context, sel ast.SelectionSet, obj *model.UserInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, userInfoImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("UserInfo") - case "userId": - - out.Values[i] = ec._UserInfo_userId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "displayName": - - out.Values[i] = ec._UserInfo_displayName(ctx, field, obj) - - case "authRole": - - out.Values[i] = ec._UserInfo_authRole(ctx, field, obj) - - case "authTokens": - - out.Values[i] = ec._UserInfo_authTokens(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "linkedAuthProviders": - - out.Values[i] = ec._UserInfo_linkedAuthProviders(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "metaParameters": - - out.Values[i] = ec._UserInfo_metaParameters(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "configurationParameters": - - out.Values[i] = ec._UserInfo_configurationParameters(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var webFeatureSetImplementors = []string{"WebFeatureSet"} - -func (ec *executionContext) _WebFeatureSet(ctx context.Context, sel ast.SelectionSet, obj *model.WebFeatureSet) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, webFeatureSetImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("WebFeatureSet") - case "id": - - out.Values[i] = ec._WebFeatureSet_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "label": - - out.Values[i] = ec._WebFeatureSet_label(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._WebFeatureSet_description(ctx, field, obj) - - case "icon": - - out.Values[i] = ec._WebFeatureSet_icon(ctx, field, obj) - - case "enabled": - - out.Values[i] = ec._WebFeatureSet_enabled(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var webServiceConfigImplementors = []string{"WebServiceConfig"} - -func (ec *executionContext) _WebServiceConfig(ctx context.Context, sel ast.SelectionSet, obj *model.WebServiceConfig) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, webServiceConfigImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("WebServiceConfig") - case "id": - - out.Values[i] = ec._WebServiceConfig_id(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec._WebServiceConfig_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec._WebServiceConfig_description(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "bundleVersion": - - out.Values[i] = ec._WebServiceConfig_bundleVersion(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __DirectiveImplementors = []string{"__Directive"} - -func (ec *executionContext) ___Directive(ctx context.Context, sel ast.SelectionSet, obj *introspection.Directive) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __DirectiveImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Directive") - case "name": - - out.Values[i] = ec.___Directive_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec.___Directive_description(ctx, field, obj) - - case "locations": - - out.Values[i] = ec.___Directive_locations(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "args": - - out.Values[i] = ec.___Directive_args(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "isRepeatable": - - out.Values[i] = ec.___Directive_isRepeatable(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __EnumValueImplementors = []string{"__EnumValue"} - -func (ec *executionContext) ___EnumValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.EnumValue) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __EnumValueImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__EnumValue") - case "name": - - out.Values[i] = ec.___EnumValue_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec.___EnumValue_description(ctx, field, obj) - - case "isDeprecated": - - out.Values[i] = ec.___EnumValue_isDeprecated(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "deprecationReason": - - out.Values[i] = ec.___EnumValue_deprecationReason(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __FieldImplementors = []string{"__Field"} - -func (ec *executionContext) ___Field(ctx context.Context, sel ast.SelectionSet, obj *introspection.Field) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __FieldImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Field") - case "name": - - out.Values[i] = ec.___Field_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec.___Field_description(ctx, field, obj) - - case "args": - - out.Values[i] = ec.___Field_args(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "type": - - out.Values[i] = ec.___Field_type(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "isDeprecated": - - out.Values[i] = ec.___Field_isDeprecated(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "deprecationReason": - - out.Values[i] = ec.___Field_deprecationReason(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __InputValueImplementors = []string{"__InputValue"} - -func (ec *executionContext) ___InputValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.InputValue) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __InputValueImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__InputValue") - case "name": - - out.Values[i] = ec.___InputValue_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec.___InputValue_description(ctx, field, obj) - - case "type": - - out.Values[i] = ec.___InputValue_type(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "defaultValue": - - out.Values[i] = ec.___InputValue_defaultValue(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __SchemaImplementors = []string{"__Schema"} - -func (ec *executionContext) ___Schema(ctx context.Context, sel ast.SelectionSet, obj *introspection.Schema) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __SchemaImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Schema") - case "description": - - out.Values[i] = ec.___Schema_description(ctx, field, obj) - - case "types": - - out.Values[i] = ec.___Schema_types(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "queryType": - - out.Values[i] = ec.___Schema_queryType(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "mutationType": - - out.Values[i] = ec.___Schema_mutationType(ctx, field, obj) - - case "subscriptionType": - - out.Values[i] = ec.___Schema_subscriptionType(ctx, field, obj) - - case "directives": - - out.Values[i] = ec.___Schema_directives(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -var __TypeImplementors = []string{"__Type"} - -func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, obj *introspection.Type) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __TypeImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Type") - case "kind": - - out.Values[i] = ec.___Type_kind(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - - out.Values[i] = ec.___Type_name(ctx, field, obj) - - case "description": - - out.Values[i] = ec.___Type_description(ctx, field, obj) - - case "fields": - - out.Values[i] = ec.___Type_fields(ctx, field, obj) - - case "interfaces": - - out.Values[i] = ec.___Type_interfaces(ctx, field, obj) - - case "possibleTypes": - - out.Values[i] = ec.___Type_possibleTypes(ctx, field, obj) - - case "enumValues": - - out.Values[i] = ec.___Type_enumValues(ctx, field, obj) - - case "inputFields": - - out.Values[i] = ec.___Type_inputFields(ctx, field, obj) - - case "ofType": - - out.Values[i] = ec.___Type_ofType(ctx, field, obj) - - case "specifiedByURL": - - out.Values[i] = ec.___Type_specifiedByURL(ctx, field, obj) - - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - -// endregion **************************** object.gotpl **************************** - -// region ***************************** type.gotpl ***************************** - -func (ec *executionContext) marshalNAdminAuthProviderConfiguration2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v model.AdminAuthProviderConfiguration) graphql.Marshaler { - return ec._AdminAuthProviderConfiguration(ctx, sel, &v) -} - -func (ec *executionContext) marshalNAdminAuthProviderConfiguration2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminAuthProviderConfigurationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminAuthProviderConfiguration) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAdminAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminAuthProviderConfiguration(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAdminAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v *model.AdminAuthProviderConfiguration) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AdminAuthProviderConfiguration(ctx, sel, v) -} - -func (ec *executionContext) marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminConnectionGrantInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAdminConnectionGrantInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionGrantInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAdminConnectionGrantInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionGrantInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminConnectionGrantInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AdminConnectionGrantInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAdminConnectionSearchInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionSearchInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminConnectionSearchInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAdminConnectionSearchInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionSearchInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAdminConnectionSearchInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminConnectionSearchInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminConnectionSearchInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AdminConnectionSearchInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAdminPermissionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminPermissionInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminPermissionInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAdminPermissionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminPermissionInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAdminPermissionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminPermissionInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminPermissionInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AdminPermissionInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAdminRoleInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminRoleInfo(ctx context.Context, sel ast.SelectionSet, v model.AdminRoleInfo) graphql.Marshaler { - return ec._AdminRoleInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNAdminRoleInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminRoleInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminRoleInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAdminRoleInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminRoleInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAdminRoleInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminRoleInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminRoleInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AdminRoleInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNAdminSubjectType2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminSubjectType(ctx context.Context, v interface{}) (model.AdminSubjectType, error) { - var res model.AdminSubjectType - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNAdminSubjectType2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminSubjectType(ctx context.Context, sel ast.SelectionSet, v model.AdminSubjectType) graphql.Marshaler { - return v -} - -func (ec *executionContext) marshalNAdminUserInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminUserInfo(ctx context.Context, sel ast.SelectionSet, v model.AdminUserInfo) graphql.Marshaler { - return ec._AdminUserInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNAdminUserInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminUserInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminUserInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAdminUserInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminUserInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAdminUserInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAdminUserInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminUserInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AdminUserInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAsyncTaskInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx context.Context, sel ast.SelectionSet, v model.AsyncTaskInfo) graphql.Marshaler { - return ec._AsyncTaskInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAsyncTaskInfo(ctx context.Context, sel ast.SelectionSet, v *model.AsyncTaskInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AsyncTaskInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAuthCredentialInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthCredentialInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthCredentialInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAuthCredentialInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthCredentialInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAuthCredentialInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthCredentialInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthCredentialInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AuthCredentialInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAuthInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthInfo(ctx context.Context, sel ast.SelectionSet, v model.AuthInfo) graphql.Marshaler { - return ec._AuthInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNAuthInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AuthInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderConfiguration) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AuthProviderConfiguration(ctx, sel, v) -} - -func (ec *executionContext) marshalNAuthProviderCredentialsProfile2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderCredentialsProfileᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderCredentialsProfile) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAuthProviderCredentialsProfile2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderCredentialsProfile(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAuthProviderCredentialsProfile2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderCredentialsProfile(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderCredentialsProfile) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AuthProviderCredentialsProfile(ctx, sel, v) -} - -func (ec *executionContext) marshalNAuthProviderInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAuthProviderInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNAuthProviderInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AuthProviderInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNAuthStatus2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthStatus(ctx context.Context, v interface{}) (model.AuthStatus, error) { - var res model.AuthStatus - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNAuthStatus2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthStatus(ctx context.Context, sel ast.SelectionSet, v model.AuthStatus) graphql.Marshaler { - return v -} - -func (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v interface{}) (bool, error) { - res, err := graphql.UnmarshalBoolean(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { - res := graphql.MarshalBoolean(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx context.Context, v interface{}) (model.ConnectionConfig, error) { - res, err := ec.unmarshalInputConnectionConfig(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNConnectionFolderInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionFolderInfo(ctx context.Context, sel ast.SelectionSet, v model.ConnectionFolderInfo) graphql.Marshaler { - return ec._ConnectionFolderInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNConnectionFolderInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionFolderInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ConnectionFolderInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNConnectionFolderInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionFolderInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNConnectionFolderInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionFolderInfo(ctx context.Context, sel ast.SelectionSet, v *model.ConnectionFolderInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._ConnectionFolderInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNConnectionInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx context.Context, sel ast.SelectionSet, v model.ConnectionInfo) graphql.Marshaler { - return ec._ConnectionInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNConnectionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ConnectionInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionInfo(ctx context.Context, sel ast.SelectionSet, v *model.ConnectionInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._ConnectionInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNDataTransferParameters2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTransferParameters(ctx context.Context, v interface{}) (model.DataTransferParameters, error) { - res, err := ec.unmarshalInputDataTransferParameters(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNDataTransferProcessorInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTransferProcessorInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DataTransferProcessorInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNDataTransferProcessorInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTransferProcessorInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNDataTransferProcessorInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTransferProcessorInfo(ctx context.Context, sel ast.SelectionSet, v *model.DataTransferProcessorInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._DataTransferProcessorInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNDataTypeLogicalOperation2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTypeLogicalOperationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DataTypeLogicalOperation) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNDataTypeLogicalOperation2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTypeLogicalOperation(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNDataTypeLogicalOperation2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDataTypeLogicalOperation(ctx context.Context, sel ast.SelectionSet, v *model.DataTypeLogicalOperation) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._DataTypeLogicalOperation(ctx, sel, v) -} - -func (ec *executionContext) marshalNDatabaseAuthModel2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseAuthModelᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DatabaseAuthModel) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNDatabaseAuthModel2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseAuthModel(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNDatabaseAuthModel2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseAuthModel(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseAuthModel) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._DatabaseAuthModel(ctx, sel, v) -} - -func (ec *executionContext) marshalNDatabaseCatalog2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseCatalogᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DatabaseCatalog) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNDatabaseCatalog2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseCatalog(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNDatabaseCatalog2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseCatalog(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseCatalog) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._DatabaseCatalog(ctx, sel, v) -} - -func (ec *executionContext) marshalNDatabaseStructContainers2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseStructContainers(ctx context.Context, sel ast.SelectionSet, v model.DatabaseStructContainers) graphql.Marshaler { - return ec._DatabaseStructContainers(ctx, sel, &v) -} - -func (ec *executionContext) marshalNDatabaseStructContainers2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseStructContainers(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseStructContainers) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._DatabaseStructContainers(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNDateTime2timeᚐTime(ctx context.Context, v interface{}) (time.Time, error) { - res, err := graphql.UnmarshalTime(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNDateTime2timeᚐTime(ctx context.Context, sel ast.SelectionSet, v time.Time) graphql.Marshaler { - res := graphql.MarshalTime(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) marshalNDriverInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDriverInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DriverInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNDriverInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDriverInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNDriverInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDriverInfo(ctx context.Context, sel ast.SelectionSet, v *model.DriverInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._DriverInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNID2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalID(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNID2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalID(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) unmarshalNID2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNID2string(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalNID2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalNID2string(ctx, sel, v[i]) - } - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) unmarshalNID2ᚕᚖstring(ctx context.Context, v interface{}) ([]*string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOID2ᚖstring(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalNID2ᚕᚖstring(ctx context.Context, sel ast.SelectionSet, v []*string) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalOID2ᚖstring(ctx, sel, v[i]) - } - - return ret -} - -func (ec *executionContext) unmarshalNInt2int(ctx context.Context, v interface{}) (int, error) { - res, err := graphql.UnmarshalInt(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNInt2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { - res := graphql.MarshalInt(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) marshalNLogEntry2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐLogEntryᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.LogEntry) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNLogEntry2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐLogEntry(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNLogEntry2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐLogEntry(ctx context.Context, sel ast.SelectionSet, v *model.LogEntry) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._LogEntry(ctx, sel, v) -} - -func (ec *executionContext) marshalNNavigatorNodeInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, v model.NavigatorNodeInfo) graphql.Marshaler { - return ec._NavigatorNodeInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NavigatorNodeInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, v *model.NavigatorNodeInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._NavigatorNodeInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNNavigatorSettings2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorSettings(ctx context.Context, sel ast.SelectionSet, v *model.NavigatorSettings) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._NavigatorSettings(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNNavigatorSettingsInput2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNavigatorSettingsInput(ctx context.Context, v interface{}) (model.NavigatorSettingsInput, error) { - res, err := ec.unmarshalInputNavigatorSettingsInput(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNNetworkEndpointInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkEndpointInfo(ctx context.Context, sel ast.SelectionSet, v model.NetworkEndpointInfo) graphql.Marshaler { - return ec._NetworkEndpointInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNNetworkEndpointInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkEndpointInfo(ctx context.Context, sel ast.SelectionSet, v *model.NetworkEndpointInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._NetworkEndpointInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNNetworkHandlerAuthType2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, v interface{}) (model.NetworkHandlerAuthType, error) { - var res model.NetworkHandlerAuthType - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNNetworkHandlerAuthType2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, sel ast.SelectionSet, v model.NetworkHandlerAuthType) graphql.Marshaler { - return v -} - -func (ec *executionContext) marshalNNetworkHandlerConfig2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NetworkHandlerConfig) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNNetworkHandlerConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfig(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNNetworkHandlerConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfig(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerConfig) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._NetworkHandlerConfig(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNNetworkHandlerConfigInput2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigInput(ctx context.Context, v interface{}) (model.NetworkHandlerConfigInput, error) { - res, err := ec.unmarshalInputNetworkHandlerConfigInput(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) unmarshalNNetworkHandlerConfigInput2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigInput(ctx context.Context, v interface{}) (*model.NetworkHandlerConfigInput, error) { - res, err := ec.unmarshalInputNetworkHandlerConfigInput(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNNetworkHandlerDescriptor2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerDescriptorᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NetworkHandlerDescriptor) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNNetworkHandlerDescriptor2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerDescriptor(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNNetworkHandlerDescriptor2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerDescriptor(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerDescriptor) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._NetworkHandlerDescriptor(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNObject2interface(ctx context.Context, v interface{}) (interface{}, error) { - res, err := graphql.UnmarshalAny(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNObject2interface(ctx context.Context, sel ast.SelectionSet, v interface{}) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - res := graphql.MarshalAny(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) unmarshalNObject2ᚕinterface(ctx context.Context, v interface{}) ([]interface{}, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]interface{}, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOObject2interface(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalNObject2ᚕinterface(ctx context.Context, sel ast.SelectionSet, v []interface{}) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalOObject2interface(ctx, sel, v[i]) - } - - return ret -} - -func (ec *executionContext) marshalNObjectOrigin2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectOriginᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectOrigin) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNObjectOrigin2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectOrigin(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNObjectOrigin2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectOrigin(ctx context.Context, sel ast.SelectionSet, v *model.ObjectOrigin) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._ObjectOrigin(ctx, sel, v) -} - -func (ec *executionContext) marshalNObjectPropertyInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v model.ObjectPropertyInfo) graphql.Marshaler { - return ec._ObjectPropertyInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v *model.ObjectPropertyInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._ObjectPropertyInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNObjectPropertyLength2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyLength(ctx context.Context, v interface{}) (model.ObjectPropertyLength, error) { - var res model.ObjectPropertyLength - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNObjectPropertyLength2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyLength(ctx context.Context, sel ast.SelectionSet, v model.ObjectPropertyLength) graphql.Marshaler { - return v -} - -func (ec *executionContext) marshalNProductInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐProductInfo(ctx context.Context, sel ast.SelectionSet, v *model.ProductInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._ProductInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNRMProject2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐRMProjectᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.RMProject) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNRMProject2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐRMProject(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNRMProject2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐRMProject(ctx context.Context, sel ast.SelectionSet, v *model.RMProject) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._RMProject(ctx, sel, v) -} - -func (ec *executionContext) marshalNRMResource2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐRMResourceᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.RMResource) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNRMResource2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐRMResource(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNRMResource2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐRMResource(ctx context.Context, sel ast.SelectionSet, v *model.RMResource) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._RMResource(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNResultDataFormat2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx context.Context, v interface{}) (model.ResultDataFormat, error) { - var res model.ResultDataFormat - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNResultDataFormat2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx context.Context, sel ast.SelectionSet, v model.ResultDataFormat) graphql.Marshaler { - return v -} - -func (ec *executionContext) unmarshalNResultDataFormat2ᚕgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormatᚄ(ctx context.Context, v interface{}) ([]model.ResultDataFormat, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]model.ResultDataFormat, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNResultDataFormat2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalNResultDataFormat2ᚕgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormatᚄ(ctx context.Context, sel ast.SelectionSet, v []model.ResultDataFormat) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNResultDataFormat2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNSQLContextInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLContextInfo) graphql.Marshaler { - return ec._SQLContextInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNSQLContextInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v []*model.SQLContextInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalOSQLContextInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLContextInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - return ret -} - -func (ec *executionContext) marshalNSQLContextInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLContextInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLContextInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNSQLExecuteInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLExecuteInfo) graphql.Marshaler { - return ec._SQLExecuteInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNSQLExecuteInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecuteInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLExecuteInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNSQLExecutionPlan2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecutionPlan(ctx context.Context, sel ast.SelectionSet, v model.SQLExecutionPlan) graphql.Marshaler { - return ec._SQLExecutionPlan(ctx, sel, &v) -} - -func (ec *executionContext) marshalNSQLExecutionPlan2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecutionPlan(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecutionPlan) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLExecutionPlan(ctx, sel, v) -} - -func (ec *executionContext) marshalNSQLExecutionPlanNode2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecutionPlanNodeᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLExecutionPlanNode) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNSQLExecutionPlanNode2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecutionPlanNode(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNSQLExecutionPlanNode2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecutionPlanNode(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecutionPlanNode) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLExecutionPlanNode(ctx, sel, v) -} - -func (ec *executionContext) marshalNSQLQueryGenerator2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLQueryGeneratorᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLQueryGenerator) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNSQLQueryGenerator2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLQueryGenerator(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNSQLQueryGenerator2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLQueryGenerator(ctx context.Context, sel ast.SelectionSet, v *model.SQLQueryGenerator) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLQueryGenerator(ctx, sel, v) -} - -func (ec *executionContext) marshalNSQLQueryResults2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLQueryResultsᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLQueryResults) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNSQLQueryResults2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLQueryResults(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNSQLQueryResults2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLQueryResults(ctx context.Context, sel ast.SelectionSet, v *model.SQLQueryResults) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLQueryResults(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx context.Context, v interface{}) ([]*model.SQLResultRow, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*model.SQLResultRow, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNSQLResultRow2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRow(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) unmarshalNSQLResultRow2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRow(ctx context.Context, v interface{}) (*model.SQLResultRow, error) { - res, err := ec.unmarshalInputSQLResultRow(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNSQLScriptInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLScriptInfo) graphql.Marshaler { - return ec._SQLScriptInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNSQLScriptInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLScriptInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLScriptInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNSQLScriptQuery2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptQuery(ctx context.Context, sel ast.SelectionSet, v model.SQLScriptQuery) graphql.Marshaler { - return ec._SQLScriptQuery(ctx, sel, &v) -} - -func (ec *executionContext) marshalNSQLScriptQuery2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptQueryᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLScriptQuery) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNSQLScriptQuery2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptQuery(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNSQLScriptQuery2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLScriptQuery(ctx context.Context, sel ast.SelectionSet, v *model.SQLScriptQuery) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLScriptQuery(ctx, sel, v) -} - -func (ec *executionContext) marshalNServerConfig2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerConfig(ctx context.Context, sel ast.SelectionSet, v model.ServerConfig) graphql.Marshaler { - return ec._ServerConfig(ctx, sel, &v) -} - -func (ec *executionContext) marshalNServerConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerConfig(ctx context.Context, sel ast.SelectionSet, v *model.ServerConfig) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._ServerConfig(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNServerConfigInput2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerConfigInput(ctx context.Context, v interface{}) (model.ServerConfigInput, error) { - res, err := ec.unmarshalInputServerConfigInput(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNServerLanguage2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerLanguageᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ServerLanguage) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNServerLanguage2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerLanguage(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNServerLanguage2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerLanguage(ctx context.Context, sel ast.SelectionSet, v *model.ServerLanguage) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._ServerLanguage(ctx, sel, v) -} - -func (ec *executionContext) marshalNSessionInfo2githubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSessionInfo(ctx context.Context, sel ast.SelectionSet, v model.SessionInfo) graphql.Marshaler { - return ec._SessionInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNSessionInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSessionInfo(ctx context.Context, sel ast.SelectionSet, v *model.SessionInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SessionInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNString2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalString(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalString(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) unmarshalNString2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNString2string(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalNString2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalNString2string(ctx, sel, v[i]) - } - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) unmarshalNString2ᚕᚕᚖstring(ctx context.Context, v interface{}) ([][]*string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([][]*string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOString2ᚕᚖstring(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalNString2ᚕᚕᚖstring(ctx context.Context, sel ast.SelectionSet, v [][]*string) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalOString2ᚕᚖstring(ctx, sel, v[i]) - } - - return ret -} - -func (ec *executionContext) unmarshalNString2ᚕᚖstring(ctx context.Context, v interface{}) ([]*string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOString2ᚖstring(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalNString2ᚕᚖstring(ctx context.Context, sel ast.SelectionSet, v []*string) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalOString2ᚖstring(ctx, sel, v[i]) - } - - return ret -} - -func (ec *executionContext) marshalNUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserAuthTokenᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.UserAuthToken) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNUserAuthToken2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserAuthToken(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNUserAuthToken2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserAuthToken(ctx context.Context, sel ast.SelectionSet, v *model.UserAuthToken) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._UserAuthToken(ctx, sel, v) -} - -func (ec *executionContext) marshalNWebFeatureSet2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐWebFeatureSetᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.WebFeatureSet) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNWebFeatureSet2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐWebFeatureSet(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalNWebFeatureSet2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐWebFeatureSet(ctx context.Context, sel ast.SelectionSet, v *model.WebFeatureSet) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._WebFeatureSet(ctx, sel, v) -} - -func (ec *executionContext) marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx context.Context, sel ast.SelectionSet, v introspection.Directive) graphql.Marshaler { - return ec.___Directive(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Directive) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) unmarshalN__DirectiveLocation2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalString(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalN__DirectiveLocation2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalString(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) unmarshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalN__DirectiveLocation2string(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__DirectiveLocation2string(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalN__EnumValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValue(ctx context.Context, sel ast.SelectionSet, v introspection.EnumValue) graphql.Marshaler { - return ec.___EnumValue(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__Field2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐField(ctx context.Context, sel ast.SelectionSet, v introspection.Field) graphql.Marshaler { - return ec.___Field(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx context.Context, sel ast.SelectionSet, v introspection.InputValue) graphql.Marshaler { - return ec.___InputValue(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v introspection.Type) graphql.Marshaler { - return ec.___Type(ctx, sel, &v) -} - -func (ec *executionContext) marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec.___Type(ctx, sel, v) -} - -func (ec *executionContext) unmarshalN__TypeKind2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalString(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalN__TypeKind2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalString(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) unmarshalOAuthCredentialEncryption2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthCredentialEncryption(ctx context.Context, v interface{}) (*model.AuthCredentialEncryption, error) { - if v == nil { - return nil, nil - } - var res = new(model.AuthCredentialEncryption) - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOAuthCredentialEncryption2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthCredentialEncryption(ctx context.Context, sel ast.SelectionSet, v *model.AuthCredentialEncryption) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return v -} - -func (ec *executionContext) marshalOAuthProviderConfiguration2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderConfigurationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderConfiguration) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐAuthProviderConfiguration(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) unmarshalOBoolean2bool(ctx context.Context, v interface{}) (bool, error) { - res, err := graphql.UnmarshalBoolean(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { - res := graphql.MarshalBoolean(v) - return res -} - -func (ec *executionContext) unmarshalOBoolean2ᚖbool(ctx context.Context, v interface{}) (*bool, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalBoolean(v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOBoolean2ᚖbool(ctx context.Context, sel ast.SelectionSet, v *bool) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalBoolean(*v) - return res -} - -func (ec *executionContext) unmarshalOConnectionConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐConnectionConfig(ctx context.Context, v interface{}) (*model.ConnectionConfig, error) { - if v == nil { - return nil, nil - } - res, err := ec.unmarshalInputConnectionConfig(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalODatabaseObjectInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐDatabaseObjectInfo(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseObjectInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._DatabaseObjectInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalODateTime2ᚖtimeᚐTime(ctx context.Context, v interface{}) (*time.Time, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalTime(v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalODateTime2ᚖtimeᚐTime(ctx context.Context, sel ast.SelectionSet, v *time.Time) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalTime(*v) - return res -} - -func (ec *executionContext) unmarshalOFloat2ᚖfloat64(ctx context.Context, v interface{}) (*float64, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalFloatContext(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOFloat2ᚖfloat64(ctx context.Context, sel ast.SelectionSet, v *float64) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalFloatContext(*v) - return graphql.WrapContextMarshaler(ctx, res) -} - -func (ec *executionContext) unmarshalOID2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNID2string(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalOID2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalNID2string(ctx, sel, v[i]) - } - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) unmarshalOID2ᚖstring(ctx context.Context, v interface{}) (*string, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalID(v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOID2ᚖstring(ctx context.Context, sel ast.SelectionSet, v *string) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalID(*v) - return res -} - -func (ec *executionContext) unmarshalOInt2ᚖint(ctx context.Context, v interface{}) (*int, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalInt(v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOInt2ᚖint(ctx context.Context, sel ast.SelectionSet, v *int) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalInt(*v) - return res -} - -func (ec *executionContext) unmarshalONetworkHandlerAuthType2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, v interface{}) (*model.NetworkHandlerAuthType, error) { - if v == nil { - return nil, nil - } - var res = new(model.NetworkHandlerAuthType) - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalONetworkHandlerAuthType2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerAuthType) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return v -} - -func (ec *executionContext) unmarshalONetworkHandlerConfigInput2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigInputᚄ(ctx context.Context, v interface{}) ([]*model.NetworkHandlerConfigInput, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*model.NetworkHandlerConfigInput, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNNetworkHandlerConfigInput2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerConfigInput(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) unmarshalONetworkHandlerType2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerType(ctx context.Context, v interface{}) (*model.NetworkHandlerType, error) { - if v == nil { - return nil, nil - } - var res = new(model.NetworkHandlerType) - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalONetworkHandlerType2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐNetworkHandlerType(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerType) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return v -} - -func (ec *executionContext) unmarshalOObject2interface(ctx context.Context, v interface{}) (interface{}, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalAny(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOObject2interface(ctx context.Context, sel ast.SelectionSet, v interface{}) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalAny(v) - return res -} - -func (ec *executionContext) unmarshalOObject2ᚕinterface(ctx context.Context, v interface{}) ([]interface{}, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]interface{}, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOObject2interface(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalOObject2ᚕinterface(ctx context.Context, sel ast.SelectionSet, v []interface{}) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalOObject2interface(ctx, sel, v[i]) - } - - return ret -} - -func (ec *executionContext) unmarshalOObject2ᚕᚕinterface(ctx context.Context, v interface{}) ([][]interface{}, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([][]interface{}, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOObject2ᚕinterface(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalOObject2ᚕᚕinterface(ctx context.Context, sel ast.SelectionSet, v [][]interface{}) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalOObject2ᚕinterface(ctx, sel, v[i]) - } - - return ret -} - -func (ec *executionContext) unmarshalOObjectPropertyFilter2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyFilter(ctx context.Context, v interface{}) (*model.ObjectPropertyFilter, error) { - if v == nil { - return nil, nil - } - res, err := ec.unmarshalInputObjectPropertyFilter(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalOObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - return ret -} - -func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalOObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v *model.ObjectPropertyInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._ObjectPropertyInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx context.Context, v interface{}) (*model.ResultDataFormat, error) { - if v == nil { - return nil, nil - } - var res = new(model.ResultDataFormat) - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐResultDataFormat(ctx context.Context, sel ast.SelectionSet, v *model.ResultDataFormat) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return v -} - -func (ec *executionContext) marshalOSQLCompletionProposal2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLCompletionProposal(ctx context.Context, sel ast.SelectionSet, v []*model.SQLCompletionProposal) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalOSQLCompletionProposal2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLCompletionProposal(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - return ret -} - -func (ec *executionContext) marshalOSQLCompletionProposal2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLCompletionProposal(ctx context.Context, sel ast.SelectionSet, v *model.SQLCompletionProposal) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._SQLCompletionProposal(ctx, sel, v) -} - -func (ec *executionContext) marshalOSQLContextInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLContextInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._SQLContextInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalOSQLDataFilter2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDataFilter(ctx context.Context, v interface{}) (*model.SQLDataFilter, error) { - if v == nil { - return nil, nil - } - res, err := ec.unmarshalInputSQLDataFilter(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) unmarshalOSQLDataFilterConstraint2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDataFilterConstraint(ctx context.Context, v interface{}) ([]*model.SQLDataFilterConstraint, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*model.SQLDataFilterConstraint, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOSQLDataFilterConstraint2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDataFilterConstraint(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) unmarshalOSQLDataFilterConstraint2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDataFilterConstraint(ctx context.Context, v interface{}) (*model.SQLDataFilterConstraint, error) { - if v == nil { - return nil, nil - } - res, err := ec.unmarshalInputSQLDataFilterConstraint(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOSQLDialectInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLDialectInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLDialectInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._SQLDialectInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalOSQLExecuteInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecuteInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._SQLExecuteInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalOSQLResultColumn2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultColumn(ctx context.Context, sel ast.SelectionSet, v []*model.SQLResultColumn) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalOSQLResultColumn2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultColumn(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - return ret -} - -func (ec *executionContext) marshalOSQLResultColumn2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultColumn(ctx context.Context, sel ast.SelectionSet, v *model.SQLResultColumn) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._SQLResultColumn(ctx, sel, v) -} - -func (ec *executionContext) unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRowᚄ(ctx context.Context, v interface{}) ([]*model.SQLResultRow, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*model.SQLResultRow, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNSQLResultRow2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultRow(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalOSQLResultSet2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐSQLResultSet(ctx context.Context, sel ast.SelectionSet, v *model.SQLResultSet) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._SQLResultSet(ctx, sel, v) -} - -func (ec *executionContext) marshalOServerError2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerError(ctx context.Context, sel ast.SelectionSet, v *model.ServerError) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._ServerError(ctx, sel, v) -} - -func (ec *executionContext) marshalOServerMessage2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerMessage(ctx context.Context, sel ast.SelectionSet, v []*model.ServerMessage) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalOServerMessage2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerMessage(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - return ret -} - -func (ec *executionContext) marshalOServerMessage2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐServerMessage(ctx context.Context, sel ast.SelectionSet, v *model.ServerMessage) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._ServerMessage(ctx, sel, v) -} - -func (ec *executionContext) unmarshalOString2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNString2string(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalOString2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalNString2string(ctx, sel, v[i]) - } - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) unmarshalOString2ᚕᚖstring(ctx context.Context, v interface{}) ([]*string, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOString2ᚖstring(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalOString2ᚕᚖstring(ctx context.Context, sel ast.SelectionSet, v []*string) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalOString2ᚖstring(ctx, sel, v[i]) - } - - return ret -} - -func (ec *executionContext) unmarshalOString2ᚖstring(ctx context.Context, v interface{}) (*string, error) { - if v == nil { - return nil, nil - } - res, err := graphql.UnmarshalString(v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalOString2ᚖstring(ctx context.Context, sel ast.SelectionSet, v *string) graphql.Marshaler { - if v == nil { - return graphql.Null - } - res := graphql.MarshalString(*v) - return res -} - -func (ec *executionContext) marshalOUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserAuthTokenᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.UserAuthToken) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNUserAuthToken2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserAuthToken(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalOUserInfo2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐUserInfo(ctx context.Context, sel ast.SelectionSet, v *model.UserInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._UserInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalOWebServiceConfig2ᚕᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐWebServiceConfig(ctx context.Context, sel ast.SelectionSet, v []*model.WebServiceConfig) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalOWebServiceConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐWebServiceConfig(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - return ret -} - -func (ec *executionContext) marshalOWebServiceConfig2ᚖgithubᚗcomᚋactiontechᚋsqleᚋsqleᚋapiᚋcloudbeaver_wrapperᚋgraphᚋmodelᚐWebServiceConfig(ctx context.Context, sel ast.SelectionSet, v *model.WebServiceConfig) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._WebServiceConfig(ctx, sel, v) -} - -func (ec *executionContext) marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.EnumValue) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__EnumValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValue(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Field) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__Field2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐField(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx context.Context, sel ast.SelectionSet, v *introspection.Schema) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec.___Schema(ctx, sel, v) -} - -func (ec *executionContext) marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec.___Type(ctx, sel, v) -} - -// endregion ***************************** type.gotpl ***************************** diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/resolver.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/resolver.go deleted file mode 100644 index 14b7bf3412..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/resolver.go +++ /dev/null @@ -1,15 +0,0 @@ -package resolver - -// This file will not be regenerated automatically. -// -// It serves as dependency injection for your app, add any dependencies you require here. - -type Resolver struct{} - -type MutationResolverImpl struct { - *mutationResolver -} - -type QueryResolverImpl struct { - *queryResolver -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/schema_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/schema_gen.go deleted file mode 100644 index c9ef8df5a0..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/schema_gen.go +++ /dev/null @@ -1,13 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -// Mutation returns MutationResolver implementation. -func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} } - -// Query returns QueryResolver implementation. -func (r *Resolver) Query() QueryResolver { return &queryResolver{r} } - -type mutationResolver struct{ *Resolver } -type queryResolver struct{ *Resolver } diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.admin_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/service.admin_gen.go deleted file mode 100644 index b258d72dda..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.admin_gen.go +++ /dev/null @@ -1,176 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - "fmt" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" -) - -// ListUsers is the resolver for the listUsers field. -func (r *queryResolver) ListUsers(ctx context.Context, userID *string) ([]*model.AdminUserInfo, error) { - panic(fmt.Errorf("not implemented: ListUsers - listUsers")) -} - -// ListRoles is the resolver for the listRoles field. -func (r *queryResolver) ListRoles(ctx context.Context, roleID *string) ([]*model.AdminRoleInfo, error) { - panic(fmt.Errorf("not implemented: ListRoles - listRoles")) -} - -// ListPermissions is the resolver for the listPermissions field. -func (r *queryResolver) ListPermissions(ctx context.Context) ([]*model.AdminPermissionInfo, error) { - panic(fmt.Errorf("not implemented: ListPermissions - listPermissions")) -} - -// CreateUser is the resolver for the createUser field. -func (r *queryResolver) CreateUser(ctx context.Context, userID string) (*model.AdminUserInfo, error) { - panic(fmt.Errorf("not implemented: CreateUser - createUser")) -} - -// DeleteUser is the resolver for the deleteUser field. -func (r *queryResolver) DeleteUser(ctx context.Context, userID string) (*bool, error) { - panic(fmt.Errorf("not implemented: DeleteUser - deleteUser")) -} - -// CreateRole is the resolver for the createRole field. -func (r *queryResolver) CreateRole(ctx context.Context, roleID string, roleName *string, description *string) (*model.AdminRoleInfo, error) { - panic(fmt.Errorf("not implemented: CreateRole - createRole")) -} - -// UpdateRole is the resolver for the updateRole field. -func (r *queryResolver) UpdateRole(ctx context.Context, roleID string, roleName *string, description *string) (*model.AdminRoleInfo, error) { - panic(fmt.Errorf("not implemented: UpdateRole - updateRole")) -} - -// DeleteRole is the resolver for the deleteRole field. -func (r *queryResolver) DeleteRole(ctx context.Context, roleID string) (*bool, error) { - panic(fmt.Errorf("not implemented: DeleteRole - deleteRole")) -} - -// GrantUserRole is the resolver for the grantUserRole field. -func (r *queryResolver) GrantUserRole(ctx context.Context, userID string, roleID string) (*bool, error) { - panic(fmt.Errorf("not implemented: GrantUserRole - grantUserRole")) -} - -// RevokeUserRole is the resolver for the revokeUserRole field. -func (r *queryResolver) RevokeUserRole(ctx context.Context, userID string, roleID string) (*bool, error) { - panic(fmt.Errorf("not implemented: RevokeUserRole - revokeUserRole")) -} - -// SetSubjectPermissions is the resolver for the setSubjectPermissions field. -func (r *queryResolver) SetSubjectPermissions(ctx context.Context, roleID string, permissions []string) ([]*model.AdminPermissionInfo, error) { - panic(fmt.Errorf("not implemented: SetSubjectPermissions - setSubjectPermissions")) -} - -// SetUserCredentials is the resolver for the setUserCredentials field. -func (r *queryResolver) SetUserCredentials(ctx context.Context, userID string, providerID string, credentials interface{}) (*bool, error) { - panic(fmt.Errorf("not implemented: SetUserCredentials - setUserCredentials")) -} - -// EnableUser is the resolver for the enableUser field. -func (r *queryResolver) EnableUser(ctx context.Context, userID string, enabled bool) (*bool, error) { - panic(fmt.Errorf("not implemented: EnableUser - enableUser")) -} - -// AllConnections is the resolver for the allConnections field. -func (r *queryResolver) AllConnections(ctx context.Context, id *string) ([]*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: AllConnections - allConnections")) -} - -// SearchConnections is the resolver for the searchConnections field. -func (r *queryResolver) SearchConnections(ctx context.Context, hostNames []string) ([]*model.AdminConnectionSearchInfo, error) { - panic(fmt.Errorf("not implemented: SearchConnections - searchConnections")) -} - -// CreateConnectionConfiguration is the resolver for the createConnectionConfiguration field. -func (r *queryResolver) CreateConnectionConfiguration(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CreateConnectionConfiguration - createConnectionConfiguration")) -} - -// CopyConnectionConfiguration is the resolver for the copyConnectionConfiguration field. -func (r *queryResolver) CopyConnectionConfiguration(ctx context.Context, nodePath string, config *model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CopyConnectionConfiguration - copyConnectionConfiguration")) -} - -// UpdateConnectionConfiguration is the resolver for the updateConnectionConfiguration field. -func (r *queryResolver) UpdateConnectionConfiguration(ctx context.Context, id string, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: UpdateConnectionConfiguration - updateConnectionConfiguration")) -} - -// DeleteConnectionConfiguration is the resolver for the deleteConnectionConfiguration field. -func (r *queryResolver) DeleteConnectionConfiguration(ctx context.Context, id string) (*bool, error) { - panic(fmt.Errorf("not implemented: DeleteConnectionConfiguration - deleteConnectionConfiguration")) -} - -// GetConnectionSubjectAccess is the resolver for the getConnectionSubjectAccess field. -func (r *queryResolver) GetConnectionSubjectAccess(ctx context.Context, connectionID *string) ([]*model.AdminConnectionGrantInfo, error) { - panic(fmt.Errorf("not implemented: GetConnectionSubjectAccess - getConnectionSubjectAccess")) -} - -// SetConnectionSubjectAccess is the resolver for the setConnectionSubjectAccess field. -func (r *queryResolver) SetConnectionSubjectAccess(ctx context.Context, connectionID string, subjects []string) (*bool, error) { - panic(fmt.Errorf("not implemented: SetConnectionSubjectAccess - setConnectionSubjectAccess")) -} - -// GetSubjectConnectionAccess is the resolver for the getSubjectConnectionAccess field. -func (r *queryResolver) GetSubjectConnectionAccess(ctx context.Context, subjectID *string) ([]*model.AdminConnectionGrantInfo, error) { - panic(fmt.Errorf("not implemented: GetSubjectConnectionAccess - getSubjectConnectionAccess")) -} - -// SetSubjectConnectionAccess is the resolver for the setSubjectConnectionAccess field. -func (r *queryResolver) SetSubjectConnectionAccess(ctx context.Context, subjectID string, connections []string) (*bool, error) { - panic(fmt.Errorf("not implemented: SetSubjectConnectionAccess - setSubjectConnectionAccess")) -} - -// ListFeatureSets is the resolver for the listFeatureSets field. -func (r *queryResolver) ListFeatureSets(ctx context.Context) ([]*model.WebFeatureSet, error) { - panic(fmt.Errorf("not implemented: ListFeatureSets - listFeatureSets")) -} - -// ListAuthProviderConfigurationParameters is the resolver for the listAuthProviderConfigurationParameters field. -func (r *queryResolver) ListAuthProviderConfigurationParameters(ctx context.Context, providerID string) ([]*model.ObjectPropertyInfo, error) { - panic(fmt.Errorf("not implemented: ListAuthProviderConfigurationParameters - listAuthProviderConfigurationParameters")) -} - -// ListAuthProviderConfigurations is the resolver for the listAuthProviderConfigurations field. -func (r *queryResolver) ListAuthProviderConfigurations(ctx context.Context, providerID *string) ([]*model.AdminAuthProviderConfiguration, error) { - panic(fmt.Errorf("not implemented: ListAuthProviderConfigurations - listAuthProviderConfigurations")) -} - -// SaveAuthProviderConfiguration is the resolver for the saveAuthProviderConfiguration field. -func (r *queryResolver) SaveAuthProviderConfiguration(ctx context.Context, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters interface{}) (*model.AdminAuthProviderConfiguration, error) { - panic(fmt.Errorf("not implemented: SaveAuthProviderConfiguration - saveAuthProviderConfiguration")) -} - -// DeleteAuthProviderConfiguration is the resolver for the deleteAuthProviderConfiguration field. -func (r *queryResolver) DeleteAuthProviderConfiguration(ctx context.Context, id string) (bool, error) { - panic(fmt.Errorf("not implemented: DeleteAuthProviderConfiguration - deleteAuthProviderConfiguration")) -} - -// SaveUserMetaParameter is the resolver for the saveUserMetaParameter field. -func (r *queryResolver) SaveUserMetaParameter(ctx context.Context, id string, displayName string, description *string, required bool) (*model.ObjectPropertyInfo, error) { - panic(fmt.Errorf("not implemented: SaveUserMetaParameter - saveUserMetaParameter")) -} - -// DeleteUserMetaParameter is the resolver for the deleteUserMetaParameter field. -func (r *queryResolver) DeleteUserMetaParameter(ctx context.Context, id string) (bool, error) { - panic(fmt.Errorf("not implemented: DeleteUserMetaParameter - deleteUserMetaParameter")) -} - -// SetUserMetaParameterValues is the resolver for the setUserMetaParameterValues field. -func (r *queryResolver) SetUserMetaParameterValues(ctx context.Context, userID string, parameters interface{}) (bool, error) { - panic(fmt.Errorf("not implemented: SetUserMetaParameterValues - setUserMetaParameterValues")) -} - -// ConfigureServer is the resolver for the configureServer field. -func (r *queryResolver) ConfigureServer(ctx context.Context, configuration model.ServerConfigInput) (bool, error) { - panic(fmt.Errorf("not implemented: ConfigureServer - configureServer")) -} - -// SetDefaultNavigatorSettings is the resolver for the setDefaultNavigatorSettings field. -func (r *queryResolver) SetDefaultNavigatorSettings(ctx context.Context, settings model.NavigatorSettingsInput) (bool, error) { - panic(fmt.Errorf("not implemented: SetDefaultNavigatorSettings - setDefaultNavigatorSettings")) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.auth_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/service.auth_gen.go deleted file mode 100644 index 8e90beeb03..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.auth_gen.go +++ /dev/null @@ -1,51 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - "fmt" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" -) - -// SetUserConfigurationParameter is the resolver for the setUserConfigurationParameter field. -func (r *mutationResolver) SetUserConfigurationParameter(ctx context.Context, name string, value interface{}) (bool, error) { - panic(fmt.Errorf("not implemented: SetUserConfigurationParameter - setUserConfigurationParameter")) -} - -// AuthLogin is the resolver for the authLogin field. -func (r *queryResolver) AuthLogin(ctx context.Context, provider string, configuration *string, credentials interface{}, linkUser *bool) (*model.AuthInfo, error) { - panic(fmt.Errorf("not implemented: AuthLogin - authLogin")) -} - -// AuthUpdateStatus is the resolver for the authUpdateStatus field. -func (r *queryResolver) AuthUpdateStatus(ctx context.Context, authID string, linkUser *bool) (*model.AuthInfo, error) { - panic(fmt.Errorf("not implemented: AuthUpdateStatus - authUpdateStatus")) -} - -// AuthLogout is the resolver for the authLogout field. -func (r *queryResolver) AuthLogout(ctx context.Context, provider *string, configuration *string) (*bool, error) { - panic(fmt.Errorf("not implemented: AuthLogout - authLogout")) -} - -// ActiveUser is the resolver for the activeUser field. -func (r *queryResolver) ActiveUser(ctx context.Context) (*model.UserInfo, error) { - panic(fmt.Errorf("not implemented: ActiveUser - activeUser")) -} - -// AuthProviders is the resolver for the authProviders field. -func (r *queryResolver) AuthProviders(ctx context.Context) ([]*model.AuthProviderInfo, error) { - panic(fmt.Errorf("not implemented: AuthProviders - authProviders")) -} - -// AuthChangeLocalPassword is the resolver for the authChangeLocalPassword field. -func (r *queryResolver) AuthChangeLocalPassword(ctx context.Context, oldPassword string, newPassword string) (bool, error) { - panic(fmt.Errorf("not implemented: AuthChangeLocalPassword - authChangeLocalPassword")) -} - -// ListUserProfileProperties is the resolver for the listUserProfileProperties field. -func (r *queryResolver) ListUserProfileProperties(ctx context.Context) ([]*model.ObjectPropertyInfo, error) { - panic(fmt.Errorf("not implemented: ListUserProfileProperties - listUserProfileProperties")) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.core_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/service.core_gen.go deleted file mode 100644 index 7ce45368fa..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.core_gen.go +++ /dev/null @@ -1,176 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - "fmt" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" -) - -// OpenSession is the resolver for the openSession field. -func (r *mutationResolver) OpenSession(ctx context.Context, defaultLocale *string) (*model.SessionInfo, error) { - panic(fmt.Errorf("not implemented: OpenSession - openSession")) -} - -// CloseSession is the resolver for the closeSession field. -func (r *mutationResolver) CloseSession(ctx context.Context) (*bool, error) { - panic(fmt.Errorf("not implemented: CloseSession - closeSession")) -} - -// TouchSession is the resolver for the touchSession field. -func (r *mutationResolver) TouchSession(ctx context.Context) (*bool, error) { - panic(fmt.Errorf("not implemented: TouchSession - touchSession")) -} - -// RefreshSessionConnections is the resolver for the refreshSessionConnections field. -func (r *mutationResolver) RefreshSessionConnections(ctx context.Context) (*bool, error) { - panic(fmt.Errorf("not implemented: RefreshSessionConnections - refreshSessionConnections")) -} - -// ChangeSessionLanguage is the resolver for the changeSessionLanguage field. -func (r *mutationResolver) ChangeSessionLanguage(ctx context.Context, locale *string) (*bool, error) { - panic(fmt.Errorf("not implemented: ChangeSessionLanguage - changeSessionLanguage")) -} - -// CreateConnection is the resolver for the createConnection field. -func (r *mutationResolver) CreateConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CreateConnection - createConnection")) -} - -// UpdateConnection is the resolver for the updateConnection field. -func (r *mutationResolver) UpdateConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: UpdateConnection - updateConnection")) -} - -// DeleteConnection is the resolver for the deleteConnection field. -func (r *mutationResolver) DeleteConnection(ctx context.Context, id string) (bool, error) { - panic(fmt.Errorf("not implemented: DeleteConnection - deleteConnection")) -} - -// CreateConnectionFromTemplate is the resolver for the createConnectionFromTemplate field. -func (r *mutationResolver) CreateConnectionFromTemplate(ctx context.Context, templateID string, connectionName *string) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CreateConnectionFromTemplate - createConnectionFromTemplate")) -} - -// CreateConnectionFolder is the resolver for the createConnectionFolder field. -func (r *mutationResolver) CreateConnectionFolder(ctx context.Context, parentFolderPath *string, folderName string) (*model.ConnectionFolderInfo, error) { - panic(fmt.Errorf("not implemented: CreateConnectionFolder - createConnectionFolder")) -} - -// DeleteConnectionFolder is the resolver for the deleteConnectionFolder field. -func (r *mutationResolver) DeleteConnectionFolder(ctx context.Context, folderPath string) (bool, error) { - panic(fmt.Errorf("not implemented: DeleteConnectionFolder - deleteConnectionFolder")) -} - -// CopyConnectionFromNode is the resolver for the copyConnectionFromNode field. -func (r *mutationResolver) CopyConnectionFromNode(ctx context.Context, nodePath string, config *model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CopyConnectionFromNode - copyConnectionFromNode")) -} - -// TestConnection is the resolver for the testConnection field. -func (r *mutationResolver) TestConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: TestConnection - testConnection")) -} - -// TestNetworkHandler is the resolver for the testNetworkHandler field. -func (r *mutationResolver) TestNetworkHandler(ctx context.Context, config model.NetworkHandlerConfigInput) (*model.NetworkEndpointInfo, error) { - panic(fmt.Errorf("not implemented: TestNetworkHandler - testNetworkHandler")) -} - -// InitConnection is the resolver for the initConnection field. -func (r *mutationResolver) InitConnection(ctx context.Context, id string, credentials interface{}, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: InitConnection - initConnection")) -} - -// CloseConnection is the resolver for the closeConnection field. -func (r *mutationResolver) CloseConnection(ctx context.Context, id string) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CloseConnection - closeConnection")) -} - -// SetConnectionNavigatorSettings is the resolver for the setConnectionNavigatorSettings field. -func (r *mutationResolver) SetConnectionNavigatorSettings(ctx context.Context, id string, settings model.NavigatorSettingsInput) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: SetConnectionNavigatorSettings - setConnectionNavigatorSettings")) -} - -// AsyncTaskCancel is the resolver for the asyncTaskCancel field. -func (r *mutationResolver) AsyncTaskCancel(ctx context.Context, id string) (*bool, error) { - panic(fmt.Errorf("not implemented: AsyncTaskCancel - asyncTaskCancel")) -} - -// AsyncTaskInfo is the resolver for the asyncTaskInfo field. -func (r *mutationResolver) AsyncTaskInfo(ctx context.Context, id string, removeOnFinish bool) (*model.AsyncTaskInfo, error) { - panic(fmt.Errorf("not implemented: AsyncTaskInfo - asyncTaskInfo")) -} - -// OpenConnection is the resolver for the openConnection field. -func (r *mutationResolver) OpenConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: OpenConnection - openConnection")) -} - -// AsyncTaskStatus is the resolver for the asyncTaskStatus field. -func (r *mutationResolver) AsyncTaskStatus(ctx context.Context, id string) (*model.AsyncTaskInfo, error) { - panic(fmt.Errorf("not implemented: AsyncTaskStatus - asyncTaskStatus")) -} - -// ServerConfig is the resolver for the serverConfig field. -func (r *queryResolver) ServerConfig(ctx context.Context) (*model.ServerConfig, error) { - panic(fmt.Errorf("not implemented: ServerConfig - serverConfig")) -} - -// SessionState is the resolver for the sessionState field. -func (r *queryResolver) SessionState(ctx context.Context) (*model.SessionInfo, error) { - panic(fmt.Errorf("not implemented: SessionState - sessionState")) -} - -// SessionPermissions is the resolver for the sessionPermissions field. -func (r *queryResolver) SessionPermissions(ctx context.Context) ([]*string, error) { - panic(fmt.Errorf("not implemented: SessionPermissions - sessionPermissions")) -} - -// DriverList is the resolver for the driverList field. -func (r *queryResolver) DriverList(ctx context.Context, id *string) ([]*model.DriverInfo, error) { - panic(fmt.Errorf("not implemented: DriverList - driverList")) -} - -// AuthModels is the resolver for the authModels field. -func (r *queryResolver) AuthModels(ctx context.Context) ([]*model.DatabaseAuthModel, error) { - panic(fmt.Errorf("not implemented: AuthModels - authModels")) -} - -// NetworkHandlers is the resolver for the networkHandlers field. -func (r *queryResolver) NetworkHandlers(ctx context.Context) ([]*model.NetworkHandlerDescriptor, error) { - panic(fmt.Errorf("not implemented: NetworkHandlers - networkHandlers")) -} - -// UserConnections is the resolver for the userConnections field. -func (r *queryResolver) UserConnections(ctx context.Context, id *string) ([]*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: UserConnections - userConnections")) -} - -// TemplateConnections is the resolver for the templateConnections field. -func (r *queryResolver) TemplateConnections(ctx context.Context) ([]*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: TemplateConnections - templateConnections")) -} - -// ConnectionFolders is the resolver for the connectionFolders field. -func (r *queryResolver) ConnectionFolders(ctx context.Context, path *string) ([]*model.ConnectionFolderInfo, error) { - panic(fmt.Errorf("not implemented: ConnectionFolders - connectionFolders")) -} - -// ConnectionState is the resolver for the connectionState field. -func (r *queryResolver) ConnectionState(ctx context.Context, id string) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: ConnectionState - connectionState")) -} - -// ConnectionInfo is the resolver for the connectionInfo field. -func (r *queryResolver) ConnectionInfo(ctx context.Context, id string) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: ConnectionInfo - connectionInfo")) -} - -// ReadSessionLog is the resolver for the readSessionLog field. -func (r *queryResolver) ReadSessionLog(ctx context.Context, maxEntries *int, clearEntries *bool) ([]*model.LogEntry, error) { - panic(fmt.Errorf("not implemented: ReadSessionLog - readSessionLog")) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.data.transfer_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/service.data.transfer_gen.go deleted file mode 100644 index eb1903f5eb..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.data.transfer_gen.go +++ /dev/null @@ -1,31 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - "fmt" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" -) - -// DataTransferAvailableStreamProcessors is the resolver for the dataTransferAvailableStreamProcessors field. -func (r *queryResolver) DataTransferAvailableStreamProcessors(ctx context.Context) ([]*model.DataTransferProcessorInfo, error) { - panic(fmt.Errorf("not implemented: DataTransferAvailableStreamProcessors - dataTransferAvailableStreamProcessors")) -} - -// DataTransferExportDataFromContainer is the resolver for the dataTransferExportDataFromContainer field. -func (r *queryResolver) DataTransferExportDataFromContainer(ctx context.Context, connectionID string, containerNodePath string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) { - panic(fmt.Errorf("not implemented: DataTransferExportDataFromContainer - dataTransferExportDataFromContainer")) -} - -// DataTransferExportDataFromResults is the resolver for the dataTransferExportDataFromResults field. -func (r *queryResolver) DataTransferExportDataFromResults(ctx context.Context, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) { - panic(fmt.Errorf("not implemented: DataTransferExportDataFromResults - dataTransferExportDataFromResults")) -} - -// DataTransferRemoveDataFile is the resolver for the dataTransferRemoveDataFile field. -func (r *queryResolver) DataTransferRemoveDataFile(ctx context.Context, dataFileID string) (*bool, error) { - panic(fmt.Errorf("not implemented: DataTransferRemoveDataFile - dataTransferRemoveDataFile")) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.metadata_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/service.metadata_gen.go deleted file mode 100644 index 501ac2fe15..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.metadata_gen.go +++ /dev/null @@ -1,14 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - "fmt" -) - -// MetadataGetNodeDdl is the resolver for the metadataGetNodeDDL field. -func (r *queryResolver) MetadataGetNodeDdl(ctx context.Context, nodeID string, options interface{}) (*string, error) { - panic(fmt.Errorf("not implemented: MetadataGetNodeDdl - metadataGetNodeDDL")) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.navigator_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/service.navigator_gen.go deleted file mode 100644 index 55cd069112..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.navigator_gen.go +++ /dev/null @@ -1,51 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - "fmt" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" -) - -// NavRenameNode is the resolver for the navRenameNode field. -func (r *mutationResolver) NavRenameNode(ctx context.Context, nodePath string, newName string) (*string, error) { - panic(fmt.Errorf("not implemented: NavRenameNode - navRenameNode")) -} - -// NavDeleteNodes is the resolver for the navDeleteNodes field. -func (r *mutationResolver) NavDeleteNodes(ctx context.Context, nodePaths []string) (*int, error) { - panic(fmt.Errorf("not implemented: NavDeleteNodes - navDeleteNodes")) -} - -// NavMoveNodesToFolder is the resolver for the navMoveNodesToFolder field. -func (r *mutationResolver) NavMoveNodesToFolder(ctx context.Context, nodePaths []string, folderPath string) (*bool, error) { - panic(fmt.Errorf("not implemented: NavMoveNodesToFolder - navMoveNodesToFolder")) -} - -// NavNodeChildren is the resolver for the navNodeChildren field. -func (r *queryResolver) NavNodeChildren(ctx context.Context, parentPath string, offset *int, limit *int, onlyFolders *bool) ([]*model.NavigatorNodeInfo, error) { - panic(fmt.Errorf("not implemented: NavNodeChildren - navNodeChildren")) -} - -// NavNodeParents is the resolver for the navNodeParents field. -func (r *queryResolver) NavNodeParents(ctx context.Context, nodePath string) ([]*model.NavigatorNodeInfo, error) { - panic(fmt.Errorf("not implemented: NavNodeParents - navNodeParents")) -} - -// NavNodeInfo is the resolver for the navNodeInfo field. -func (r *queryResolver) NavNodeInfo(ctx context.Context, nodePath string) (*model.NavigatorNodeInfo, error) { - panic(fmt.Errorf("not implemented: NavNodeInfo - navNodeInfo")) -} - -// NavRefreshNode is the resolver for the navRefreshNode field. -func (r *queryResolver) NavRefreshNode(ctx context.Context, nodePath string) (*bool, error) { - panic(fmt.Errorf("not implemented: NavRefreshNode - navRefreshNode")) -} - -// NavGetStructContainers is the resolver for the navGetStructContainers field. -func (r *queryResolver) NavGetStructContainers(ctx context.Context, connectionID string, contextID *string, catalog *string) (*model.DatabaseStructContainers, error) { - panic(fmt.Errorf("not implemented: NavGetStructContainers - navGetStructContainers")) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.rm_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/service.rm_gen.go deleted file mode 100644 index f1721e4836..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.rm_gen.go +++ /dev/null @@ -1,46 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - "fmt" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" -) - -// RmCreateResource is the resolver for the rmCreateResource field. -func (r *mutationResolver) RmCreateResource(ctx context.Context, projectID string, resourcePath string, isFolder bool) (string, error) { - panic(fmt.Errorf("not implemented: RmCreateResource - rmCreateResource")) -} - -// RmMoveResource is the resolver for the rmMoveResource field. -func (r *mutationResolver) RmMoveResource(ctx context.Context, projectID string, oldResourcePath string, newResourcePath *string) (string, error) { - panic(fmt.Errorf("not implemented: RmMoveResource - rmMoveResource")) -} - -// RmDeleteResource is the resolver for the rmDeleteResource field. -func (r *mutationResolver) RmDeleteResource(ctx context.Context, projectID string, resourcePath string, recursive bool) (*bool, error) { - panic(fmt.Errorf("not implemented: RmDeleteResource - rmDeleteResource")) -} - -// RmWriteResourceStringContent is the resolver for the rmWriteResourceStringContent field. -func (r *mutationResolver) RmWriteResourceStringContent(ctx context.Context, projectID string, resourcePath string, data string) (string, error) { - panic(fmt.Errorf("not implemented: RmWriteResourceStringContent - rmWriteResourceStringContent")) -} - -// RmListProjects is the resolver for the rmListProjects field. -func (r *queryResolver) RmListProjects(ctx context.Context) ([]*model.RMProject, error) { - panic(fmt.Errorf("not implemented: RmListProjects - rmListProjects")) -} - -// RmListResources is the resolver for the rmListResources field. -func (r *queryResolver) RmListResources(ctx context.Context, projectID string, folder *string, nameMask *string, readProperties *bool, readHistory *bool) ([]*model.RMResource, error) { - panic(fmt.Errorf("not implemented: RmListResources - rmListResources")) -} - -// RmReadResourceAsString is the resolver for the rmReadResourceAsString field. -func (r *queryResolver) RmReadResourceAsString(ctx context.Context, projectID string, resourcePath string) (string, error) { - panic(fmt.Errorf("not implemented: RmReadResourceAsString - rmReadResourceAsString")) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.sql_gen.go b/sqle/api/cloudbeaver_wrapper/graph/resolver/service.sql_gen.go deleted file mode 100644 index 4529d12bb9..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/resolver/service.sql_gen.go +++ /dev/null @@ -1,116 +0,0 @@ -package resolver - -// This file will be automatically regenerated based on the schema, any resolver implementations -// will be copied through when generating and any unknown code will be moved to the end. - -import ( - "context" - "fmt" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" -) - -// SQLContextCreate is the resolver for the sqlContextCreate field. -func (r *mutationResolver) SQLContextCreate(ctx context.Context, connectionID string, defaultCatalog *string, defaultSchema *string) (*model.SQLContextInfo, error) { - panic(fmt.Errorf("not implemented: SQLContextCreate - sqlContextCreate")) -} - -// SQLContextSetDefaults is the resolver for the sqlContextSetDefaults field. -func (r *mutationResolver) SQLContextSetDefaults(ctx context.Context, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) (bool, error) { - panic(fmt.Errorf("not implemented: SQLContextSetDefaults - sqlContextSetDefaults")) -} - -// SQLContextDestroy is the resolver for the sqlContextDestroy field. -func (r *mutationResolver) SQLContextDestroy(ctx context.Context, connectionID string, contextID string) (bool, error) { - panic(fmt.Errorf("not implemented: SQLContextDestroy - sqlContextDestroy")) -} - -// AsyncSQLExecuteQuery is the resolver for the asyncSqlExecuteQuery field. -func (r *mutationResolver) AsyncSQLExecuteQuery(ctx context.Context, projectID *string, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat, readLogs *bool) (*model.AsyncTaskInfo, error) { - panic(fmt.Errorf("not implemented: AsyncSQLExecuteQuery - asyncSqlExecuteQuery")) -} - -// AsyncReadDataFromContainer is the resolver for the asyncReadDataFromContainer field. -func (r *mutationResolver) AsyncReadDataFromContainer(ctx context.Context, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) { - panic(fmt.Errorf("not implemented: AsyncReadDataFromContainer - asyncReadDataFromContainer")) -} - -// SQLResultClose is the resolver for the sqlResultClose field. -func (r *mutationResolver) SQLResultClose(ctx context.Context, connectionID string, contextID string, resultID string) (bool, error) { - panic(fmt.Errorf("not implemented: SQLResultClose - sqlResultClose")) -} - -// UpdateResultsDataBatch is the resolver for the updateResultsDataBatch field. -func (r *mutationResolver) UpdateResultsDataBatch(ctx context.Context, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (*model.SQLExecuteInfo, error) { - panic(fmt.Errorf("not implemented: UpdateResultsDataBatch - updateResultsDataBatch")) -} - -// UpdateResultsDataBatchScript is the resolver for the updateResultsDataBatchScript field. -func (r *mutationResolver) UpdateResultsDataBatchScript(ctx context.Context, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (string, error) { - panic(fmt.Errorf("not implemented: UpdateResultsDataBatchScript - updateResultsDataBatchScript")) -} - -// ReadLobValue is the resolver for the readLobValue field. -func (r *mutationResolver) ReadLobValue(ctx context.Context, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) (string, error) { - panic(fmt.Errorf("not implemented: ReadLobValue - readLobValue")) -} - -// AsyncSQLExecuteResults is the resolver for the asyncSqlExecuteResults field. -func (r *mutationResolver) AsyncSQLExecuteResults(ctx context.Context, taskID string) (*model.SQLExecuteInfo, error) { - panic(fmt.Errorf("not implemented: AsyncSQLExecuteResults - asyncSqlExecuteResults")) -} - -// AsyncSQLExplainExecutionPlan is the resolver for the asyncSqlExplainExecutionPlan field. -func (r *mutationResolver) AsyncSQLExplainExecutionPlan(ctx context.Context, connectionID string, contextID string, query string, configuration interface{}) (*model.AsyncTaskInfo, error) { - panic(fmt.Errorf("not implemented: AsyncSQLExplainExecutionPlan - asyncSqlExplainExecutionPlan")) -} - -// AsyncSQLExplainExecutionPlanResult is the resolver for the asyncSqlExplainExecutionPlanResult field. -func (r *mutationResolver) AsyncSQLExplainExecutionPlanResult(ctx context.Context, taskID string) (*model.SQLExecutionPlan, error) { - panic(fmt.Errorf("not implemented: AsyncSQLExplainExecutionPlanResult - asyncSqlExplainExecutionPlanResult")) -} - -// SQLDialectInfo is the resolver for the sqlDialectInfo field. -func (r *queryResolver) SQLDialectInfo(ctx context.Context, connectionID string) (*model.SQLDialectInfo, error) { - panic(fmt.Errorf("not implemented: SQLDialectInfo - sqlDialectInfo")) -} - -// SQLListContexts is the resolver for the sqlListContexts field. -func (r *queryResolver) SQLListContexts(ctx context.Context, connectionID *string, contextID *string) ([]*model.SQLContextInfo, error) { - panic(fmt.Errorf("not implemented: SQLListContexts - sqlListContexts")) -} - -// SQLCompletionProposals is the resolver for the sqlCompletionProposals field. -func (r *queryResolver) SQLCompletionProposals(ctx context.Context, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) ([]*model.SQLCompletionProposal, error) { - panic(fmt.Errorf("not implemented: SQLCompletionProposals - sqlCompletionProposals")) -} - -// SQLFormatQuery is the resolver for the sqlFormatQuery field. -func (r *queryResolver) SQLFormatQuery(ctx context.Context, connectionID string, contextID string, query string) (string, error) { - panic(fmt.Errorf("not implemented: SQLFormatQuery - sqlFormatQuery")) -} - -// SQLSupportedOperations is the resolver for the sqlSupportedOperations field. -func (r *queryResolver) SQLSupportedOperations(ctx context.Context, connectionID string, contextID string, resultsID string, attributeIndex int) ([]*model.DataTypeLogicalOperation, error) { - panic(fmt.Errorf("not implemented: SQLSupportedOperations - sqlSupportedOperations")) -} - -// SQLEntityQueryGenerators is the resolver for the sqlEntityQueryGenerators field. -func (r *queryResolver) SQLEntityQueryGenerators(ctx context.Context, nodePathList []string) ([]*model.SQLQueryGenerator, error) { - panic(fmt.Errorf("not implemented: SQLEntityQueryGenerators - sqlEntityQueryGenerators")) -} - -// SQLGenerateEntityQuery is the resolver for the sqlGenerateEntityQuery field. -func (r *queryResolver) SQLGenerateEntityQuery(ctx context.Context, generatorID string, options interface{}, nodePathList []string) (string, error) { - panic(fmt.Errorf("not implemented: SQLGenerateEntityQuery - sqlGenerateEntityQuery")) -} - -// SQLParseScript is the resolver for the sqlParseScript field. -func (r *queryResolver) SQLParseScript(ctx context.Context, connectionID string, script string) (*model.SQLScriptInfo, error) { - panic(fmt.Errorf("not implemented: SQLParseScript - sqlParseScript")) -} - -// SQLParseQuery is the resolver for the sqlParseQuery field. -func (r *queryResolver) SQLParseQuery(ctx context.Context, connectionID string, script string, position int) (*model.SQLScriptQuery, error) { - panic(fmt.Errorf("not implemented: SQLParseQuery - sqlParseQuery")) -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/schema.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/schema.graphqls deleted file mode 100644 index a3dee4ffa5..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/schema.graphqls +++ /dev/null @@ -1,13 +0,0 @@ -# Any object (JSON) -scalar Object -# Date/Time -scalar DateTime - -type Query - -type Mutation - -schema { - query: Query - mutation: Mutation -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/service.admin.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/service.admin.graphqls deleted file mode 100644 index db85a8cb99..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/service.admin.graphqls +++ /dev/null @@ -1,181 +0,0 @@ - -enum AdminSubjectType { - user, - role -} - -type AdminConnectionGrantInfo { - connectionId: ID! @deprecated(reason: "use dataSourceId instead") - dataSourceId: ID! - subjectId: ID! - subjectType: AdminSubjectType! -} - -type AdminConnectionSearchInfo { - displayName: String! - host: String! - port: Int! - possibleDrivers: [ID!]! - defaultDriver: ID! -} - -type AdminUserInfo { - userId: ID! - - metaParameters: Object! - configurationParameters: Object! - grantedRoles: [ID!]! - grantedConnections: [AdminConnectionGrantInfo!]! - - origins: [ObjectOrigin!]! - - linkedAuthProviders: [String!]! - enabled: Boolean! -} - -type AdminRoleInfo { - roleId: ID! - roleName: String - description: String - - grantedUsers: [ID!]! - grantedConnections: [AdminConnectionGrantInfo!]! - - rolePermissions: [ID!]! -} - -type AdminPermissionInfo { - id: ID! - label: String - description: String - - provider: String! - category: String -} - -type AdminAuthProviderConfiguration { - providerId: ID! - id: ID! - displayName: String! - disabled: Boolean! - - iconURL: String - description: String - - parameters: Object! - - signInLink: String - signOutLink: String - redirectLink: String - metadataLink: String -} - -type WebFeatureSet { - id: String! - label: String! - description: String - icon: String - - enabled: Boolean! -} - -input ServerConfigInput { - serverName: String - serverURL: String - - adminName: String - adminPassword: String - - anonymousAccessEnabled: Boolean - authenticationEnabled: Boolean - customConnectionsEnabled: Boolean - publicCredentialsSaveEnabled: Boolean - adminCredentialsSaveEnabled: Boolean - resourceManagerEnabled: Boolean - - enabledFeatures: [ID!] - enabledAuthProviders: [ID!] - disabledDrivers: [ID!] - - sessionExpireTime: Int -} - -extend type Query { - - #### Users and roles - - listUsers(userId: ID): [AdminUserInfo!]! - listRoles(roleId: ID): [AdminRoleInfo!]! - listPermissions: [AdminPermissionInfo!]! - - createUser(userId: ID!): AdminUserInfo! - deleteUser(userId: ID!): Boolean - - createRole(roleId: ID!, roleName: String, description: String): AdminRoleInfo! - updateRole(roleId: ID!, roleName: String, description: String): AdminRoleInfo! - deleteRole(roleId: ID!): Boolean - - grantUserRole(userId: ID!, roleId: ID!): Boolean - revokeUserRole(userId: ID!, roleId: ID!): Boolean - - setSubjectPermissions(roleId: ID!, permissions: [ID!]!): [AdminPermissionInfo!]! - - setUserCredentials(userId: ID!, providerId: ID!, credentials: Object!): Boolean - - enableUser(userId: ID!, enabled: Boolean!): Boolean - - #### Connection management - - # All connection configurations - allConnections( id: ID ): [ ConnectionInfo! ]! - - searchConnections( hostNames: [String!]! ): [AdminConnectionSearchInfo!]! - - createConnectionConfiguration( config: ConnectionConfig! ): ConnectionInfo! - copyConnectionConfiguration( nodePath: String!, config: ConnectionConfig ): ConnectionInfo! - updateConnectionConfiguration( id: ID!, config: ConnectionConfig! ): ConnectionInfo! - deleteConnectionConfiguration( id: ID! ): Boolean - - # Permissions - - getConnectionSubjectAccess(connectionId: ID): [AdminConnectionGrantInfo!]! - setConnectionSubjectAccess(connectionId: ID!, subjects: [ID!]!): Boolean - - getSubjectConnectionAccess(subjectId: ID): [AdminConnectionGrantInfo!]! - setSubjectConnectionAccess(subjectId: ID!, connections: [ID!]!): Boolean - - #### Feature sets - - listFeatureSets: [WebFeatureSet!]! - - #### Auth providers and configurations - - listAuthProviderConfigurationParameters(providerId: ID!): [ObjectPropertyInfo!]! - listAuthProviderConfigurations(providerId: ID): [AdminAuthProviderConfiguration!]! - - saveAuthProviderConfiguration( - providerId: ID!, - id: ID!, - displayName: String, - disabled: Boolean, - iconURL: String - description: String - parameters: Object): AdminAuthProviderConfiguration! - deleteAuthProviderConfiguration(id: ID!): Boolean! - - #### User profile - - saveUserMetaParameter(id: ID!, displayName: String!, description: String, required: Boolean!): ObjectPropertyInfo! - - deleteUserMetaParameter(id: ID!): Boolean! - - setUserMetaParameterValues(userId: ID!, parameters: Object!): Boolean! - - #### Global configuration - - configureServer(configuration: ServerConfigInput!): Boolean! - - # Changes default navigator settings - setDefaultNavigatorSettings( settings: NavigatorSettingsInput!): Boolean! - -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/service.auth.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/service.auth.graphqls deleted file mode 100644 index e251c227f6..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/service.auth.graphqls +++ /dev/null @@ -1,153 +0,0 @@ -enum AuthCredentialEncryption { - none, - plain, - hash -} - -enum AuthStatus { - SUCCESS, - IN_PROGRESS, - ERROR -} - -type AuthCredentialInfo { - id: ID! - displayName: String! - description: String - - # This field must be shown in admin panel - admin: Boolean! - # This field must be shown in login form - user: Boolean! - # This field can be used as user identifier - - identifying: Boolean! - possibleValues: [String] - encryption: AuthCredentialEncryption -} - -type AuthProviderConfiguration { - id: ID! - displayName: String! - disabled: Boolean! - - iconURL: String - description: String - - # URL to external authentication service. - # If specified then it is external auhentication provider (SSO). - # Otherwise authLogin function must be called. - signInLink: String - signOutLink: String - metadataLink: String -} - -type AuthProviderCredentialsProfile { - id: String - label: String - description: String - credentialParameters: [AuthCredentialInfo!]! -} - -type AuthProviderInfo { - id: ID! - label: String! - icon: ID - description: String - - defaultProvider: Boolean! - - # Configurable providers must be configured first. See configurations field. - configurable: Boolean! - - # Provider configurations (applicable only if configurable=true) - configurations: [AuthProviderConfiguration!] - - credentialProfiles: [AuthProviderCredentialsProfile!]! - - requiredFeatures: [String!]! -} - -type AuthInfo { - redirectLink: String - - authId: String - - authStatus: AuthStatus! - - userTokens: [UserAuthToken!] -} - -type UserAuthToken { - # Auth provider used for authorization - authProvider: ID! - - # Auth provider configuration ID - authConfiguration: ID - - # Authorization time - loginTime: DateTime! - - # User identity (aka user name) specific to auth provider - userId: String! - - # User display name specific to auth provider - displayName: String! - - # Optional login message - message: String - - # Auth origin - origin: ObjectOrigin! - -} - -type UserInfo { - # User unique identifier - userId: ID! - - # Human readable display name. It is taken from the first auth provider which was used for user login. - displayName: String - # User auth role ID. Optional. - authRole: ID - - # All authentication tokens used during current session - authTokens: [UserAuthToken!]! - - linkedAuthProviders: [String!]! - - # User profile properties map - metaParameters: Object! - # User configuration parameters - configurationParameters: Object! - -} - - -extend type Query { - - # Authorize user using specified auth provider. If linkUser=true then associates new - authLogin(provider: ID!, configuration: ID, credentials: Object, linkUser: Boolean): AuthInfo! - - authUpdateStatus(authId: ID!, linkUser: Boolean): AuthInfo! - - # Logouts user. If provider not specified then all authorizations are revoked from session. - authLogout(provider: ID, configuration: ID): Boolean - - # Active user information. null is no user was authorized within session - activeUser: UserInfo - - authProviders: [AuthProviderInfo!]! - - authChangeLocalPassword(oldPassword: String!, newPassword: String!): Boolean! - - listUserProfileProperties: [ObjectPropertyInfo!]! - -} - -extend type Mutation { - - # Set user config parameter. If parameter value is null then removes the parameter - setUserConfigurationParameter(name: String!, value: Object): Boolean! - -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/service.core.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/service.core.graphqls deleted file mode 100644 index 1894c49a2e..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/service.core.graphqls +++ /dev/null @@ -1,540 +0,0 @@ - -#################################################### -# General stuff -#################################################### - -# Property - -type ObjectPropertyInfo { - # ID - id: String - # Human readable name - displayName: String - # Property description - description: String - # Property category (may be used if object has a lot of properties) - category: String - # Property data type (int, String, etc) - dataType: String - - # Property value. Note: for some properties value reading may take a lot of time (e.g. RowCount for tables) - value: Object - - # List of values this property can take. Makes sense only for enumerable properties - validValues: [ Object ] - # Default property value - defaultValue: Object - - # Property value length - length: ObjectPropertyLength! - - # Supported features (system, hidden, inherited, foreign, expensive, etc) - features: [ String! ]! - # Order position - order: Int! -} - -enum ObjectPropertyLength { - # 1 character - TINY, - # 20 characters - SHORT, - # <= 64 characters - MEDIUM, - # Full line length. The default - LONG, - # Multi-line long text - MULTILINE -} - -# Async types - -type AsyncTaskInfo { - id: String! - name: String - running: Boolean! - - status: String - error: ServerError - - result: SQLExecuteInfo @deprecated # Deprecated. Use asyncSqlExecuteResults instead - # Task result. - # Can be some kind of identifier to obtain real result using another API function - taskResult: Object -} - -# Various server errors descriptor - -type ServerError { - message: String - errorCode: String - errorType: String - stackTrace: String - causedBy: ServerError -} - -type ServerMessage { - time: String - message: String -} - -# Languages supported by server - -type ServerLanguage { - isoCode: String! - displayName: String - nativeName: String -} - -type WebServiceConfig { - id: String! - name: String! - description: String! - bundleVersion: String! -} - -type ProductInfo { - id: ID! - version: String! - name: String! - description: String - buildTime: String! - releaseTime: String! - licenseInfo: String - - latestVersionInfo: String -} - -type ServerConfig { - name: String! - version: String! - workspaceId: ID! - - serverURL: String! - - rootURI: String! - - hostName: String! - - anonymousAccessEnabled: Boolean - authenticationEnabled: Boolean @deprecated - supportsCustomConnections: Boolean - supportsConnectionBrowser: Boolean - supportsWorkspaces: Boolean - resourceManagerEnabled: Boolean - - publicCredentialsSaveEnabled: Boolean - adminCredentialsSaveEnabled: Boolean - - licenseRequired: Boolean! - licenseValid: Boolean! - - sessionExpireTime: Int - localHostAddress: String - - configurationMode: Boolean - developmentMode: Boolean - redirectOnFederatedAuth: Boolean - - enabledFeatures: [ID!]! - enabledAuthProviders: [ID!]! - supportedLanguages: [ ServerLanguage! ]! - services: [ WebServiceConfig ] - productConfiguration: Object! - productInfo: ProductInfo! - defaultNavigatorSettings: NavigatorSettings! - disabledDrivers: [ID!]! - resourceQuotas: Object! -} - -type SessionInfo { - createTime: String! - lastAccessTime: String! - locale: String! - - cacheExpired: Boolean! - - serverMessages: [ ServerMessage ] - connections: [ ConnectionInfo! ]! - actionParameters: Object -} - -#################################################### -# Drivers and connections -#################################################### - -type DatabaseAuthModel { - id: ID! - displayName: String! - description: String - icon: String - # checks if the auth model needs a configuration on a local file system - requiresLocalConfiguration: Boolean - - properties: [ObjectPropertyInfo!]! -} - -type DriverInfo { - id: ID! - name: String - description: String - icon: String - iconBig: String - - # Driver provider ID - providerId: ID - # Driver Java class name - driverClassName: String - defaultHost: String - defaultPort: String - defaultDatabase: String - defaultServer: String - defaultUser: String - sampleURL: String - driverInfoURL: String - driverPropertiesURL: String - embedded: Boolean - enabled: Boolean! - requiresServerName: Boolean - - # this fields must be removed and be replaced by DriverAuthModel - allowsEmptyPassword: Boolean @deprecated - - licenseRequired: Boolean - license: String - custom: Boolean - # Driver score for ordering, biggest first - promotedScore: Int - - # Never used? - #connectionProperties: Object - #defaultConnectionProperties: Object - - # Driver properties. - # Note: it is expensive property and it may produce database server roundtrips. - # Call it only when you really need it. - # These properties are for advanced users in usually shouldn't be specified for new connections. - driverProperties: [ObjectPropertyInfo!]! - # Driver parameters (map name->value) - driverParameters: Object! - - # Additional driver provider properties - # These properties can be configured by user on main connection page - # to provide important connection settings - providerProperties: [ObjectPropertyInfo!]! - - # False for drivers which do not support authentication - anonymousAccess: Boolean - - defaultAuthModel: ID! - applicableAuthModels: [ID!]! - - applicableNetworkHandlers: [ID]! -} - -enum ResultDataFormat { - resultset, - document, - graph, - timeseries -} - -## Network handler config - -enum NetworkHandlerType { - TUNNEL, - PROXY, - CONFIG -} - -enum NetworkHandlerAuthType { - PASSWORD, - PUBLIC_KEY, - AGENT -} - -type NetworkHandlerDescriptor { - id: ID! - codeName: String! - label: String! - description: String - secured: Boolean! - type: NetworkHandlerType - properties: [ObjectPropertyInfo!]! -} - -type NetworkHandlerConfig { - id: ID! - enabled: Boolean! - authType: NetworkHandlerAuthType! - userName: String - password: String - key: String - savePassword: Boolean! - properties: Object! -} - -# Connection instance -type ConnectionInfo { - id: ID! - driverId: ID! - - name: String! - description: String - - host: String - port: String - serverName: String - databaseName: String - url: String - - properties: Object - - template: Boolean! - connected: Boolean! - provided: Boolean! - readOnly: Boolean! - useUrl: Boolean! - saveCredentials: Boolean! - - folder: ID - nodePath: String - - connectTime: String - connectionError: ServerError - serverVersion: String - clientVersion: String - - origin: ObjectOrigin! - - authNeeded: Boolean! - authModel: ID - authProperties: [ObjectPropertyInfo!]! - - providerProperties: Object! - networkHandlersConfig: [NetworkHandlerConfig!]! - - # Supported features (provided etc) - features: [ String! ]! - navigatorSettings: NavigatorSettings! - supportedDataFormats: [ ResultDataFormat! ]! -} - -type ConnectionFolderInfo { - id: ID! - description: String -} - -type NetworkEndpointInfo { - message: String - clientVersion: String - serverVersion: String -} - -type ObjectOrigin { - type: ID! - subType: ID - displayName: String! - icon: String - configuration: Object - details: [ObjectPropertyInfo!] -} - -type NavigatorSettings { - showSystemObjects: Boolean! - showUtilityObjects: Boolean! - showOnlyEntities: Boolean! - mergeEntities: Boolean! - hideFolders: Boolean! - hideSchemas: Boolean! - hideVirtualModel: Boolean! -} - -type LogEntry { - time: DateTime - type: String! - message: String - stackTrace: String -} - -#################################################### -# Input types -#################################################### - -input NavigatorSettingsInput { - showSystemObjects: Boolean! - showUtilityObjects: Boolean! - showOnlyEntities: Boolean! - mergeEntities: Boolean! - hideFolders: Boolean! - hideSchemas: Boolean! - hideVirtualModel: Boolean! -} - -input NetworkHandlerConfigInput { - id: ID! - enabled: Boolean - authType: NetworkHandlerAuthType - userName: String - password: String - key: String - savePassword: Boolean - properties: Object -} - -# Configuration of particular connection. Used for new connection create. Includes auth info -input ConnectionConfig { - # used only for testing created connection - connectionId: String - name: String - description: String - - # ID of template connection - templateId: ID - # ID of database driver - driverId: ID - - # Custom connection parameters (all optional) - - host: String - port: String - serverName: String - databaseName: String - # Connection url jdbc:{driver}://{host}[:{port}]/[{database}] - url: String - # Properties - properties: Object - - # Template connection - template: Boolean - # Read-onyl connection - readOnly: Boolean - - # User credentials - - saveCredentials: Boolean - authModelId: ID - credentials: Object - - # Map of provider properties (name/value) - - providerProperties: Object - - # Network handlers. Map of id->property map (name/value). - - networkHandlersConfig: [NetworkHandlerConfigInput!] - - #### deprecated fields - - # ID of predefined datasource - dataSourceId: ID #@deprecated - - # Direct user credentials - userName: String #@deprecated - userPassword: String #@deprecated - - # Folder - folder: ID -} - -#################################################### -# Main API -#################################################### - -extend type Query { - # Returns server config - serverConfig: ServerConfig! - - # Returns session state ( initialize if not ) - sessionState: SessionInfo! - - # Session permissions - sessionPermissions: [ID]! - - # Get driver info - driverList( id: ID ): [ DriverInfo! ]! - authModels: [DatabaseAuthModel!]! - networkHandlers: [NetworkHandlerDescriptor!]! - - # List of user connections. - userConnections( id: ID ): [ ConnectionInfo! ]! - # List of template connections. - templateConnections: [ ConnectionInfo! ]! - - # List of connection folders - connectionFolders( path: ID ): [ ConnectionFolderInfo! ]! - - # Return connection state - connectionState( id: ID! ): ConnectionInfo! @deprecated - - # Return connection info - connectionInfo( id: ID! ): ConnectionInfo! - - readSessionLog(maxEntries: Int, clearEntries: Boolean): [ LogEntry! ]! -} - -extend type Mutation { - # Initialize session - openSession(defaultLocale: String): SessionInfo! - - # Destroy session - closeSession: Boolean - - # Refreshes session on server and returns its state - touchSession: Boolean - - # Refresh session connection list - refreshSessionConnections: Boolean - - # Refreshes session on server and returns its state - changeSessionLanguage(locale: String): Boolean - - # Create new custom connection. Custom connections exist only within the current session. - createConnection( config: ConnectionConfig! ): ConnectionInfo! - - updateConnection( config: ConnectionConfig! ): ConnectionInfo! - - deleteConnection( id: ID! ): Boolean! - - createConnectionFromTemplate( templateId: ID!, connectionName: String ): ConnectionInfo! - - # Create new folder - createConnectionFolder(parentFolderPath: ID, folderName: String! ): ConnectionFolderInfo! - - deleteConnectionFolder( folderPath: ID! ): Boolean! - - # Copies connection configuration from node - copyConnectionFromNode( nodePath: String!, config: ConnectionConfig ): ConnectionInfo! - - # Test connection configuration. Returns remote server version - testConnection( config: ConnectionConfig! ): ConnectionInfo! - - # Test connection configuration. Returns remote server version - testNetworkHandler( config: NetworkHandlerConfigInput! ): NetworkEndpointInfo! - - # Initiate existing connection - initConnection( id: ID!, credentials: Object, networkCredentials: [NetworkHandlerConfigInput!], saveCredentials: Boolean ): ConnectionInfo! - - # Disconnect from database - closeConnection( id: ID! ): ConnectionInfo! - - # Changes navigator settings for connection - setConnectionNavigatorSettings( id: ID!, settings: NavigatorSettingsInput!): ConnectionInfo! - - #### Generic async functions - - asyncTaskCancel(id: String!): Boolean - - asyncTaskInfo(id: String!, removeOnFinish: Boolean!): AsyncTaskInfo! - - - #### Deprecated API - - # Create connection from template. Use createConnection instead - openConnection( config: ConnectionConfig! ): ConnectionInfo! @deprecated - - # Use asyncTaskInfo instead - asyncTaskStatus(id: String!): AsyncTaskInfo! @deprecated - -} - diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/service.data.transfer.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/service.data.transfer.graphqls deleted file mode 100644 index bdf22420d2..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/service.data.transfer.graphqls +++ /dev/null @@ -1,49 +0,0 @@ -# Data transfer queries - -type DataTransferProcessorInfo { - id: ID! - name: String - description: String - fileExtension: String - appFileExtension: String - appName: String - order: Int! - icon: String - properties: [ ObjectPropertyInfo ] - isBinary: Boolean - isHTML: Boolean -} - -input DataTransferParameters { - # Processor ID - processorId: ID! - # General settings: - # - openNewConnection: opens new database connection for data transfer task - settings: Object - # Processor properties. See DataTransferProcessorInfo.properties - processorProperties: Object! - # Data filter settings - filter: SQLDataFilter -} - -extend type Query { - - # Available transfer processors - dataTransferAvailableStreamProcessors: [ DataTransferProcessorInfo! ]! - - dataTransferExportDataFromContainer( - connectionId: ID!, - containerNodePath: ID!, - parameters: DataTransferParameters! - ): AsyncTaskInfo! - - dataTransferExportDataFromResults( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - parameters: DataTransferParameters! - ): AsyncTaskInfo! - - dataTransferRemoveDataFile(dataFileId: String!): Boolean - -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/service.metadata.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/service.metadata.graphqls deleted file mode 100644 index 0fde710b52..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/service.metadata.graphqls +++ /dev/null @@ -1,8 +0,0 @@ -# Metadata queries - -extend type Query { - - # Get child nodes - metadataGetNodeDDL(nodeId: ID!, options: Object): String - -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/service.navigator.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/service.navigator.graphqls deleted file mode 100644 index 7ce82d2639..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/service.navigator.graphqls +++ /dev/null @@ -1,136 +0,0 @@ -# Nodes, objects and properties - -type ObjectDescriptor { - id: Int - displayName: String - fullName: String - uniqueName: String - description: String - value: String -} - -input ObjectPropertyFilter { - ids: [String!] - features: [String!] - categories: [String!] - dataTypes: [String!] -} - -type ObjectDetails { - id: Int - displayName: String - description: String - value: Object -} - -type DatabaseObjectInfo { - # Object name - name: String - # Description - optional - description: String - # Object type. Java class name in most cases - type: String - - # Read object properties. - # Optional parameter 'ids' filters properties by id. null means all properties. - # Note: property value reading may take a lot of time so don't read all property values always - # Examine property meta (features in particular) before reading them - properties(filter: ObjectPropertyFilter): [ ObjectPropertyInfo ] - - # Optional properties - - ordinalPosition: Int - fullyQualifiedName: String - overloadedName: String - uniqueName: String - state: String - - # Features: script, scriptExtended, dataContainer, dataManipulator, - # entity, schema, catalog - features: [ String! ] - - # Supported editors: ddl, permissions, sourceDeclaration, sourceDefinition - editors: [ String! ] -} - -type NavigatorNodeInfo { - # Node ID - generally a full path to the node from root of tree - id: ID! - # Node human readable name - name: String - #Node full name - fullName: String - # Node icon path - icon: String - # Node description - description: String - # Node type - nodeType: String - # Can this property have child nodes? - hasChildren: Boolean - - # Associated object. Maybe null for non-database objects - object: DatabaseObjectInfo - - # Supported features: item, container, leaf - # canDelete, canRename - features: [ String! ] - - # Object detailed info. - # If is different than properties. It doesn't perform any expensive operation and doesn't require authentication. - nodeDetails: [ ObjectPropertyInfo! ] - - folder: Boolean - inline: Boolean - navigable: Boolean -} - -type DatabaseCatalog { - catalog: NavigatorNodeInfo! - schemaList: [ NavigatorNodeInfo! ]! -} - -type DatabaseStructContainers { - catalogList: [ DatabaseCatalog! ]! - schemaList: [ NavigatorNodeInfo! ]! - supportsCatalogChange: Boolean! - supportsSchemaChange: Boolean! -} - -#################################################### -# Main API -#################################################### - -extend type Query { - - # Get child nodes - navNodeChildren( - parentPath: ID!, - offset: Int, - limit: Int, - onlyFolders: Boolean): [ NavigatorNodeInfo! ]! - - # Get child nodes - navNodeParents(nodePath: ID!): [ NavigatorNodeInfo! ]! - - navNodeInfo( nodePath: ID! ): NavigatorNodeInfo! - - navRefreshNode( nodePath: ID! ): Boolean - - # contextId currently not using - navGetStructContainers( connectionId: ID!, contextId: ID, catalog: ID ): DatabaseStructContainers! - -} - -extend type Mutation { - - # Rename node and returns new node name - navRenameNode( nodePath: ID!, newName: String! ): String - - # Deletes nodes with specified IDs and returns number of deleted nodes - navDeleteNodes( nodePaths: [ID!]! ): Int - - # Moves nodes with specified IDs to the connection folder - navMoveNodesToFolder(nodePaths: [ID!]!, folderPath: ID!): Boolean - -} \ No newline at end of file diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/service.rm.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/service.rm.graphqls deleted file mode 100644 index d74b840273..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/service.rm.graphqls +++ /dev/null @@ -1,60 +0,0 @@ -# Metadata queries - -type RMProject { - id: String! - name: String! - description: String - shared: Boolean! - - createTime: DateTime! - creator: String! -} - -type RMResource { - name: String! - folder: Boolean! - length: Int! -} - -extend type Query { - - # List accessible projects - rmListProjects: [RMProject!]! - - # List accessible projects - rmListResources( - projectId: String!, - folder: String, - nameMask: String, - readProperties: Boolean, - readHistory: Boolean): [RMResource!]! - - # Reads resource contents as string in UTF-8 - rmReadResourceAsString( - projectId: String!, - resourcePath: String!): String! - -} - -extend type Mutation { - - rmCreateResource( - projectId: String!, - resourcePath: String!, - isFolder: Boolean!): String! - - rmMoveResource( - projectId: String!, - oldResourcePath: String!, - newResourcePath: String): String! - - rmDeleteResource( - projectId: String!, - resourcePath: String!, - recursive: Boolean!): Boolean - - rmWriteResourceStringContent( - projectId: String!, - resourcePath: String!, - data: String!): String! -} \ No newline at end of file diff --git a/sqle/api/cloudbeaver_wrapper/graph/schema/service.sql.graphqls b/sqle/api/cloudbeaver_wrapper/graph/schema/service.sql.graphqls deleted file mode 100644 index 7dfb4ea543..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/schema/service.sql.graphqls +++ /dev/null @@ -1,334 +0,0 @@ -#################################################### -# SQL helpers -#################################################### - -type SQLDialectInfo { - name: String! - - dataTypes: [ String ]! - functions: [ String ]! - reservedWords: [ String ]! - quoteStrings: [ [ String ] ]! - singleLineComments: [ String ]! - multiLineComments: [ [ String ] ]! - - catalogSeparator: String - structSeparator: String - scriptDelimiter: String - - supportsExplainExecutionPlan: Boolean! - -} - -type SQLCompletionProposal { - displayString: String! - type: String! - score: Int - - replacementString: String! - replacementOffset: Int! - replacementLength: Int! - cursorPosition: Int - - icon: String - nodePath: String -} - -#################################################### -# Data read / SQL execution -#################################################### - -# SQL context must be created for each SQL editor -type SQLContextInfo { - - id: ID! - connectionId: ID! - defaultCatalog: String - defaultSchema: String - -} - -input SQLDataFilterConstraint { - attributePosition: Int! - orderPosition: Int - orderAsc: Boolean - - criteria: String - operator: String - value: Object -} - -input SQLDataFilter { - # Row offset. We use Float because offset may be bigger than 32 bit. - offset: Float - limit: Int - - constraints: [ SQLDataFilterConstraint ] - where: String - orderBy: String -} - -type SQLResultColumn { - position: Int! - name: String - label: String - icon: String - entityName: String - - dataKind: String - typeName: String - fullTypeName: String - # Column value max length. We use Float because it may be bigger than 32 bit. - maxLength: Float - scale: Int - precision: Int - - required: Boolean! - - readOnly: Boolean! - readOnlyStatus: String - - # Operations supported for this attribute - supportedOperations: [DataTypeLogicalOperation!]! -} - -type DatabaseDocument { - id: String - contentType: String - properties: Object - data: Object -} - -type SQLResultSet { - id: ID! - columns: [ SQLResultColumn ] - rows: [ [ Object ] ] - - # True means that resultset was generated by single entity query - # New rows can be added, old rows can be deleted - singleEntity: Boolean! - # server always returns hasMoreData = false - hasMoreData: Boolean! - # can't update data or load LOB file if hasRowIdentifier = false - hasRowIdentifier: Boolean! -} - -type SQLQueryResults { - title: String - updateRowCount: Float - sourceQuery: String - - # Actual data format of this result - dataFormat: ResultDataFormat - - resultSet: SQLResultSet -} - -type SQLExecuteInfo { - - # Status message - statusMessage: String - # Execute time (ms) - duration: Int! - # Actual conditions applied to query - filterText: String - # Results - results: [ SQLQueryResults! ]! -} - -input SQLResultRow { - data: [ Object ]! - updateValues: Object -} - -type DataTypeLogicalOperation { - id: ID! - expression: String! - argumentCount: Int -} - -#################################################### -# SQL Execution plan -#################################################### - -type SQLExecutionPlan { - query: String! - nodes: [SQLExecutionPlanNode!]! -} - -type SQLExecutionPlanNode { - id: ID! - parentId: ID - - kind: String! - name: String - type: String! - condition: String - description: String - properties: [ObjectPropertyInfo!]! -} - -#################################################### -# SQL Generation -#################################################### - -type SQLQueryGenerator { - id: String! - label: String! - description: String - order: Int! - multiObject: Boolean! -} - -#################################################### -# SQL Query info -#################################################### -type SQLScriptInfo { - queries: [ SQLScriptQuery! ]! -} - -type SQLScriptQuery { - start: Int! - end: Int! -} -#################################################### -# Query and Mutation -#################################################### - -extend type Query { - - sqlDialectInfo( connectionId: ID! ): SQLDialectInfo - - # Lists SQL contexts for a connection (optional) or returns the particular context info - sqlListContexts( connectionId: ID, contextId: ID ): [ SQLContextInfo ]! - - sqlCompletionProposals( - connectionId: ID!, - contextId: ID!, - query: String!, - position: Int!, - maxResults: Int, - simpleMode: Boolean - ): [ SQLCompletionProposal ] - - sqlFormatQuery( - connectionId: ID!, - contextId: ID!, - query: String! - ): String! - - sqlSupportedOperations( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - attributeIndex: Int! - ): [DataTypeLogicalOperation!]! - - # List of all available entity query generators - sqlEntityQueryGenerators(nodePathList: [String!]! - ): [SQLQueryGenerator!]! - - # Options: - # fullyQualifiedNames: Boolean - # compactSQL: Boolean - # showComments: Boolean - # showPermissions: Boolean - # showFullDdl: Boolean - # excludeAutoGeneratedColumn: Boolean - # useCustomDataFormat: Boolean - sqlGenerateEntityQuery( - generatorId: String!, - options: Object!, - nodePathList: [String!]! - ): String! - - sqlParseScript( - connectionId: ID!, - script: String! - ): SQLScriptInfo! - - sqlParseQuery( - connectionId: ID!, - script: String!, - position: Int! - ): SQLScriptQuery! -} - -extend type Mutation { - sqlContextCreate( connectionId: ID!, defaultCatalog: String, defaultSchema: String ): SQLContextInfo! - - sqlContextSetDefaults( connectionId: ID!, contextId: ID!, defaultCatalog: ID, defaultSchema: ID ): Boolean! - - sqlContextDestroy( connectionId: ID!, contextId: ID! ): Boolean! - - # Execute SQL and return results - asyncSqlExecuteQuery( - projectId: ID, - connectionId: ID!, - contextId: ID!, - sql: String!, - resultId: ID, - filter: SQLDataFilter, - dataFormat: ResultDataFormat, # requested data format. May be ignored by server - readLogs: Boolean # added 23.2.1 - ): AsyncTaskInfo! - - # Read data from table - asyncReadDataFromContainer( - connectionId: ID!, - contextId: ID!, - containerNodePath: ID!, - resultId: ID, - filter: SQLDataFilter, - dataFormat: ResultDataFormat - ): AsyncTaskInfo! - - # Close results (free resources) - sqlResultClose(connectionId: ID!, contextId: ID!, resultId: ID!): Boolean! - - # Update multiple cell values - updateResultsDataBatch( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - - updatedRows: [ SQLResultRow! ], - deletedRows: [ SQLResultRow! ], - addedRows: [ SQLResultRow! ], - ): SQLExecuteInfo! - - # Return SQL script for cell values update - updateResultsDataBatchScript( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - - updatedRows: [ SQLResultRow! ], - deletedRows: [ SQLResultRow! ], - addedRows: [ SQLResultRow! ], - ): String! - - #Return BLOB name - readLobValue( - connectionId: ID!, - contextId: ID!, - resultsId: ID!, - lobColumnIndex: Int!, - row: [ SQLResultRow! ]! - ): String! - - # Returns SQLExecuteInfo - asyncSqlExecuteResults(taskId: ID!): SQLExecuteInfo ! - - # Read data from table - asyncSqlExplainExecutionPlan( - connectionId: ID!, - contextId: ID!, - query: String!, - configuration: Object! - ): AsyncTaskInfo! - - # Returns SQLExecutionPlan - asyncSqlExplainExecutionPlanResult(taskId: ID!): SQLExecutionPlan ! - -} diff --git a/sqle/api/cloudbeaver_wrapper/graph/tools.go b/sqle/api/cloudbeaver_wrapper/graph/tools.go deleted file mode 100644 index d28155f881..0000000000 --- a/sqle/api/cloudbeaver_wrapper/graph/tools.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build tools -// +build tools - -package main - -import ( - "fmt" - "os" - - "github.com/99designs/gqlgen/api" - "github.com/99designs/gqlgen/codegen/config" - _ "github.com/99designs/gqlgen/graphql/introspection" -) - -func main() { - cfg, err := config.LoadConfigFromDefaultLocations() - if err != nil { - fmt.Fprintln(os.Stderr, "failed to load config", err.Error()) - os.Exit(2) - } - - err = api.Generate(cfg) - if err != nil { - fmt.Fprintln(os.Stderr, err.Error()) - os.Exit(3) - } -} diff --git a/sqle/api/cloudbeaver_wrapper/service/audit.go b/sqle/api/cloudbeaver_wrapper/service/audit.go deleted file mode 100644 index a3f42d4c3d..0000000000 --- a/sqle/api/cloudbeaver_wrapper/service/audit.go +++ /dev/null @@ -1,83 +0,0 @@ -package service - -import ( - "fmt" - "strings" - - driverV2 "github.com/actiontech/sqle/sqle/driver/v2" - "github.com/actiontech/sqle/sqle/log" - sqleModel "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/server" -) - -type AuditResult struct { - Result string - LimitLevel string - AuditLevel string -} - -func AuditSQL(sql string, connectionID string) (auditSuccess bool, result *AuditResult, err error) { - if sql == "" || connectionID == "" { - return true, nil, nil - } - - // 获取SQLE实例 - s := sqleModel.GetStorage() - cache, err := s.GetCloudBeaverInstanceCacheByCBInstIDs([]string{connectionID}) - if err != nil { - return false, nil, err - } - - // 找不到这个实例的缓存表示这个实例不在SQLE管理范围内 - if len(cache) == 0 { - return true, nil, nil - } - - // 找不到sqle实例可能是实例被删除后没更新的脏数据 - inst, exist, err := s.GetInstanceById(fmt.Sprintf("%v", cache[0].SQLEInstanceID)) - if err != nil || !exist { - return false, nil, err - } - - // 不用审核的实例跳过审核 - if !inst.SqlQueryConfig.AuditEnabled { - return true, nil, nil - } - - ruleTemplate, exist, err := s.GetRuleTemplatesByInstanceNameAndProjectId(inst.Name, inst.ProjectId) - if err != nil { - return false, nil, err - } - ruleTemplateName := "" - var projectId uint - if exist { - ruleTemplateName = ruleTemplate.Name - projectId = ruleTemplate.ProjectId - } - - task, err := server.AuditSQLByDBType(log.NewEntry(), sql, inst.DbType, &projectId, ruleTemplateName) - if err != nil { - return false, nil, err - } - - if driverV2.RuleLevel(task.AuditLevel).More(driverV2.RuleLevel(inst.SqlQueryConfig.AllowQueryWhenLessThanAuditLevel)) { - return false, &AuditResult{ - Result: generateAuditResult(task), - LimitLevel: inst.SqlQueryConfig.AllowQueryWhenLessThanAuditLevel, - AuditLevel: task.AuditLevel, - }, nil - } - - return true, nil, nil -} - -func generateAuditResult(task *sqleModel.Task) string { - builder := strings.Builder{} - for _, executeSQL := range task.ExecuteSQLs { - builder.WriteString(strings.TrimSpace(executeSQL.Content)) - builder.WriteString("\n------------------------------------------------------------------------------------------------\n") - builder.WriteString(executeSQL.GetAuditResults()) - builder.WriteString("\n------------------------------------------------------------------------------------------------\n\n") - } - return builder.String() -} diff --git a/sqle/api/cloudbeaver_wrapper/service/base.go b/sqle/api/cloudbeaver_wrapper/service/base.go deleted file mode 100644 index e94f32ec31..0000000000 --- a/sqle/api/cloudbeaver_wrapper/service/base.go +++ /dev/null @@ -1,92 +0,0 @@ -package service - -import ( - "fmt" - "sync" - - gqlClient "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/client" - "github.com/actiontech/sqle/sqle/config" - - "github.com/labstack/echo/v4" -) - -type SQLQueryConfig struct { - config.SQLQueryConfig - SqlePort int - SqleEnableHttps bool -} - -var ( - cfg = &SQLQueryConfig{} - cfgMu = &sync.RWMutex{} -) - -const ( - CbRootUri = "/sql_query" - CbGqlApi = "/api/gql" - CBUserRole = "user" -) - -// 这个客户端会用当前用户操作, 请求会发给SQLE, 由SQLE转发到CB -func GetSQLEGQLClientWithCurrentUser(ctx echo.Context) (*gqlClient.Client, error) { - return gqlClient.NewClient(GetSQLEGqlServerURI(), gqlClient.WithCookie(ctx.Cookies())), nil -} - -// 这个客户端会用CB管理员操作, 请求会直接发到CB -func GetGQLClientWithRootUser() (*gqlClient.Client, error) { - cookies, err := LoginToCBServer(GetSQLQueryConfig().CloudBeaverAdminUser, GetSQLQueryConfig().CloudBeaverAdminPassword) - if err != nil { - return nil, err - } - return gqlClient.NewClient(GetGqlServerURI(), gqlClient.WithCookie(cookies)), nil -} - -// 这个客户端会用指定用户操作, 请求会直接发到CB -func GetGQLClient(username, password string) (*gqlClient.Client, error) { - cookies, err := LoginToCBServer(username, password) - if err != nil { - return nil, err - } - return gqlClient.NewClient(GetGqlServerURI(), gqlClient.WithCookie(cookies)), nil -} - -func IsCloudBeaverConfigured() bool { - c := GetSQLQueryConfig() - return c.SqlePort != 0 && c.CloudBeaverHost != "" && c.CloudBeaverPort != "" && c.CloudBeaverAdminUser != "" && c.CloudBeaverAdminPassword != "" -} - -func GetGqlServerURI() string { - protocol := "http" - if cfg.EnableHttps { - protocol = "https" - } - - c := GetSQLQueryConfig() - - return fmt.Sprintf("%v://%v:%v%v%v", protocol, c.CloudBeaverHost, c.CloudBeaverPort, CbRootUri, CbGqlApi) -} - -func GetSQLEGqlServerURI() string { - protocol := "http" - if cfg.EnableHttps { - protocol = "https" - } - - c := GetSQLQueryConfig() - - return fmt.Sprintf("%v://localhost:%v%v%v", protocol, c.SqlePort, CbRootUri, CbGqlApi) -} - -func InitSQLQueryConfig(sqlePort int, sqleEnableHttps bool, c config.SQLQueryConfig) { - cfgMu.Lock() - cfg.SqlePort = sqlePort - cfg.SQLQueryConfig = c - cfg.SqleEnableHttps = sqleEnableHttps - cfgMu.Unlock() -} - -func GetSQLQueryConfig() *SQLQueryConfig { - cfgMu.RLock() - defer cfgMu.RUnlock() - return cfg -} diff --git a/sqle/api/cloudbeaver_wrapper/service/gql.go b/sqle/api/cloudbeaver_wrapper/service/gql.go deleted file mode 100644 index 211d24f360..0000000000 --- a/sqle/api/cloudbeaver_wrapper/service/gql.go +++ /dev/null @@ -1,345 +0,0 @@ -package service - -import ( - "context" - "fmt" - "strconv" - "strings" - - gqlClient "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/client" -) - -var QueryGQL GetQueryGQL = CloudBeaverV2321{} - -var ( - Version2215 = CBVersion{ - version: []int{22, 1, 5}, - } - - Version2221 = CBVersion{ - version: []int{22, 2, 1}, - } - - Version2223 = CBVersion{ - version: []int{22, 2, 3}, - } - Version2321 = CBVersion{ - version: []int{23, 2, 1}, - } -) - -const getServerConfigQuery = ` -query serverConfig { - serverConfig { - version - } -}` - -func InitGQLVersion() error { - client := gqlClient.NewClient(GetGqlServerURI()) - req := gqlClient.NewRequest(getServerConfigQuery, map[string]interface{}{}) - resp := struct { - ServerConfig struct { - Version string `json:"version"` - } `json:"serverConfig"` - }{} - err := client.Run(context.Background(), req, &resp) - if err != nil { - return err - } - - version, err := NewCBVersion(resp.ServerConfig.Version) - if err != nil { - return err - } - // QueryGQL 默认值是 CloudBeaverV2223{} - if version.LessThan(Version2321) { - QueryGQL = CloudBeaverV2223{} - } - if version.LessThan(Version2223) { - QueryGQL = CloudBeaverV2221{} - } - if version.LessThan(Version2221) { - QueryGQL = CloudBeaverV2215{} - } - if version.LessThan(Version2215) { - return fmt.Errorf("CloudBeaver version less than 22.1.5 are not supported temporarily, your version is %v", resp.ServerConfig.Version) - } - - return nil -} - -// CloudBeaver 版本号格式一般为 X.X.X.X 格式,例如 '22.3.1.202212261505' , 其中前三位为版本号 -type CBVersion struct { - version []int // version是版本号使用'.'进行分割后的数组 -} - -func NewCBVersion(versionStr string) (CBVersion, error) { - versions := strings.Split(versionStr, ".") - if len(versions) < 3 { - return CBVersion{}, fmt.Errorf("CloudBeaver version number that cannot be resolved") - } - cb := CBVersion{ - version: []int{}, - } - for _, version := range versions { - v, err := strconv.Atoi(version) - if err != nil { - return CBVersion{}, fmt.Errorf("CloudBeaver version number that cannot be resolved") - } - cb.version = append(cb.version, v) - } - return cb, nil -} - -// 只比较前三位, 因为只有前三位与版本有关 -func (v CBVersion) LessThan(version CBVersion) bool { - if v.version[0] < version.version[0] { - return true - } - if v.version[0] > version.version[0] { - return false - } - if v.version[1] < version.version[1] { - return true - } - if v.version[1] > version.version[1] { - return false - } - return v.version[2] < version.version[2] - -} - -// 不同版本的CloudBeaver间存在不兼容查询语句 -// 说明: 接口传参时不要删除旧版查询语句的查询参数,多余的参数对新接口没有影响但是可以兼容旧版本 -type GetQueryGQL interface { - CreateConnectionQuery() string - UpdateConnectionQuery() string - GetUserConnectionsQuery() string - SetUserConnectionsQuery() string - IsUserExistQuery(userId string) (string, map[string]interface{}) - UpdatePasswordQuery() string - CreateUserQuery() string - GrantUserRoleQuery() string - LoginQuery() string - GetActiveUserQuery() string -} - -// TODO 暂时无法确定这套查询语句是兼容到22.1.5版本还是22.1.4版本, 因为虽然找到了22.1.4版本的镜像, 但没找到22.1.4版本的代码 -type CloudBeaverV2215 struct{} - -func (CloudBeaverV2215) CreateConnectionQuery() string { - return ` -mutation createConnection( - $projectId: ID! - $config: ConnectionConfig! -) { - connection: createConnection(projectId: $projectId, config: $config) { - ...DatabaseConnection - } -} -fragment DatabaseConnection on ConnectionInfo { - id -} -` -} - -func (CloudBeaverV2215) UpdateConnectionQuery() string { - return ` -mutation updateConnection( - $projectId: ID! - $config: ConnectionConfig! -) { - connection: updateConnection(projectId: $projectId, config: $config) { - ...DatabaseConnection - } -} -fragment DatabaseConnection on ConnectionInfo { - id -} -` -} - -func (CloudBeaverV2215) GetUserConnectionsQuery() string { - return ` -query getUserConnections ( - $projectId: ID - $connectionId: ID -){ - connections: userConnections(projectId: $projectId, id: $connectionId) { - ...DatabaseConnection - } -} -fragment DatabaseConnection on ConnectionInfo { - id -} -` -} - -func (CloudBeaverV2215) SetUserConnectionsQuery() string { - return ` -query setConnections($userId: ID!, $connections: [ID!]!) { - grantedConnections: setSubjectConnectionAccess( - subjectId: $userId - connections: $connections - ) -} -` -} - -func (CloudBeaverV2215) IsUserExistQuery(userId string) (string, map[string]interface{}) { - return ` -query getUserList( - $userId: ID -){ - listUsers(userId: $userId) { - ...adminUserInfo - } -} -fragment adminUserInfo on AdminUserInfo { - userId -}`, map[string]interface{}{"userId": userId} -} - -func (CloudBeaverV2215) UpdatePasswordQuery() string { - return ` -query setUserCredentials( - $userId: ID! - $credentials: Object! -) { - setUserCredentials( - userId: $userId - providerId: "local" - credentials: $credentials - ) -} -` -} - -func (CloudBeaverV2215) CreateUserQuery() string { - return ` -query createUser( - $userId: ID! -) { - user: createUser(userId: $userId) { - ...adminUserInfo - } -} -fragment adminUserInfo on AdminUserInfo { - userId -} -` -} - -func (CloudBeaverV2215) GrantUserRoleQuery() string { - return ` -query grantUserRole($userId: ID!, $roleId: ID!) { - grantUserRole(userId: $userId, roleId: $roleId) -}` -} - -func (CloudBeaverV2215) LoginQuery() string { - return ` -query authLogin( - $credentials: Object -) { - authInfo: authLogin( - provider: "local" - configuration: null - credentials: $credentials - linkUser: false - ){ - authId - } -} -` -} - -func (CloudBeaverV2215) GetActiveUserQuery() string { - return ` - query getActiveUser { - user: activeUser { - userId - } - } -` -} - -type CloudBeaverV2221 struct { - CloudBeaverV2215 -} - -func (CloudBeaverV2221) CreateUserQuery() string { - return ` -query createUser( - $userId: ID! -) { - user: createUser(userId: $userId, enabled: true) { - ...adminUserInfo - } -} -fragment adminUserInfo on AdminUserInfo { - userId -} -` -} - -type CloudBeaverV2223 struct { - CloudBeaverV2221 -} - -func (CloudBeaverV2223) CreateUserQuery() string { - return ` -query createUser( - $userId: ID! -) { - user: createUser(userId: $userId, enabled: true, authRole: null) { - ...adminUserInfo - } -} -fragment adminUserInfo on AdminUserInfo { - userId -} -` -} - -func (CloudBeaverV2223) GrantUserRoleQuery() string { - return ` -query grantUserTeam($userId: ID!, $teamId: ID!) { - grantUserTeam(userId: $userId, teamId: $teamId) -}` -} - -type CloudBeaverV2321 struct { - CloudBeaverV2221 -} - -func (CloudBeaverV2321) IsUserExistQuery(userId string) (string, map[string]interface{}) { - - return ` -query getUserList( - $page: PageInput! - $filter: AdminUserFilterInput! -){ - listUsers(page: $page, filter: $filter) { - ...adminUserInfo - } -} -fragment adminUserInfo on AdminUserInfo { - userId -} -`, map[string]interface{}{ - "page": map[string]interface{}{"offset": 0, "limit": 100}, - "filter": map[string]interface{}{"userIdMask": userId, "enabledState": true}, - } -} - -func (CloudBeaverV2321) GetActiveUserQuery() string { - return ` - query getActiveUser { - user: activeUser { - userId - } - } -` -} diff --git a/sqle/api/cloudbeaver_wrapper/service/gql_test.go b/sqle/api/cloudbeaver_wrapper/service/gql_test.go deleted file mode 100644 index fd34ef5bd5..0000000000 --- a/sqle/api/cloudbeaver_wrapper/service/gql_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package service - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestCBVersion_LessThan(t *testing.T) { - // 判断V1是否比V2小 - versions := []struct { - V1 CBVersion - V2 CBVersion - result bool - }{ - // 应当只比较前三位 - { - V1: CBVersion{ - []int{2, 2, 2, 2}, - }, - V2: CBVersion{ - []int{2, 2, 2, 3}, - }, - result: false, - }, - // 前两位相同 - { - V1: CBVersion{ - []int{2, 2, 2}, - }, - V2: CBVersion{ - []int{2, 2, 2}, - }, - result: false, - }, { - V1: CBVersion{ - []int{2, 2, 3}, - }, - V2: CBVersion{ - []int{2, 2, 2}, - }, - result: false, - }, { - V1: CBVersion{ - []int{2, 2, 1}, - }, - V2: CBVersion{ - []int{2, 2, 2}, - }, - result: true, - }, - // 第一位相同 - { - V1: CBVersion{ - []int{2, 2, 2}, - }, - V2: CBVersion{ - []int{2, 1, 2}, - }, - result: false, - }, { - V1: CBVersion{ - []int{2, 1, 2}, - }, - V2: CBVersion{ - []int{2, 2, 2}, - }, - result: true, - }, - // 第一位不同 - { - V1: CBVersion{ - []int{2, 2, 2}, - }, - V2: CBVersion{ - []int{1, 2, 2}, - }, - result: false, - }, { - V1: CBVersion{ - []int{1, 2, 2}, - }, - V2: CBVersion{ - []int{2, 2, 2}, - }, - result: true, - }, - } - - for _, version := range versions { - assert.Equal(t, version.V1.LessThan(version.V2), version.result, - fmt.Sprintf("V1: %v || V2: %v || result: %v", version.V1, version.V2, version.result)) - } -} diff --git a/sqle/api/cloudbeaver_wrapper/service/instance.go b/sqle/api/cloudbeaver_wrapper/service/instance.go deleted file mode 100644 index c69f5021a0..0000000000 --- a/sqle/api/cloudbeaver_wrapper/service/instance.go +++ /dev/null @@ -1,375 +0,0 @@ -package service - -import ( - "context" - "fmt" - - gqlClient "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/client" - driverV2 "github.com/actiontech/sqle/sqle/driver/v2" - "github.com/actiontech/sqle/sqle/log" - sqleModel "github.com/actiontech/sqle/sqle/model" -) - -func SyncUserBindInstance(cbUserID string) error { - // 获取当前SQLE用户 - s := sqleModel.GetStorage() - sqleUserCache, exist, err := s.GetCloudBeaverUserCacheByCBUserID(cbUserID) - if err != nil || !exist { // 如果用户不存在表示这可能是个与SQLE无关的用户 - return err - } - sqleUser, exist, err := s.GetUserByID(sqleUserCache.SQLEUserID) - if err != nil || !exist { - return err - } - - // 获取用户当前拥有权限的SQLE实例 - var sqleInstSlice []*sqleModel.Instance - if sqleUser.Name == sqleModel.DefaultAdminUser { - sqleInstSlice, err = s.GetAllInstance() - } else { - sqleInstSlice, err = s.GetUserCanOpInstances(sqleUser, []uint{sqleModel.OP_SQL_QUERY_QUERY}) - } - if err != nil { - return err - } - - sqleInstMap := map[uint] /*sqle inst id*/ *sqleModel.Instance{} - instIds := make([]uint, len(sqleInstSlice)) - for i, instance := range sqleInstSlice { - instIds[i] = instance.ID - } - insts, err := s.GetInstancesFromActiveProjectByIds(instIds) - if err != nil { - return err - } - for _, inst := range insts { - sqleInstMap[inst.ID] = inst - } - - // 同步实例信息 - if err := SyncInstance(sqleInstMap); err != nil { - return err - } - - // 同步cloudbeaver上用户对实例的权限信息 - if err := SyncVisibleInstance(sqleUserCache, sqleUser, sqleInstMap); err != nil { - return err - } - - return nil -} - -func SyncInstance(sqleInstances map[uint] /*sqle inst id*/ *sqleModel.Instance) error { - ids := []uint{} - for _, instance := range sqleInstances { - ids = append(ids, instance.ID) - } - - // 从缓存中获取需要同步的CloudBeaver实例 - s := sqleModel.GetStorage() - cbInstCacheSlice, err := s.GetCloudBeaverInstanceCacheBySQLEInstIDs(ids) - if err != nil { - return err - } - cbInstCacheMap := map[uint] /* sqle inst id*/ *sqleModel.CloudBeaverInstanceCache{} - for _, cache := range cbInstCacheSlice { - cbInstCacheMap[cache.SQLEInstanceID] = cache - } - - // 找到需要同步的实例 - needAdd := []uint /*sqle inst id*/ {} - needUpdate := []uint /*sqle inst id*/ {} - for sqleInstID, sqleInst := range sqleInstances { - cb, ok := cbInstCacheMap[sqleInstID] - if !ok { - needAdd = append(needAdd, sqleInstID) - } else if cb.SQLEInstanceFingerprint != sqleInst.Fingerprint() { - needUpdate = append(needUpdate, sqleInstID) - } - } - - if len(needAdd) == 0 && len(needUpdate) == 0 { - return nil - } - - // 获取管理员链接 - client, err := GetGQLClientWithRootUser() - if err != nil { - return err - } - - l := log.NewEntry() - - // 同步实例信息 - for _, sqleInstID := range needAdd { - project, _, err := s.GetProjectByID(sqleInstances[sqleInstID].ProjectId) - if err != nil { - l.Errorf("get instance %v project failed: %v", sqleInstID, err) - project.Name = "unknown" - } - if err := AddCloudBeaverInstance(client, sqleInstances[sqleInstID], project); err != nil { - l.Errorf("add instance %v to cloudbeaver failed: %v", sqleInstID, err) - } - } - for _, sqleInstID := range needUpdate { - project, _, err := s.GetProjectByID(sqleInstances[sqleInstID].ProjectId) - if err != nil { - l.Errorf("get instance %v project failed: %v", sqleInstID, err) - project.Name = "unknown" - } - if err := UpdateCloudBeaverInstance(client, cbInstCacheMap[sqleInstID].CloudBeaverInstanceID, sqleInstances[sqleInstID], project); err != nil { - l.Errorf("update instance %v to cloudbeaver failed: %v", sqleInstID, err) - } - } - - return nil - -} - -// AddCloudBeaverInstance 添加实例后会同步缓存 -func AddCloudBeaverInstance(client *gqlClient.Client, sqleInst *sqleModel.Instance, project *sqleModel.Project) error { - params, err := GenerateCloudBeaverInstanceParams(sqleInst, project) - if err != nil { - fmt.Println("Instances of this type are not currently supported:", sqleInst.DbType) - // 不支持的类型跳过就好,没必要终端流程 - //nolint:nilerr - return nil - } - // 添加实例 - req := gqlClient.NewRequest(QueryGQL.CreateConnectionQuery(), params) - resp := struct { - Connection struct { - ID string `json:"id"` - } `json:"connection"` - }{} - - err = client.Run(context.TODO(), req, &resp) - if err != nil { - return err - } - - // 同步缓存 - s := sqleModel.GetStorage() - return s.Save(&sqleModel.CloudBeaverInstanceCache{ - CloudBeaverInstanceID: resp.Connection.ID, - SQLEInstanceID: sqleInst.ID, - SQLEInstanceFingerprint: sqleInst.Fingerprint(), - }) -} - -// UpdateCloudBeaverInstance 更新完毕后会同步缓存 -func UpdateCloudBeaverInstance(client *gqlClient.Client, cbInstID string, sqleInst *sqleModel.Instance, project *sqleModel.Project) error { - - params, err := GenerateCloudBeaverInstanceParams(sqleInst, project) - if err != nil { - fmt.Println("Instances of this type are not currently supported:", sqleInst.DbType) - // 不支持的类型跳过就好,没必要终端流程 - //nolint:nilerr - return nil - } - // 更新实例 - params["config"].(map[string]interface{})["connectionId"] = cbInstID - req := gqlClient.NewRequest(QueryGQL.UpdateConnectionQuery(), params) - resp := struct { - Connection struct { - ID string `json:"id"` - } `json:"connection"` - }{} - - err = client.Run(context.TODO(), req, &resp) - if err != nil { - return err - } - - // 同步缓存 - s := sqleModel.GetStorage() - return s.Save(&sqleModel.CloudBeaverInstanceCache{ - CloudBeaverInstanceID: resp.Connection.ID, - SQLEInstanceID: sqleInst.ID, - SQLEInstanceFingerprint: sqleInst.Fingerprint(), - }) -} - -func SyncVisibleInstance(cbUserCache *sqleModel.CloudBeaverUserCache, sqleUser *sqleModel.User, sqleInstances map[uint] /*sqle inst id*/ *sqleModel.Instance) error { - - if cbUserCache.SQLEFingerprint != sqleUser.FingerPrint() { - return fmt.Errorf("user information is not synchronized, unable to update instance information") - } - - ids := []uint{} - for _, instance := range sqleInstances { - ids = append(ids, instance.ID) - } - - // 从缓存中获取需要同步的CloudBeaver实例 - s := sqleModel.GetStorage() - cbInstCacheSlice, err := s.GetCloudBeaverInstanceCacheBySQLEInstIDs(ids) - if err != nil { - return err - } - cbInstCacheMap := map[string] /* cb inst id*/ *sqleModel.CloudBeaverInstanceCache{} - for _, cache := range cbInstCacheSlice { - cbInstCacheMap[cache.CloudBeaverInstanceID] = cache - } - - // 获取用户当前实例列表 - getConnResp := &struct { - Connections []*struct { - Id string `json:"id"` - } `json:"connections"` - }{} - - getConReq := gqlClient.NewRequest(QueryGQL.GetUserConnectionsQuery(), nil) - - client, err := GetGQLClient(cbUserCache.CloudBeaverUserID, sqleUser.Password) - if err != nil { - return err - } - - err = client.Run(context.TODO(), getConReq, getConnResp) - if err != nil { - return err - } - - // 判断是否需要同步权限 - if len(getConnResp.Connections) != len(cbInstCacheSlice) { - return syncVisibleInstance(cbInstCacheSlice, cbUserCache.CloudBeaverUserID) - } - for _, connection := range getConnResp.Connections { - if _, ok := cbInstCacheMap[connection.Id]; !ok { - return syncVisibleInstance(cbInstCacheSlice, cbUserCache.CloudBeaverUserID) - } - } - return nil - -} - -func syncVisibleInstance(cbInstCacheSlice []*sqleModel.CloudBeaverInstanceCache, cloudBeaverUserID string) error { - cbInstIDs := []string{} - for _, cache := range cbInstCacheSlice { - cbInstIDs = append(cbInstIDs, cache.CloudBeaverInstanceID) - } - setConnReq := gqlClient.NewRequest(QueryGQL.SetUserConnectionsQuery(), map[string]interface{}{ - "userId": cloudBeaverUserID, - "connections": cbInstIDs, - }) - rootClient, err := GetGQLClientWithRootUser() - if err != nil { - return err - } - err = rootClient.Run(context.TODO(), setConnReq, nil) - return err -} - -func generateCommonCloudBeaverConfigParams(sqleInst *sqleModel.Instance, project *sqleModel.Project) map[string]interface{} { - return map[string]interface{}{ - "configurationType": "MANUAL", - "name": fmt.Sprintf("%v: %v", project.Name, sqleInst.Name), - "template": false, - "host": sqleInst.Host, - "port": sqleInst.Port, - "databaseName": nil, - "description": nil, - "authModelId": "native", - "saveCredentials": true, - "credentials": map[string]interface{}{ - "userName": sqleInst.User, - "userPassword": sqleInst.Password, - }, - } -} - -func GenerateCloudBeaverInstanceParams(sqleInst *sqleModel.Instance, project *sqleModel.Project) (map[string]interface{}, error) { - var err error - config := generateCommonCloudBeaverConfigParams(sqleInst, project) - - switch sqleInst.DbType { - case driverV2.DriverTypeMySQL, driverV2.DriverTypeTDSQLForInnoDB: - err = fillMySQLParams(config) - case driverV2.DriverTypeTiDB: - err = fillTiDBParams(config) - case driverV2.DriverTypePostgreSQL: - err = fillPGSQLParams(config) - case driverV2.DriverTypeSQLServer: - err = fillMSSQLParams(config) - case driverV2.DriverTypeOracle: - err = fillOracleParams(sqleInst, config) - case driverV2.DriverTypeDB2: - err = fillDB2Params(sqleInst, config) - case driverV2.DriverTypeOceanBase: - err = fillOceanBaseParams(sqleInst, config) - default: - return nil, fmt.Errorf("temporarily unsupported instance types") - } - - resp := map[string]interface{}{ - "projectId": "g_GlobalConfiguration", - "config": config, - } - return resp, err -} - -func fillMySQLParams(config map[string]interface{}) error { - config["driverId"] = "mysql:mysql8" - return nil -} - -func fillTiDBParams(config map[string]interface{}) error { - config["driverId"] = "mysql:tidb" - return nil -} - -func fillMSSQLParams(config map[string]interface{}) error { - config["driverId"] = "sqlserver:microsoft" - config["authModelId"] = "sqlserver_database" - return nil -} - -func fillPGSQLParams(config map[string]interface{}) error { - config["driverId"] = "postgresql:postgres-jdbc" - config["providerProperties"] = map[string]interface{}{ - "@dbeaver-show-non-default-db@": true, - "@dbeaver-show-unavailable-db@": true, - "@dbeaver-show-template-db@": true, - } - return nil -} - -func fillOracleParams(inst *sqleModel.Instance, config map[string]interface{}) error { - serviceName := inst.AdditionalParams.GetParam("service_name") - if serviceName == nil { - return fmt.Errorf("the service name of oracle cannot be empty") - } - - config["driverId"] = "oracle:oracle_thin" - config["authModelId"] = "oracle_native" - config["databaseName"] = serviceName.Value - config["providerProperties"] = map[string]interface{}{ - "@dbeaver-sid-service@": "SID", - "oracle.logon-as": "Normal", - } - return nil -} - -func fillDB2Params(inst *sqleModel.Instance, config map[string]interface{}) error { - dbName := inst.AdditionalParams.GetParam("database_name") - if dbName == nil { - return fmt.Errorf("the database name of DB2 cannot be empty") - } - - config["driverId"] = "db2:db2" - config["databaseName"] = dbName.Value - return nil -} - -func fillOceanBaseParams(inst *sqleModel.Instance, config map[string]interface{}) error { - tenant := inst.AdditionalParams.GetParam("tenant_name") - if tenant == nil { - return fmt.Errorf("the tenant name of oceanbase cannot be empty") - } - - config["driverId"] = "oceanbase:alipay_oceanbase" - config["authModelId"] = "oceanbase_native" - config["credentials"].(map[string]interface{})["userName"] = fmt.Sprintf("%v@%v", inst.User, tenant) - return nil -} diff --git a/sqle/api/cloudbeaver_wrapper/service/user.go b/sqle/api/cloudbeaver_wrapper/service/user.go deleted file mode 100644 index 258cc94b32..0000000000 --- a/sqle/api/cloudbeaver_wrapper/service/user.go +++ /dev/null @@ -1,162 +0,0 @@ -package service - -import ( - "context" - "fmt" - "net/http" - "strings" - - gqlClient "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/client" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/graph/model" - sqleModel "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/utils" -) - -func SyncCurrentUser(cloudBeaverUser string) error { - ctx := context.Background() - - // 获取SQLE缓存中的CloudBeaver用户信息和SQLE用户信息 - s := sqleModel.GetStorage() - cache, cbExist, err := s.GetCloudBeaverUserCacheByCBUserID(cloudBeaverUser) - if err != nil { - return err - } - - sqleUserName := RestoreFromCloudBeaverUserName(cloudBeaverUser) - sqleUser, exist, err := s.GetUserByName(sqleUserName) - if err != nil { - return err - } - if !exist { // SQLE用户不存在有可能是用户使用自行添加的用户导致的, 此用户因为与SQLE无关, 所以忽略 - return nil - } - - // 如果缓存存在且指纹校验通过, 则认为用户同步过且当前缓存为最新缓存 - // 反之则需要触发同步并更新缓存 - if cbExist && sqleUser.FingerPrint() == cache.SQLEFingerprint { - return nil - } - - if IsReserved(cloudBeaverUser) { - return fmt.Errorf("this username cannot be used") - } - - // 使用管理员身份登录 - client, err := GetGQLClientWithRootUser() - if err != nil { - return err - } - - checkExistReq := gqlClient.NewRequest(QueryGQL.IsUserExistQuery(cloudBeaverUser)) - - type UserList struct { - ListUsers []struct { - UserID string `json:"userID"` - } `json:"listUsers"` - } - users := UserList{} - - err = client.Run(ctx, checkExistReq, &users) - if err != nil { - return fmt.Errorf("check cloudbeaver user exist failed: %v", err) - } - - // 用户不存在则创建CloudBeaver用户 - if len(users.ListUsers) == 0 { - // 创建用户 - createUserReq := gqlClient.NewRequest(QueryGQL.CreateUserQuery(), map[string]interface{}{ - "userId": cloudBeaverUser, - }) - err = client.Run(ctx, createUserReq, &UserList{}) - if err != nil { - return fmt.Errorf("create cloudbeaver user failed: %v", err) - } - - // 授予角色(不授予角色的用户无法登录) - grantUserRoleReq := gqlClient.NewRequest(QueryGQL.GrantUserRoleQuery(), map[string]interface{}{ - "userId": cloudBeaverUser, - "roleId": CBUserRole, - "teamId": CBUserRole, - }) - err = client.Run(ctx, grantUserRoleReq, nil) - if err != nil { - return fmt.Errorf("create cloudbeaver user failed: %v", err) - } - } - - // 更新CloudBeaver用户密码 - updatePasswordReq := gqlClient.NewRequest(QueryGQL.UpdatePasswordQuery(), map[string]interface{}{ - "userId": cloudBeaverUser, - "credentials": model.JSON{ - "password": strings.ToUpper(utils.Md5(sqleUser.Password)), - }, - }) - err = client.Run(ctx, updatePasswordReq, nil) - if err != nil { - return fmt.Errorf("update cloudbeaver user failed: %v", err) - } - - // 更新SQLE缓存 - return s.UpdateCloudBeaverUserCache(sqleUser.ID, cloudBeaverUser) -} - -// IsReserved 会检查用户名是否为无法使用的名称, 比如admin和user是角色名, 按照CloudBeaver的要求角色名无法作为用户名 -func IsReserved(name string) bool { - _, ok := map[string]struct{}{ - "admin": {}, - "user": {}, - }[name] - return ok -} - -const CBNamePrefix = "sqle-" - -func GenerateCloudBeaverUserName(name string) string { - return CBNamePrefix + name -} - -func RestoreFromCloudBeaverUserName(name string) string { - return strings.TrimPrefix(name, CBNamePrefix) -} - -// LoginToCBServer 的登录请求会直接被转发, 不会被中间件拦截处理 -func LoginToCBServer(user, pwd string) (cookie []*http.Cookie, err error) { - client := gqlClient.NewClient(GetGqlServerURI(), gqlClient.WithHttpResHandler( - func(response *http.Response) { - if response != nil { - cookie = response.Cookies() - } - })) - req := gqlClient.NewRequest(QueryGQL.LoginQuery(), map[string]interface{}{ - "credentials": model.JSON{ - "user": user, - "password": strings.ToUpper(utils.Md5(pwd)), // the password is an all-caps md5-32 string - }, - }) - - res := struct { - AuthInfo struct { - AuthId interface{} `json:"authId"` - } `json:"authInfo"` - }{} - if err := client.Run(context.TODO(), req, &res); err != nil { - return cookie, fmt.Errorf("cloudbeaver login failed: %v", err) - } - - return cookie, nil -} - -type ActiveUserQueryRes struct { - User interface{} `json:"user"` -} - -func GetActiveUserQuery(cookies []*http.Cookie) (*ActiveUserQueryRes, error) { - client := gqlClient.NewClient(GetGqlServerURI(), gqlClient.WithCookie(cookies)) - req := gqlClient.NewRequest(QueryGQL.GetActiveUserQuery(), map[string]interface{}{}) - - res := &ActiveUserQueryRes{} - if err := client.Run(context.TODO(), req, res); err != nil { - return nil, err - } - return res, nil -} diff --git a/sqle/api/controller/base.go b/sqle/api/controller/base.go index e76a6d1f60..2946e2e7d5 100644 --- a/sqle/api/controller/base.go +++ b/sqle/api/controller/base.go @@ -1,17 +1,29 @@ package controller import ( + "context" "fmt" "io/ioutil" "net/http" + "strconv" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/model" + dmsJWT "github.com/actiontech/dms/pkg/dms-common/api/jwt" "github.com/golang-jwt/jwt" "github.com/labstack/echo/v4" ) +var dmsServerAddress string + +func GetDMSServerAddress() string { + return dmsServerAddress +} +func InitDMSServerAddress(addr string) { + dmsServerAddress = addr +} + type BaseRes struct { Code int `json:"code" example:"0"` Message string `json:"message" example:"ok"` @@ -59,7 +71,19 @@ func GetUserName(c echo.Context) string { return claims["name"].(string) } -func GetCurrentUser(c echo.Context) (*model.User, error) { +func GetUserID(c echo.Context) string { + uidStr, err := dmsJWT.GetUserUidStrFromContextWithOldJwt(c) + if err != nil { + return "" + } + uid, err := strconv.Atoi(uidStr) + if err != nil { + return "" + } + return fmt.Sprintf("%d", uid) +} + +func GetCurrentUser(c echo.Context, getUser func(context.Context, string, string) (*model.User, error)) (*model.User, error) { key := "current_user" currentUser := c.Get(key) if currentUser != nil { @@ -67,15 +91,11 @@ func GetCurrentUser(c echo.Context) (*model.User, error) { return user, nil } } - s := model.GetStorage() - user, exist, err := s.GetUserByName(GetUserName(c)) + uidStr := GetUserID(c) + user, err := getUser(c.Request().Context(), uidStr, GetDMSServerAddress()) if err != nil { return nil, err } - if !exist { - return nil, errors.New(errors.DataNotExist, - fmt.Errorf("current user is not exist")) - } c.Set(key, user) return user, nil } diff --git a/sqle/api/controller/v1/audit_plan.go b/sqle/api/controller/v1/audit_plan.go index f78e040c4b..23221ab470 100644 --- a/sqle/api/controller/v1/audit_plan.go +++ b/sqle/api/controller/v1/audit_plan.go @@ -13,8 +13,11 @@ import ( "strings" "time" + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + dmsCommonJwt "github.com/actiontech/dms/pkg/dms-common/api/jwt" "github.com/actiontech/sqle/sqle/api/controller" "github.com/actiontech/sqle/sqle/common" + dms "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/driver" driverV2 "github.com/actiontech/sqle/sqle/driver/v2" "github.com/actiontech/sqle/sqle/errors" @@ -25,7 +28,6 @@ import ( "github.com/actiontech/sqle/sqle/server" "github.com/actiontech/sqle/sqle/server/auditplan" "github.com/actiontech/sqle/sqle/utils" - "github.com/labstack/echo/v4" dry "github.com/ungerik/go-dry" ) @@ -219,36 +221,13 @@ func CreateAuditPlan(c echo.Context) error { return controller.JSONBaseErrorReq(c, errAuditPlanInstanceConflict) } - // check project - projectName := c.Param("project_name") - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - if project.IsArchived() { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - // check user - currentUserName := controller.GetUserName(c) - - err = CheckIsProjectMember(currentUserName, projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - user, exist, err := s.GetUserByName(currentUserName) - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("user is not exist"))) - } else if err != nil { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataConflict, err)) - } - // check audit plan name - _, exist, err = s.GetAuditPlanFromProjectByName(projectName, req.Name) + _, exist, err := s.GetAuditPlanFromProjectByName(projectUid, req.Name) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -259,7 +238,7 @@ func CreateAuditPlan(c echo.Context) error { // check instance var instanceType string if req.InstanceName != "" { - inst, exist, err := s.GetInstanceByNameAndProjectName(req.InstanceName, projectName) + inst, exist, err := dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, req.InstanceName) if !exist { return controller.JSONBaseErrorReq(c, ErrInstanceNotExist) } else if err != nil { @@ -282,23 +261,25 @@ func CreateAuditPlan(c echo.Context) error { } } instanceType = inst.DbType - // check operation - can, err := s.CheckUserCanCreateAuditPlan(user, projectName, req.InstanceName) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !can { + canCreateAuditPlan, err := CheckUserCanCreateAuditPlan(c.Request().Context(), projectUid, user, []*model.Instance{inst}) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if !canCreateAuditPlan { return controller.JSONBaseErrorReq(c, errors.NewUserNotPermissionError(model.GetOperationCodeDesc(uint(model.OP_AUDIT_PLAN_SAVE)))) } - } else { instanceType = req.InstanceType } // check rule template name if req.RuleTemplateName != "" { - exist, err = s.IsRuleTemplateExist(req.RuleTemplateName, []uint{project.ID, model.ProjectIdForGlobalRuleTemplate}) + exist, err = s.IsRuleTemplateExist(req.RuleTemplateName, []string{projectUid, model.ProjectIdForGlobalRuleTemplate}) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -306,7 +287,7 @@ func CreateAuditPlan(c echo.Context) error { return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("rule template does not exist"))) } } - ruleTemplateName, err := autoSelectRuleTemplate(req.RuleTemplateName, req.InstanceName, req.InstanceType, project.ID) + ruleTemplateName, err := autoSelectRuleTemplate(c.Request().Context(), req.RuleTemplateName, req.InstanceName, req.InstanceType, projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -321,11 +302,10 @@ func CreateAuditPlan(c echo.Context) error { } // generate token + userId := controller.GetUserID(c) // 为了控制JWT Token的长度,保证其长度不超过数据表定义的长度上限(255字符) // 因此使用MD5算法将变长的 currentUserName 和 Name 转换为固定长度 - j := utils.NewJWT(utils.JWTSecretKey) - t, err := j.CreateToken(currentUserName, time.Now().Add(tokenExpire).Unix(), - utils.WithAuditPlanName(utils.Md5(req.Name))) + t, err := dmsCommonJwt.GenJwtToken(dmsCommonJwt.WithUserId(userId), dmsCommonJwt.WithExpiredTime(tokenExpire), dmsCommonJwt.WithAuditPlanName(utils.Md5(req.Name))) if err != nil { return controller.JSONBaseErrorReq(c, errors.New(errors.DataConflict, err)) } @@ -335,13 +315,13 @@ func CreateAuditPlan(c echo.Context) error { CronExpression: req.Cron, Type: req.Type, Params: ps, - CreateUserID: user.ID, + CreateUserID: userId, Token: t, DBType: instanceType, RuleTemplateName: ruleTemplateName, InstanceName: req.InstanceName, InstanceDatabase: req.InstanceDatabase, - ProjectId: project.ID, + ProjectId: model.ProjectUID(projectUid), } err = s.Save(ap) if err != nil { @@ -353,7 +333,7 @@ func CreateAuditPlan(c echo.Context) error { // customRuleTemplateName如果为空, 将返回instanceName绑定的规则模板, 如果customRuleTemplateName,和instanceName都为空, 将返回dbType对应默认模板, dbType不能为空, 函数不做参数校验 // 规则模板选择规则: 指定规则模板 -- > 数据源绑定的规则模板 -- > 数据库类型默认模板 -func autoSelectRuleTemplate(customRuleTemplateName string, instanceName string, dbType string, projectId uint) (ruleTemplateName string, err error) { +func autoSelectRuleTemplate(ctx context.Context, customRuleTemplateName string, instanceName string, dbType string, projectId string) (ruleTemplateName string, err error) { s := model.GetStorage() if customRuleTemplateName != "" { @@ -361,13 +341,14 @@ func autoSelectRuleTemplate(customRuleTemplateName string, instanceName string, } if instanceName != "" { - ruleTemplate, exist, err := s.GetRuleTemplatesByInstanceNameAndProjectId(instanceName, projectId) + instance, exist, err := dms.GetInstanceInProjectByName(ctx, projectId, instanceName) if err != nil { return "", err } if exist { - return ruleTemplate.Name, nil + return instance.RuleTemplateName, nil } + } return s.GetDefaultRuleTemplateName(dbType), nil @@ -385,18 +366,14 @@ func autoSelectRuleTemplate(customRuleTemplateName string, instanceName string, // @router /v1/projects/{project_name}/audit_plans/{audit_plan_name}/ [delete] func DeleteAuditPlan(c echo.Context) error { s := model.GetStorage() - projectName := c.Param("project_name") - apName := c.Param("audit_plan_name") - - archived, err := s.IsProjectArchived(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, 0) + apName := c.Param("audit_plan_name") + + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, "") if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -433,19 +410,16 @@ func UpdateAuditPlan(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - apName := c.Param("audit_plan_name") - - storage := model.GetStorage() - archived, err := storage.IsProjectArchived(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, 0) + apName := c.Param("audit_plan_name") + + storage := model.GetStorage() + + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, "") if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -465,7 +439,7 @@ func UpdateAuditPlan(c echo.Context) error { } if req.RuleTemplateName != nil { - exist, err = storage.IsRuleTemplateExist(*req.RuleTemplateName, []uint{ap.ProjectId, model.ProjectIdForGlobalRuleTemplate}) + exist, err = storage.IsRuleTemplateExist(*req.RuleTemplateName, []string{projectUid, model.ProjectIdForGlobalRuleTemplate}) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -537,9 +511,7 @@ func GetAuditPlans(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -549,22 +521,11 @@ func GetAuditPlans(c echo.Context) error { offset = req.PageSize * (req.PageIndex - 1) } - currentUser, err := controller.GetCurrentUser(c) - if err != nil { - return err - } - instances, err := s.GetUserCanOpInstancesFromProject(currentUser, projectName, []uint{model.OP_AUDIT_PLAN_VIEW_OTHERS}) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - names := []string{} - for _, instance := range instances { - names = append(names, instance.Name) - } + userId := controller.GetUserID(c) - isManager, err := s.IsProjectManager(currentUser.Name, projectName) + up, err := dms.NewUserPermission(userId, projectUid) if err != nil { - return controller.JSONBaseErrorReq(c, err) + return err } data := map[string]interface{}{ @@ -572,15 +533,20 @@ func GetAuditPlans(c echo.Context) error { "fuzzy_search_audit_plan_name": req.FuzzySearchAuditPlanName, "filter_audit_plan_type": req.FilterAuditPlanType, "filter_audit_plan_instance_name": req.FilterAuditPlanInstanceName, - "current_user_name": currentUser.Name, - "current_user_is_admin": model.DefaultAdminUser == currentUser.Name || isManager, - "filter_project_name": projectName, + "filter_project_id": projectUid, "limit": req.PageSize, + "current_user_id": userId, + "current_user_is_admin": up.IsAdmin(), "offset": offset, } - if len(names) > 0 { - data["accessible_instances_name"] = fmt.Sprintf("'%s'", strings.Join(names, "', '")) + if !up.IsAdmin() { + instanceNames, err := dms.GetInstanceNamesInProjectByIds(c.Request().Context(), projectUid, up.GetInstancesByOP(v1.OpPermissionTypeViewOtherAuditPlan)) + if err != nil { + return err + } + data["accessible_instances_name"] = fmt.Sprintf("\"%s\"", strings.Join(instanceNames, "\",\"")) } + auditPlans, count, err := s.GetAuditPlansByReq(data) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -626,10 +592,13 @@ type GetAuditPlanResV1 struct { // @Success 200 {object} v1.GetAuditPlanResV1 // @router /v1/projects/{project_name}/audit_plans/{audit_plan_name}/ [get] func GetAuditPlan(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } apName := c.Param("audit_plan_name") - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, model.OP_AUDIT_PLAN_VIEW_OTHERS) + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, v1.OpPermissionTypeViewOtherAuditPlan) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -696,10 +665,13 @@ func GetAuditPlanReports(c echo.Context) error { return err } - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } apName := c.Param("audit_plan_name") - _, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, model.OP_AUDIT_PLAN_VIEW_OTHERS) + _, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, v1.OpPermissionTypeViewOtherAuditPlan) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -713,7 +685,7 @@ func GetAuditPlanReports(c echo.Context) error { } data := map[string]interface{}{ - "project_name": projectName, + "project_id": projectUid, "audit_plan_name": apName, "limit": req.PageSize, "offset": offset, @@ -756,10 +728,13 @@ type GetAuditPlanReportResV1 struct { // @Success 200 {object} v1.GetAuditPlanReportResV1 // @router /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/ [get] func GetAuditPlanReport(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } apName := c.Param("audit_plan_name") - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, model.OP_AUDIT_PLAN_VIEW_OTHERS) + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, v1.OpPermissionTypeViewOtherAuditPlan) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -914,14 +889,22 @@ func FullSyncAuditPlanSQLs(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") apName := c.Param("audit_plan_name") s := model.GetStorage() - ap, err := CheckProjectAndAuditPlan(s, projectName, apName) + + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), true) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + + ap, exist, err := s.GetAuditPlanFromProjectByName(projectUid, apName) if err != nil { return controller.JSONBaseErrorReq(c, err) } + if !exist { + return controller.JSONBaseErrorReq(c, errAuditPlanNotExist) + } l := log.NewEntry() reqSQLs := req.SQLs @@ -963,15 +946,22 @@ func PartialSyncAuditPlanSQLs(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") apName := c.Param("audit_plan_name") s := model.GetStorage() - ap, err := CheckProjectAndAuditPlan(s, projectName, apName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } + ap, exist, err := dms.GetAuditPlanWithInstanceFromProjectByName(projectUid, apName, s.GetAuditPlanFromProjectByName) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if !exist { + return controller.JSONBaseErrorReq(c, errAuditPlanNotExist) + } + l := log.NewEntry() reqSQLs := req.SQLs blackList, err := s.GetBlackListAuditPlanSQLs() @@ -990,26 +980,6 @@ func PartialSyncAuditPlanSQLs(c echo.Context) error { return controller.JSONBaseErrorReq(c, auditplan.UploadSQLs(l, ap, sqls, true)) } -func CheckProjectAndAuditPlan(s *model.Storage, projectName string, apName string) (*model.AuditPlan, error) { - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return nil, err - } - if archived { - return nil, ErrProjectArchived - } - - ap, exist, err := s.GetAuditPlanFromProjectByName(projectName, apName) - if err != nil { - return nil, err - } - if !exist { - return nil, errors.NewAuditPlanNotExistErr() - } - - return ap, nil -} - func convertToModelAuditPlanSQL(c echo.Context, auditPlan *model.AuditPlan, reqSQLs []*AuditPlanSQLReqV1) ([]*auditplan.SQL, error) { var p driver.Plugin var err error @@ -1103,19 +1073,13 @@ type TriggerAuditPlanResV1 struct { // @Success 200 {object} v1.TriggerAuditPlanResV1 // @router /v1/projects/{project_name}/audit_plans/{audit_plan_name}/trigger [post] func TriggerAuditPlan(c echo.Context) error { - projectName := c.Param("project_name") - apName := c.Param("audit_plan_name") - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } + apName := c.Param("audit_plan_name") - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, 0) + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, "") if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1139,44 +1103,6 @@ func TriggerAuditPlan(c echo.Context) error { }) } -// deprecated. will be removed when sqle-ee is not referenced. -func CheckCurrentUserCanAccessAuditPlan(c echo.Context, apName string, opCode int) error { - storage := model.GetStorage() - - ap, exist, err := storage.GetAuditPlanByName(apName) - if err != nil { - return err - } - if !exist { - return errAuditPlanNotExist - } - - if controller.GetUserName(c) == model.DefaultAdminUser { - return nil - } - - user, err := controller.GetCurrentUser(c) - if err != nil { - return err - } - - if ap.CreateUserID == user.ID { - return nil - } - if opCode > 0 { - instances, err := storage.GetUserCanOpInstances(user, []uint{uint(opCode)}) - if err != nil { - return controller.JSONBaseErrorReq(c, errors.NewUserNotPermissionError(model.GetOperationCodeDesc(uint(opCode)))) - } - for _, instance := range instances { - if ap.InstanceName == instance.Name { - return nil - } - } - } - return nil -} - type UpdateAuditPlanNotifyConfigReqV1 struct { NotifyInterval *int `json:"notify_interval" default:"10"` NotifyLevel *string `json:"notify_level" default:"warn" enums:"normal,notice,warn,error" valid:"oneof=normal notice warn error"` @@ -1202,19 +1128,15 @@ func UpdateAuditPlanNotifyConfig(c echo.Context) error { return err } - projectName := c.Param("project_name") - apName := c.Param("audit_plan_name") - - storage := model.GetStorage() - archived, err := storage.IsProjectArchived(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } + apName := c.Param("audit_plan_name") - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, 0) + storage := model.GetStorage() + + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, "") if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1270,10 +1192,13 @@ type GetAuditPlanNotifyConfigResDataV1 struct { // @Success 200 {object} v1.GetAuditPlanNotifyConfigResV1 // @router /v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config [get] func GetAuditPlanNotifyConfig(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } apName := c.Param("audit_plan_name") - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, model.OP_AUDIT_PLAN_VIEW_OTHERS) + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, v1.OpPermissionTypeViewOtherAuditPlan) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1314,10 +1239,13 @@ type TestAuditPlanNotifyConfigResDataV1 struct { // @Success 200 {object} v1.TestAuditPlanNotifyConfigResV1 // @router /v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config/test [get] func TestAuditPlanNotifyConfig(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } apName := c.Param("audit_plan_name") - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, 0) + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, "") if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1325,12 +1253,11 @@ func TestAuditPlanNotifyConfig(c echo.Context) error { return controller.JSONBaseErrorReq(c, errAuditPlanNotExist) } - s := model.GetStorage() - user, exist, err := s.GetUserByID(ap.CreateUserID) + // s := model.GetStorage() + _, err = controller.GetCurrentUser(c, dms.GetUser) if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { + // return controller.JSONBaseErrorReq(c, err) + // dms-todo: 需要判断用户是否存在,dms提供 return c.JSON(http.StatusOK, TestAuditPlanNotifyConfigResV1{ BaseRes: controller.NewBaseReq(nil), Data: TestAuditPlanNotifyConfigResDataV1{ @@ -1339,8 +1266,14 @@ func TestAuditPlanNotifyConfig(c echo.Context) error { }, }) } - ap.CreateUser = user + // user, exist, err := s.GetUserByID(ap.CreateUserID) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + + // dms-todo: notification + // ap.CreateUser = user err = notification.GetAuditPlanNotifier().Send(¬ification.TestNotify{}, ap) if err != nil { return c.JSON(http.StatusOK, TestAuditPlanNotifyConfigResV1{ @@ -1434,10 +1367,13 @@ func GetAuditPlanSQLs(c echo.Context) error { return err } - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } apName := c.Param("audit_plan_name") - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, model.OP_AUDIT_PLAN_VIEW_OTHERS) + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, v1.OpPermissionTypeViewOtherAuditPlan) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1515,10 +1451,13 @@ func GetAuditPlanReportSQLsV1(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } apName := c.Param("audit_plan_name") - ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, model.OP_AUDIT_PLAN_VIEW_OTHERS) + ap, exist, err := GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, v1.OpPermissionTypeViewOtherAuditPlan) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1606,7 +1545,7 @@ func ExportAuditPlanReportV1(c echo.Context) error { {"审核结果评分", strconv.FormatInt(int64(reportInfo.Score), 10)}, {"审核通过率", fmt.Sprintf("%v%%", reportInfo.PassRate*100)}, {"所属项目", projectName}, - {"扫描任务创建人", utils.AddDelTag(reportInfo.AuditPlan.CreateUser.DeletedAt, reportInfo.AuditPlan.CreateUser.Name)}, + {"扫描任务创建人", dms.GetUserNameWithDelTag(reportInfo.AuditPlan.CreateUserID)}, {"扫描任务类型", reportInfo.AuditPlan.Type}, {"数据库类型", reportInfo.AuditPlan.DBType}, {"审核的数据库", reportInfo.AuditPlan.InstanceDatabase}, diff --git a/sqle/api/controller/v1/auth.go b/sqle/api/controller/v1/auth.go deleted file mode 100644 index 6740b286fa..0000000000 --- a/sqle/api/controller/v1/auth.go +++ /dev/null @@ -1,333 +0,0 @@ -package v1 - -import ( - "crypto/tls" - _errors "errors" - "fmt" - "net/http" - "time" - - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper" - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/utils" - - "github.com/go-ldap/ldap/v3" - "github.com/labstack/echo/v4" -) - -type UserLoginReqV1 struct { - UserName string `json:"username" form:"username" example:"test" valid:"required"` - Password string `json:"password" form:"password" example:"123456" valid:"required"` -} - -type GetUserLoginResV1 struct { - controller.BaseRes - Data UserLoginResV1 `json:"data"` -} - -type UserLoginResV1 struct { - Token string `json:"token" example:"this is a jwt token string"` -} - -// @Summary 用户登录 -// @Description user login -// @Tags user -// @Id loginV1 -// @Param user body v1.UserLoginReqV1 true "user login request" -// @Success 200 {object} v1.GetUserLoginResV1 -// @router /v1/login [post] -func LoginV1(c echo.Context) error { - req := new(UserLoginReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - t, err := Login(c, req.UserName, req.Password) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return c.JSON(http.StatusOK, &GetUserLoginResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: UserLoginResV1{ - Token: t, // this token won't be used any more - }, - }) -} - -func Login(c echo.Context, userName, password string) (token string, err error) { - loginChecker, err := GetLoginCheckerByUserName(userName) - if err != nil { - return "", errors.New(errors.LoginAuthFail, err) - } - err = loginChecker.login(password) - if err != nil { - return "", errors.New(errors.LoginAuthFail, err) - } - - token, err = generateToken(userName) - if err != nil { - return "", errors.New(http.StatusInternalServerError, err) - } - - SetCookie(c, token) - - return -} - -func SetCookie(c echo.Context, token string) { - c.SetCookie(&http.Cookie{ - Name: "sqle-token", - Value: token, - Expires: time.Now().Add(tokenLifeTime), - Path: "/", - }) -} - -const tokenLifeTime = time.Hour * 24 - -func generateToken(userName string) (string, error) { - j := utils.NewJWT(utils.JWTSecretKey) - return j.CreateToken(userName, time.Now().Add(tokenLifeTime).Unix()) -} - -// GetLoginCheckerByUserName get login checker by user name and init login checker -func GetLoginCheckerByUserName(userName string) (LoginChecker, error) { - // get user metadata and config - s := model.GetStorage() - user, userExist, err := s.GetUserByName(userName) - if err != nil { - return nil, err - } - ldapC, ldapExist, err := s.GetLDAPConfiguration() - if err != nil { - return nil, err - } - - checkerType := loginCheckerTypeUnknown - exist := false - { // get login checker type - var u *model.User = nil - var l *model.LDAPConfiguration = nil - if userExist { - u = user - } - if ldapExist { - l = ldapC - } - checkerType, exist = getLoginCheckerType(u, l) - } - - // match login method - switch checkerType { - case loginCheckerTypeLDAP: - if !exist { - return newLdapLoginV3WhenUserNotExist(ldapC, userName), nil - } - return newLdapLoginV3WhenUserExist(ldapC, user), nil - case loginCheckerTypeSQLE: - return newSqleLogin(user), nil - default: - return nil, fmt.Errorf("the user does not exist or the password is wrong") - } -} - -type checkerType int - -const ( - loginCheckerTypeUnknown checkerType = iota - loginCheckerTypeSQLE - loginCheckerTypeLDAP -) - -// determine whether the login conditions are met according to the order of login priority -func getLoginCheckerType(user *model.User, ldapC *model.LDAPConfiguration) (checkerType checkerType, userExist bool) { - - // ldap login condition - if ldapC != nil && ldapC.Enable { - if user != nil && user.UserAuthenticationType == model.UserAuthenticationTypeLDAP { - return loginCheckerTypeLDAP, true - } - if user == nil { - return loginCheckerTypeLDAP, false - } - } - - // sqle login condition, oauth 2 and other login types of users can also log in through the account and password - if user != nil && (user.UserAuthenticationType != model.UserAuthenticationTypeLDAP) { - return loginCheckerTypeSQLE, true - } - - // no alternative login method - return loginCheckerTypeUnknown, user != nil -} - -type LoginChecker interface { - login(password string) (err error) -} - -type baseLoginChecker struct { - user *model.User -} - -// ldapLoginV3 version 3 ldap login verification logic. -type ldapLoginV3 struct { - baseLoginChecker - config *model.LDAPConfiguration - email string - userExist bool -} - -func newLdapLoginV3WhenUserExist(configuration *model.LDAPConfiguration, user *model.User) *ldapLoginV3 { - return &ldapLoginV3{ - config: configuration, - userExist: true, - baseLoginChecker: baseLoginChecker{ - user: user, - }, - } -} - -func newLdapLoginV3WhenUserNotExist(configuration *model.LDAPConfiguration, userName string) *ldapLoginV3 { - return &ldapLoginV3{ - config: configuration, - userExist: false, - baseLoginChecker: baseLoginChecker{ - user: &model.User{ - Name: userName, - }, - }, - } -} - -func (l *ldapLoginV3) login(password string) (err error) { - err = l.loginToLdap(password) - if err != nil { - return err - } - return l.autoRegisterUser(password) -} - -var errLdapLoginFailed = _errors.New("ldap login failed, username and password do not match") - -const ldapServerErrorFormat = "search user on ldap server failed: %v" - -func (l *ldapLoginV3) loginToLdap(password string) (err error) { - ldapC, _, err := model.GetStorage().GetLDAPConfiguration() - if err != nil { - return err - } - - var conn *ldap.Conn - if l.config.EnableSSL { - url := fmt.Sprintf("ldaps://%s:%s", ldapC.Host, ldapC.Port) - conn, err = ldap.DialURL(url, ldap.DialWithTLSConfig(&tls.Config{InsecureSkipVerify: true})) - } else { - url := fmt.Sprintf("ldap://%s:%s", ldapC.Host, ldapC.Port) - conn, err = ldap.DialURL(url) - } - if err != nil { - return fmt.Errorf("get ldap server connect failed: %v", err) - } - defer conn.Close() - - if err = conn.Bind(ldapC.ConnectDn, ldapC.ConnectPassword); err != nil { - return fmt.Errorf("bind ldap manager user failed: %v", err) - } - searchRequest := ldap.NewSearchRequest( - ldapC.BaseDn, - ldap.ScopeWholeSubtree, - ldap.NeverDerefAliases, - 0, - 0, - false, - fmt.Sprintf("(%s=%s)", ldapC.UserNameRdnKey, l.user.Name), - []string{}, - nil, - ) - result, err := conn.Search(searchRequest) - if err != nil { - return fmt.Errorf(ldapServerErrorFormat, err) - } - if len(result.Entries) == 0 { - return errLdapLoginFailed - } - if len(result.Entries) != 1 { - return fmt.Errorf(ldapServerErrorFormat, "the queried user is not unique, please check whether the relevant configuration is correct") - } - userDn := result.Entries[0].DN - if err = conn.Bind(userDn, password); err != nil { - return errLdapLoginFailed - } - l.email = result.Entries[0].GetAttributeValue(ldapC.UserEmailRdnKey) - return nil -} - -func (l *ldapLoginV3) autoRegisterUser(pwd string) (err error) { - if l.userExist { - return l.updateUser(pwd) - } - return l.registerUser(pwd) -} - -func (l *ldapLoginV3) registerUser(pwd string) (err error) { - user := &model.User{ - Name: l.user.Name, - Password: pwd, - Email: l.email, - UserAuthenticationType: model.UserAuthenticationTypeLDAP, - } - return model.GetStorage().Save(user) -} - -func (l *ldapLoginV3) updateUser(pwd string) (err error) { - if l.user.Password == pwd { - return nil - } - return model.GetStorage().UpdatePassword(l.user, pwd) -} - -// sqleLogin sqle login verification logic -type sqleLogin struct { - baseLoginChecker -} - -func newSqleLogin(user *model.User) *sqleLogin { - return &sqleLogin{ - baseLoginChecker: baseLoginChecker{ - user: user, - }, - } -} - -func (s *sqleLogin) login(password string) (err error) { - if password != s.user.Password { - return fmt.Errorf("password is wrong or user does not exist") - } - return nil -} - -// LogoutV1 -// @Summary 用户登出 -// @Description user logout -// @Tags user -// @Id logoutV1 -// @Success 200 {object} controller.BaseRes -// @router /v1/logout [post] -func LogoutV1(c echo.Context) error { - return c.JSON(http.StatusOK, controller.NewBaseReq(logout(c))) -} - -func logout(c echo.Context) error { - cookie, err := c.Cookie("sqle-token") - if err != nil { - return err - } - cookie.MaxAge = -1 // MaxAge<0 means delete cookie now - cookie.Path = "/" - c.SetCookie(cookie) - cloudbeaver_wrapper.UnbindCBSessionIdBySqleToken(cookie.Value) - return nil -} diff --git a/sqle/api/controller/v1/configuration.go b/sqle/api/controller/v1/configuration.go index 7b4f177988..84d8b2ef72 100644 --- a/sqle/api/controller/v1/configuration.go +++ b/sqle/api/controller/v1/configuration.go @@ -4,258 +4,18 @@ import ( "fmt" "net/http" "strconv" - "strings" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/service" "github.com/actiontech/sqle/sqle/api/controller" "github.com/actiontech/sqle/sqle/driver" - "github.com/actiontech/sqle/sqle/errors" + "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/notification" + "github.com/actiontech/sqle/sqle/pkg/im" "github.com/actiontech/sqle/sqle/pkg/im/dingding" - "github.com/actiontech/sqle/sqle/pkg/im/feishu" "github.com/labstack/echo/v4" - larkContact "github.com/larksuite/oapi-sdk-go/v3/service/contact/v3" ) -type UpdateSMTPConfigurationReqV1 struct { - EnableSMTPNotify *bool `json:"enable_smtp_notify" from:"enable_smtp_notify" description:"是否启用邮件通知"` - Host *string `json:"smtp_host" form:"smtp_host" example:"smtp.email.qq.com"` - Port *string `json:"smtp_port" form:"smtp_port" example:"465" valid:"omitempty,port"` - Username *string `json:"smtp_username" form:"smtp_username" example:"test@qq.com" valid:"omitempty,email"` - Password *string `json:"smtp_password" form:"smtp_password" example:"123"` - IsSkipVerify *bool `json:"is_skip_verify" form:"is_skip_verify" description:"是否跳过安全认证"` -} - -// @Summary 添加 SMTP 配置 -// @Description update SMTP configuration -// @Accept json -// @Id updateSMTPConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Param instance body v1.UpdateSMTPConfigurationReqV1 true "update SMTP configuration req" -// @Success 200 {object} controller.BaseRes -// @router /v1/configurations/smtp [patch] -func UpdateSMTPConfiguration(c echo.Context) error { - req := new(UpdateSMTPConfigurationReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - smtpC, _, err := s.GetSMTPConfiguration() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - { // disable - if req.EnableSMTPNotify != nil && !(*req.EnableSMTPNotify) { - // It is never possible to trigger an error here - _ = smtpC.EnableSMTPNotify.Scan(false) - return controller.JSONBaseErrorReq(c, s.Save(smtpC)) - } - } - - if req.Host != nil { - smtpC.Host = *req.Host - } - if req.Port != nil { - smtpC.Port = *req.Port - } - if req.Username != nil { - smtpC.Username = *req.Username - } - if req.Password != nil { - smtpC.Password = *req.Password - } - if req.EnableSMTPNotify != nil { - // It is never possible to trigger an error here - _ = smtpC.EnableSMTPNotify.Scan(*req.EnableSMTPNotify) - } - if req.IsSkipVerify != nil { - smtpC.IsSkipVerify = *req.IsSkipVerify - } - - if err := s.Save(smtpC); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return controller.JSONBaseErrorReq(c, nil) -} - -type GetSMTPConfigurationResV1 struct { - controller.BaseRes - Data SMTPConfigurationResV1 `json:"data"` -} - -type SMTPConfigurationResV1 struct { - EnableSMTPNotify bool `json:"enable_smtp_notify"` - Host string `json:"smtp_host"` - Port string `json:"smtp_port"` - Username string `json:"smtp_username"` - IsSkipVerify bool `json:"is_skip_verify"` -} - -// @Summary 获取 SMTP 配置 -// @Description get SMTP configuration -// @Id getSMTPConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetSMTPConfigurationResV1 -// @router /v1/configurations/smtp [get] -func GetSMTPConfiguration(c echo.Context) error { - s := model.GetStorage() - smtpC, _, err := s.GetSMTPConfiguration() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return c.JSON(http.StatusOK, &GetSMTPConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: SMTPConfigurationResV1{ - EnableSMTPNotify: smtpC.EnableSMTPNotify.Bool, - Host: smtpC.Host, - Port: smtpC.Port, - Username: smtpC.Username, - IsSkipVerify: smtpC.IsSkipVerify, - }, - }) -} - -type TestSMTPConfigurationReqV1 struct { - RecipientAddr string `json:"recipient_addr" from:"recipient_addr" description:"消息接收者邮箱地址" valid:"required,email"` -} - -type TestSMTPConfigurationResV1 struct { - controller.BaseRes - Data TestSMTPConfigurationResDataV1 `json:"data"` -} - -type TestSMTPConfigurationResDataV1 struct { - IsSMTPSendNormal bool `json:"is_smtp_send_normal"` - SendErrorMessage string `json:"send_error_message,omitempty"` -} - -// TestSMTPConfigurationV1 used to test SMTP notifications -// @Summary 测试 邮箱 配置 -// @Description test SMTP configuration -// @Accept json -// @Id testSMTPConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Param req body v1.TestSMTPConfigurationReqV1 true "test SMTP configuration req" -// @Success 200 {object} v1.TestSMTPConfigurationResV1 -// @router /v1/configurations/smtp/test [post] -func TestSMTPConfigurationV1(c echo.Context) error { - req := new(TestSMTPConfigurationReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - s := model.GetStorage() - smtpC, exist, err := s.GetSMTPConfiguration() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return c.JSON(http.StatusOK, &TestSMTPConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: newSmtpConnectableResV1(false, "SMTP is not configured"), - }) - } - - if !smtpC.EnableSMTPNotify.Bool { - return c.JSON(http.StatusOK, &TestSMTPConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: newSmtpConnectableResV1(false, "SMTP notice is not enabled"), - }) - } - - addr := req.RecipientAddr - notifier := ¬ification.EmailNotifier{} - err = notifier.Notify(¬ification.TestNotify{}, []*model.User{ - { - Email: addr, - }, - }) - if err != nil { - return c.JSON(http.StatusOK, &TestSMTPConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: newSmtpConnectableResV1(false, err.Error()), - }) - } - - return c.JSON(http.StatusOK, &TestSMTPConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: newSmtpConnectableResV1(true, "ok"), - }) -} - -func newSmtpConnectableResV1(isSendNormal bool, errMsg string) TestSMTPConfigurationResDataV1 { - return TestSMTPConfigurationResDataV1{ - IsSMTPSendNormal: isSendNormal, - SendErrorMessage: errMsg, - } -} - -type TestWeChatConfigurationReqV1 struct { - RecipientID string `json:"recipient_id" from:"recipient_id" description:"消息接收者企业微信ID"` -} - -type TestWeChatConfigurationResV1 struct { - controller.BaseRes - Data TestWeChatConfigurationResDataV1 `json:"data"` -} - -type TestWeChatConfigurationResDataV1 struct { - IsWeChatSendNormal bool `json:"is_wechat_send_normal"` - SendErrorMessage string `json:"send_error_message,omitempty"` -} - -// TestWeChatConfigurationV1 used to test WeChat notifications -// @Summary 测试 企业微信 配置 -// @Description test WeChat configuration -// @Accept json -// @Id testWeChatConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Param instance body v1.TestWeChatConfigurationReqV1 true "test WeChat configuration req" -// @Success 200 {object} v1.TestWeChatConfigurationResV1 -// @router /v1/configurations/wechat/test [post] -func TestWeChatConfigurationV1(c echo.Context) error { - return testWeChatConfigurationV1(c) -} - -func testWeChatConfigurationV1(c echo.Context) error { - req := new(TestWeChatConfigurationReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - testID := req.RecipientID - notifier := ¬ification.WeChatNotifier{} - err := notifier.Notify(¬ification.TestNotify{}, []*model.User{ - { - Name: testID, - WeChatID: testID, - }, - }) - if err != nil { - return c.JSON(http.StatusOK, &TestWeChatConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: TestWeChatConfigurationResDataV1{ - IsWeChatSendNormal: false, - SendErrorMessage: err.Error(), - }, - }) - } - return c.JSON(http.StatusOK, &TestWeChatConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: TestWeChatConfigurationResDataV1{ - IsWeChatSendNormal: true, - SendErrorMessage: "ok", - }, - }) -} - type GetDingTalkConfigurationResV1 struct { controller.BaseRes Data DingTalkConfigurationV1 `json:"data"` @@ -406,555 +166,106 @@ func TestDingTalkConfigV1(c echo.Context) error { }) } -type GetFeishuConfigurationResV1 struct { - controller.BaseRes - Data FeishuConfigurationV1 `json:"data"` -} - -type FeishuConfigurationV1 struct { - AppID string `json:"app_id"` - IsFeishuNotificationEnabled bool `json:"is_feishu_notification_enabled"` -} - -// GetFeishuConfigurationV1 -// @Summary 获取飞书配置 -// @Description get feishu configuration -// @Id getFeishuConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetFeishuConfigurationResV1 -// @router /v1/configurations/feishu [get] -func GetFeishuConfigurationV1(c echo.Context) error { - s := model.GetStorage() - feishuCfg, exist, err := s.GetImConfigByType(model.ImTypeFeishu) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return c.JSON(http.StatusOK, &GetFeishuConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: FeishuConfigurationV1{}, - }) - } - - return c.JSON(http.StatusOK, &GetFeishuConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: FeishuConfigurationV1{ - AppID: feishuCfg.AppKey, - IsFeishuNotificationEnabled: feishuCfg.IsEnable, - }, - }) -} - -type UpdateFeishuConfigurationReqV1 struct { - AppID *string `json:"app_id" form:"app_id" validate:"required" description:"飞书应用ID"` - AppSecret *string `json:"app_secret" form:"app_secret" validate:"required" description:"飞书应用Secret"` - IsFeishuNotificationEnabled *bool `json:"is_feishu_notification_enabled" from:"is_feishu_notification_enabled" validate:"required" description:"是否启用飞书推送"` +type UpdateSystemVariablesReqV1 struct { + WorkflowExpiredHours *int `json:"workflow_expired_hours" form:"workflow_expired_hours" example:"720"` + Url *string `json:"url" form:"url" example:"http://10.186.61.32:8080" validate:"url"` + OperationRecordExpiredHours *int `json:"operation_record_expired_hours" form:"operation_record_expired_hours" example:"2160"` } -// UpdateFeishuConfigurationV1 -// @Summary 添加或更新飞书配置 -// @Description update feishu configuration +// @Summary 修改系统变量 +// @Description update system variables // @Accept json -// @Id updateFeishuConfigurationV1 +// @Id updateSystemVariablesV1 // @Tags configuration // @Security ApiKeyAuth -// @Param param body v1.UpdateFeishuConfigurationReqV1 true "update feishu configuration req" +// @Param instance body v1.UpdateSystemVariablesReqV1 true "update system variables request" // @Success 200 {object} controller.BaseRes -// @router /v1/configurations/feishu [patch] -func UpdateFeishuConfigurationV1(c echo.Context) error { - req := new(UpdateFeishuConfigurationReqV1) +// @router /v1/configurations/system_variables [patch] +func UpdateSystemVariables(c echo.Context) error { + req := new(UpdateSystemVariablesReqV1) if err := controller.BindAndValidateReq(c, req); err != nil { return err } + s := model.GetStorage() - feishuCfg, _, err := s.GetImConfigByType(model.ImTypeFeishu) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - { // disable - if req.IsFeishuNotificationEnabled != nil && !(*req.IsFeishuNotificationEnabled) { - feishuCfg.IsEnable = false - return controller.JSONBaseErrorReq(c, s.Save(feishuCfg)) - } + var systemVariables []model.SystemVariable + if req.WorkflowExpiredHours != nil { + systemVariables = append(systemVariables, model.SystemVariable{ + Key: model.SystemVariableWorkflowExpiredHours, + Value: fmt.Sprintf("%v", *req.WorkflowExpiredHours), + }) } - if req.AppID != nil { - feishuCfg.AppKey = *req.AppID - } - if req.AppSecret != nil { - feishuCfg.AppSecret = *req.AppSecret + if req.OperationRecordExpiredHours != nil { + systemVariables = append(systemVariables, model.SystemVariable{ + Key: model.SystemVariableOperationRecordExpiredHours, + Value: strconv.Itoa(*req.OperationRecordExpiredHours), + }) } - if req.IsFeishuNotificationEnabled != nil { - feishuCfg.IsEnable = *req.IsFeishuNotificationEnabled + + if req.Url != nil { + systemVariables = append(systemVariables, model.SystemVariable{ + Key: model.SystemVariableSqleUrl, + Value: *req.Url, + }) } - feishuCfg.Type = model.ImTypeFeishu - if err := s.Save(feishuCfg); err != nil { + if err := s.PathSaveSystemVariables(systemVariables); err != nil { return controller.JSONBaseErrorReq(c, err) } - return controller.JSONBaseErrorReq(c, nil) -} - -type TestFeishuConfigurationReqV1 struct { - AccountType string `json:"account_type" form:"account_type" enums:"email,phone" valid:"required"` - Account string `json:"account" form:"account" valid:"required" description:"绑定了飞书的手机号或邮箱"` -} -type TestFeishuConfigResDataV1 struct { - IsMessageSentNormally bool `json:"is_message_sent_normally"` - ErrorMessage string `json:"error_message,omitempty"` + return controller.JSONBaseErrorReq(c, nil) } -type TestFeishuConfigResV1 struct { +type GetSystemVariablesResV1 struct { controller.BaseRes - Data TestFeishuConfigResDataV1 `json:"data"` + Data SystemVariablesResV1 `json:"data"` } -const ( - FeishuAccountTypeEmail = "email" - FeishuAccountTypePhone = "phone" -) +type SystemVariablesResV1 struct { + WorkflowExpiredHours int `json:"workflow_expired_hours"` + Url string `json:"url"` + OperationRecordExpiredHours int `json:"operation_record_expired_hours"` +} -// TestFeishuConfigV1 -// @Summary 测试飞书配置 -// @Description test feishu configuration -// @Accept json -// @Id testFeishuConfigV1 +// @Summary 获取系统变量 +// @Description get system variables +// @Id getSystemVariablesV1 // @Tags configuration // @Security ApiKeyAuth -// @Param req body v1.TestFeishuConfigurationReqV1 true "test feishu configuration req" -// @Success 200 {object} v1.TestFeishuConfigResV1 -// @router /v1/configurations/feishu/test [post] -func TestFeishuConfigV1(c echo.Context) error { - req := new(TestFeishuConfigurationReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - var email, phone []string - switch req.AccountType { - case FeishuAccountTypeEmail: - err := controller.Validate(struct { - Email string `valid:"email"` - }{req.Account}) - if err != nil { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, err)) - } - email = append(email, req.Account) - case FeishuAccountTypePhone: - phone = append(phone, req.Account) - default: - return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, fmt.Errorf("unknown account type: %v", req.AccountType))) - } - +// @Success 200 {object} v1.GetSystemVariablesResV1 +// @router /v1/configurations/system_variables [get] +func GetSystemVariables(c echo.Context) error { s := model.GetStorage() - feishuCfg, exist, err := s.GetImConfigByType(model.ImTypeFeishu) + systemVariables, err := s.GetAllSystemVariables() if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return c.JSON(http.StatusOK, &TestFeishuConfigResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: TestFeishuConfigResDataV1{ - IsMessageSentNormally: false, - ErrorMessage: "feishu configuration doesn't exist", - }, - }) - } - client := feishu.NewFeishuClient(feishuCfg.AppKey, feishuCfg.AppSecret) - feishuUsers, err := client.GetUsersByEmailOrMobileWithLimitation(email, phone, larkContact.UserIdTypeGetUserUserId) + expiredHours, err := strconv.Atoi(systemVariables[model.SystemVariableWorkflowExpiredHours].Value) if err != nil { - return c.JSON(http.StatusOK, &TestFeishuConfigResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: TestFeishuConfigResDataV1{ - IsMessageSentNormally: false, - ErrorMessage: fmt.Sprintf("get user_ids failed: %v", err), - }, - }) - } - - if len(feishuUsers) == 0 { - return c.JSON(http.StatusOK, &TestFeishuConfigResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: TestFeishuConfigResDataV1{ - IsMessageSentNormally: false, - ErrorMessage: "can not find matched feishu user", - }, - }) + return controller.JSONBaseErrorReq(c, err) } - n := ¬ification.TestNotify{} - content, err := notification.BuildFeishuMessageBody(n) + operationRecordExpiredHours, err := strconv.Atoi(systemVariables[model.SystemVariableOperationRecordExpiredHours].Value) if err != nil { - return c.JSON(http.StatusOK, &TestFeishuConfigResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: TestFeishuConfigResDataV1{ - IsMessageSentNormally: false, - ErrorMessage: fmt.Sprintf("convert content failed: %v", err), - }, - }) - } - for uid := range feishuUsers { - if err = client.SendMessage(feishu.FeishuReceiverIdTypeUserId, uid, feishu.FeishuSendMessageMsgTypePost, content); err != nil { - return c.JSON(http.StatusOK, &TestFeishuConfigResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: TestFeishuConfigResDataV1{ - IsMessageSentNormally: false, - ErrorMessage: err.Error(), - }, - }) - } + return controller.JSONBaseErrorReq(c, err) } - return c.JSON(http.StatusOK, &TestFeishuConfigResV1{ + return c.JSON(http.StatusOK, &GetSystemVariablesResV1{ BaseRes: controller.NewBaseReq(nil), - Data: TestFeishuConfigResDataV1{ - IsMessageSentNormally: true, + Data: SystemVariablesResV1{ + WorkflowExpiredHours: expiredHours, + Url: systemVariables[model.SystemVariableSqleUrl].Value, + OperationRecordExpiredHours: operationRecordExpiredHours, }, }) - } -type UpdateWeChatConfigurationReqV1 struct { - EnableWeChatNotify *bool `json:"enable_wechat_notify" from:"enable_wechat_notify" description:"是否启用微信通知"` - CorpID *string `json:"corp_id" from:"corp_id" description:"企业微信ID"` - CorpSecret *string `json:"corp_secret" from:"corp_secret" description:"企业微信ID对应密码"` - AgentID *int `json:"agent_id" from:"agent_id" description:"企业微信应用ID"` - SafeEnabled *bool `json:"safe_enabled" from:"safe_enabled" description:"是否对传输信息加密"` - ProxyIP *string `json:"proxy_ip" from:"proxy_ip" description:"企业微信代理服务器IP"` -} - -// UpdateWeChatConfigurationV1 used to configure WeChat notifications -// @Summary 添加 企业微信 配置 -// @Description update WeChat configuration -// @Accept json -// @Id updateWeChatConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Param instance body v1.UpdateWeChatConfigurationReqV1 true "update WeChat configuration req" -// @Success 200 {object} controller.BaseRes -// @router /v1/configurations/wechat [patch] -func UpdateWeChatConfigurationV1(c echo.Context) error { - return updateWeChatConfigurationV1(c) -} - -func updateWeChatConfigurationV1(c echo.Context) error { - req := new(UpdateWeChatConfigurationReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - wechatC, _, err := s.GetWeChatConfiguration() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - { // disable - if req.EnableWeChatNotify != nil && !(*req.EnableWeChatNotify) { - wechatC.EnableWeChatNotify = false - return controller.JSONBaseErrorReq(c, s.Save(wechatC)) - } - } - - if req.CorpID != nil { - wechatC.CorpID = *req.CorpID - } - if req.CorpSecret != nil { - wechatC.CorpSecret = *req.CorpSecret - } - if req.AgentID != nil { - wechatC.AgentID = *req.AgentID - } - if req.ProxyIP != nil { - wechatC.ProxyIP = *req.ProxyIP - } - if req.EnableWeChatNotify != nil { - wechatC.EnableWeChatNotify = *req.EnableWeChatNotify - } - if req.SafeEnabled != nil { - wechatC.SafeEnabled = *req.SafeEnabled - } - - if err := s.Save(wechatC); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return controller.JSONBaseErrorReq(c, nil) -} - -type GetWeChatConfigurationResV1 struct { - controller.BaseRes - Data WeChatConfigurationResV1 `json:"data"` -} - -type WeChatConfigurationResV1 struct { - EnableWeChatNotify bool `json:"enable_wechat_notify"` - CorpID string `json:"corp_id"` - AgentID int `json:"agent_id"` - SafeEnabled bool `json:"safe_enabled"` - ProxyIP string `json:"proxy_ip"` -} - -// GetWeChatConfiguration used to get wechat configure -// @Summary 获取 企业微信 配置 -// @Description get WeChat configuration -// @Id getWeChatConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetWeChatConfigurationResV1 -// @router /v1/configurations/wechat [get] -func GetWeChatConfiguration(c echo.Context) error { - return getWeChatConfiguration(c) -} - -func getWeChatConfiguration(c echo.Context) error { - s := model.GetStorage() - wechatC, _, err := s.GetWeChatConfiguration() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return c.JSON(http.StatusOK, &GetWeChatConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: WeChatConfigurationResV1{ - EnableWeChatNotify: wechatC.EnableWeChatNotify, - CorpID: wechatC.CorpID, - AgentID: wechatC.AgentID, - SafeEnabled: wechatC.SafeEnabled, - ProxyIP: wechatC.ProxyIP, - }, - }) -} - -type GetLDAPConfigurationResV1 struct { - controller.BaseRes - Data LDAPConfigurationResV1 `json:"data"` -} - -type LDAPConfigurationReqV1 struct { - EnableLdap *bool `json:"enable_ldap"` - EnableSSL *bool `json:"enable_ssl"` - LdapServerHost *string `json:"ldap_server_host"` - LdapServerPort *string `json:"ldap_server_port"` - LdapConnectDn *string `json:"ldap_connect_dn"` - LdapConnectPwd *string `json:"ldap_connect_pwd"` - LdapSearchBaseDn *string `json:"ldap_search_base_dn"` - LdapUserNameRdnKey *string `json:"ldap_user_name_rdn_key"` - LdapUserEmailRdnKey *string `json:"ldap_user_email_rdn_key"` -} - -type LDAPConfigurationResV1 struct { - EnableLdap bool `json:"enable_ldap"` - EnableSSL bool `json:"enable_ssl"` - LdapServerHost string `json:"ldap_server_host"` - LdapServerPort string `json:"ldap_server_port"` - LdapConnectDn string `json:"ldap_connect_dn"` - LdapSearchBaseDn string `json:"ldap_search_base_dn"` - LdapUserNameRdnKey string `json:"ldap_user_name_rdn_key"` - LdapUserEmailRdnKey string `json:"ldap_user_email_rdn_key"` -} - -// @Summary 获取 LDAP 配置 -// @Description get LDAP configuration -// @Id getLDAPConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetLDAPConfigurationResV1 -// @router /v1/configurations/ldap [get] -func GetLDAPConfiguration(c echo.Context) error { - s := model.GetStorage() - ldapC, _, err := s.GetLDAPConfiguration() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return c.JSON(http.StatusOK, &GetLDAPConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: LDAPConfigurationResV1{ - EnableLdap: ldapC.Enable, - EnableSSL: ldapC.EnableSSL, - LdapServerHost: ldapC.Host, - LdapServerPort: ldapC.Port, - LdapConnectDn: ldapC.ConnectDn, - LdapSearchBaseDn: ldapC.BaseDn, - LdapUserNameRdnKey: ldapC.UserNameRdnKey, - LdapUserEmailRdnKey: ldapC.UserEmailRdnKey, - }, - }) -} - -// @Summary 添加 LDAP 配置 -// @Description update LDAP configuration -// @Accept json -// @Id updateLDAPConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Param instance body v1.LDAPConfigurationReqV1 true "update LDAP configuration req" -// @Success 200 {object} controller.BaseRes -// @router /v1/configurations/ldap [patch] -func UpdateLDAPConfiguration(c echo.Context) error { - req := new(LDAPConfigurationReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - ldapC, _, err := s.GetLDAPConfiguration() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - { // disable - if req.EnableLdap != nil && !(*req.EnableLdap) { - ldapC.Enable = false - return controller.JSONBaseErrorReq(c, s.Save(ldapC)) - } - } - - { // patch ldap config - - if req.EnableLdap != nil { - ldapC.Enable = *req.EnableLdap - } - - if req.EnableSSL != nil { - ldapC.EnableSSL = *req.EnableSSL - } - - if req.LdapServerHost != nil { - ldapC.Host = *req.LdapServerHost - } - - if req.LdapServerPort != nil { - ldapC.Port = *req.LdapServerPort - } - - if req.LdapConnectDn != nil { - ldapC.ConnectDn = *req.LdapConnectDn - } - - if req.LdapConnectPwd != nil { - ldapC.ConnectPassword = *req.LdapConnectPwd - } - - if req.LdapSearchBaseDn != nil { - ldapC.BaseDn = *req.LdapSearchBaseDn - } - - if req.LdapUserNameRdnKey != nil { - ldapC.UserNameRdnKey = *req.LdapUserNameRdnKey - } - - if req.LdapUserEmailRdnKey != nil { - ldapC.UserEmailRdnKey = *req.LdapUserEmailRdnKey - } - - } - if err := s.Save(ldapC); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return controller.JSONBaseErrorReq(c, nil) -} - -type UpdateSystemVariablesReqV1 struct { - WorkflowExpiredHours *int `json:"workflow_expired_hours" form:"workflow_expired_hours" example:"720"` - Url *string `json:"url" form:"url" example:"http://10.186.61.32:8080" validate:"url"` - OperationRecordExpiredHours *int `json:"operation_record_expired_hours" form:"operation_record_expired_hours" example:"2160"` -} - -// @Summary 修改系统变量 -// @Description update system variables -// @Accept json -// @Id updateSystemVariablesV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Param instance body v1.UpdateSystemVariablesReqV1 true "update system variables request" -// @Success 200 {object} controller.BaseRes -// @router /v1/configurations/system_variables [patch] -func UpdateSystemVariables(c echo.Context) error { - req := new(UpdateSystemVariablesReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - s := model.GetStorage() - - var systemVariables []model.SystemVariable - if req.WorkflowExpiredHours != nil { - systemVariables = append(systemVariables, model.SystemVariable{ - Key: model.SystemVariableWorkflowExpiredHours, - Value: fmt.Sprintf("%v", *req.WorkflowExpiredHours), - }) - } - - if req.OperationRecordExpiredHours != nil { - systemVariables = append(systemVariables, model.SystemVariable{ - Key: model.SystemVariableOperationRecordExpiredHours, - Value: strconv.Itoa(*req.OperationRecordExpiredHours), - }) - } - - if req.Url != nil { - systemVariables = append(systemVariables, model.SystemVariable{ - Key: model.SystemVariableSqleUrl, - Value: *req.Url, - }) - } - - if err := s.PathSaveSystemVariables(systemVariables); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return controller.JSONBaseErrorReq(c, nil) -} - -type GetSystemVariablesResV1 struct { - controller.BaseRes - Data SystemVariablesResV1 `json:"data"` -} - -type SystemVariablesResV1 struct { - WorkflowExpiredHours int `json:"workflow_expired_hours"` - Url string `json:"url"` - OperationRecordExpiredHours int `json:"operation_record_expired_hours"` -} - -// @Summary 获取系统变量 -// @Description get system variables -// @Id getSystemVariablesV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetSystemVariablesResV1 -// @router /v1/configurations/system_variables [get] -func GetSystemVariables(c echo.Context) error { - s := model.GetStorage() - systemVariables, err := s.GetAllSystemVariables() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - expiredHours, err := strconv.Atoi(systemVariables[model.SystemVariableWorkflowExpiredHours].Value) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - operationRecordExpiredHours, err := strconv.Atoi(systemVariables[model.SystemVariableOperationRecordExpiredHours].Value) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return c.JSON(http.StatusOK, &GetSystemVariablesResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: SystemVariablesResV1{ - WorkflowExpiredHours: expiredHours, - Url: systemVariables[model.SystemVariableSqleUrl].Value, - OperationRecordExpiredHours: operationRecordExpiredHours, - }, - }) -} - -type GetDriversResV1 struct { - controller.BaseRes - Data DriversResV1 `json:"data"` +type GetDriversResV1 struct { + controller.BaseRes + Data DriversResV1 `json:"data"` } type DriversResV1 struct { @@ -976,396 +287,16 @@ func GetDrivers(c echo.Context) error { }) } -type GetSQLEInfoResV1 struct { - controller.BaseRes - Data GetSQLEInfoResDataV1 `json:"data"` -} - -type GetSQLEInfoResDataV1 struct { - Version string `json:"version"` - LogoUrl string `json:"logo_url"` - Title string `json:"title"` -} - -// GetSQLEInfo get sqle basic info -// @Summary 获取 sqle 基本信息 -// @Description get sqle basic info -// @Id getSQLEInfoV1 -// @Tags global -// @Success 200 {object} v1.GetSQLEInfoResV1 -// @router /v1/basic_info [get] -func GetSQLEInfo(c echo.Context) error { - return getSQLEInfo(c) -} - -type GetOauth2ConfigurationResV1 struct { - controller.BaseRes - Data GetOauth2ConfigurationResDataV1 `json:"data"` -} - -type GetOauth2ConfigurationResDataV1 struct { - EnableOauth2 bool `json:"enable_oauth2"` - ClientID string `json:"client_id"` - ClientHost string `json:"client_host"` - ServerAuthUrl string `json:"server_auth_url"` - ServerTokenUrl string `json:"server_token_url"` - ServerUserIdUrl string `json:"server_user_id_url"` - Scopes []string `json:"scopes"` - AccessTokenTag string `json:"access_token_tag"` - UserIdTag string `json:"user_id_tag"` - LoginTip string `json:"login_tip"` -} - -// @Summary 获取 Oauth2 配置 -// @Description get Oauth2 configuration -// @Id getOauth2ConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetOauth2ConfigurationResV1 -// @router /v1/configurations/oauth2 [get] -func GetOauth2Configuration(c echo.Context) error { - s := model.GetStorage() - oauth2C, _, err := s.GetOauth2Configuration() - return c.JSON(http.StatusOK, &GetOauth2ConfigurationResV1{ - BaseRes: controller.NewBaseReq(err), - Data: GetOauth2ConfigurationResDataV1{ - EnableOauth2: oauth2C.EnableOauth2, - ClientID: oauth2C.ClientID, - ClientHost: oauth2C.ClientHost, - ServerAuthUrl: oauth2C.ServerAuthUrl, - ServerTokenUrl: oauth2C.ServerTokenUrl, - ServerUserIdUrl: oauth2C.ServerUserIdUrl, - Scopes: oauth2C.GetScopes(), - AccessTokenTag: oauth2C.AccessTokenTag, - UserIdTag: oauth2C.UserIdTag, - LoginTip: oauth2C.LoginTip, - }, - }) -} - -type Oauth2ConfigurationReqV1 struct { - EnableOauth2 *bool `json:"enable_oauth2"` - ClientID *string `json:"client_id"` - ClientKey *string `json:"client_key"` - ClientHost *string `json:"client_host"` - ServerAuthUrl *string `json:"server_auth_url"` - ServerTokenUrl *string `json:"server_token_url"` - ServerUserIdUrl *string `json:"server_user_id_url"` - Scopes *[]string `json:"scopes"` - AccessTokenTag *string `json:"access_token_tag"` - UserIdTag *string `json:"user_id_tag"` - LoginTip *string `json:"login_tip"` -} - -// @Summary 修改 Oauth2 配置 -// @Description update Oauth2 configuration -// @Accept json -// @Id updateOauth2ConfigurationV1 -// @Tags configuration -// @Security ApiKeyAuth -// @Param conf body v1.Oauth2ConfigurationReqV1 true "update Oauth2 configuration req" -// @Success 200 {object} controller.BaseRes -// @router /v1/configurations/oauth2 [patch] -func UpdateOauth2Configuration(c echo.Context) error { - req := new(Oauth2ConfigurationReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - oauth2C, _, err := s.GetOauth2Configuration() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - { // disable - if req.EnableOauth2 != nil && !(*req.EnableOauth2) { - oauth2C.EnableOauth2 = false - return controller.JSONBaseErrorReq(c, s.Save(oauth2C)) - } - } - - { // patch oauth2 config - if req.EnableOauth2 != nil { - oauth2C.EnableOauth2 = *req.EnableOauth2 - } - if req.ClientID != nil { - oauth2C.ClientID = *req.ClientID - } - if req.ClientKey != nil { - oauth2C.ClientKey = *req.ClientKey - } - if req.ClientHost != nil { - oauth2C.ClientHost = *req.ClientHost - } - if req.ServerAuthUrl != nil { - oauth2C.ServerAuthUrl = *req.ServerAuthUrl - } - if req.ServerTokenUrl != nil { - oauth2C.ServerTokenUrl = *req.ServerTokenUrl - } - if req.ServerUserIdUrl != nil { - oauth2C.ServerUserIdUrl = *req.ServerUserIdUrl - } - if req.Scopes != nil { - oauth2C.SetScopes(*req.Scopes) - } - if req.AccessTokenTag != nil { - oauth2C.AccessTokenTag = *req.AccessTokenTag - } - if req.UserIdTag != nil { - oauth2C.UserIdTag = *req.UserIdTag - } - if req.LoginTip != nil { - oauth2C.LoginTip = *req.LoginTip - } - - } - - return controller.JSONBaseErrorReq(c, s.Save(oauth2C)) -} - -type GetOauth2TipsResV1 struct { - controller.BaseRes - Data GetOauth2TipsResDataV1 `json:"data"` -} - -type GetOauth2TipsResDataV1 struct { - EnableOauth2 bool `json:"enable_oauth2"` - LoginTip string `json:"login_tip"` -} - -// @Summary 获取 Oauth2 基本信息 -// @Description get Oauth2 tips -// @Id getOauth2Tips -// @Tags configuration -// @Success 200 {object} v1.GetOauth2TipsResV1 -// @router /v1/configurations/oauth2/tips [get] -func GetOauth2Tips(c echo.Context) error { - s := model.GetStorage() - oauth2C, _, err := s.GetOauth2Configuration() - return c.JSON(http.StatusOK, &GetOauth2TipsResV1{ - BaseRes: controller.NewBaseReq(err), - Data: GetOauth2TipsResDataV1{ - EnableOauth2: oauth2C.EnableOauth2, - LoginTip: oauth2C.LoginTip, - }, - }) -} - -type GetSQLQueryConfigurationResV1 struct { - controller.BaseRes - Data GetSQLQueryConfigurationResDataV1 `json:"data"` -} - -type GetSQLQueryConfigurationResDataV1 struct { - EnableSQLQuery bool `json:"enable_sql_query"` - SQLQueryRootURI string `json:"sql_query_root_uri"` -} - -// @Summary 获取SQL查询配置信息 -// @Description get sqle query configuration -// @Id getSQLQueryConfiguration -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetSQLQueryConfigurationResV1 -// @router /v1/configurations/sql_query [get] -func GetSQLQueryConfiguration(c echo.Context) error { - return c.JSON(http.StatusOK, GetSQLQueryConfigurationResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: GetSQLQueryConfigurationResDataV1{ - EnableSQLQuery: service.IsCloudBeaverConfigured(), - SQLQueryRootURI: service.CbRootUri, - }, - }) -} - -type UploadLogoResV1 struct { - controller.BaseRes - Data UploadLogoResDataV1 `json:"data"` -} - -type UploadLogoResDataV1 struct { - LogoUrl string `json:"logo_url"` -} - -// UploadLogo -// @Summary 上传Logo -// @Description upload logo -// @Id uploadLogo -// @Tags configuration -// @Accept mpfd -// @Security ApiKeyAuth -// @Param logo formData file true "logo file" -// @Success 200 {object} v1.UploadLogoResV1 -// @router /v1/configurations/personalise/logo [post] -func UploadLogo(c echo.Context) error { - return uploadLogo(c) -} - -type GetLogoReqV1 struct { - Timestamp string `query:"timestamp"` -} - -// GetLogo -// @Summary 获取logo -// @Description get logo -// @Id getLogo -// @Tags configuration -// @Param timestamp query string false "timestamp" -// @Success 200 {file} file "get logo" -// @router /v1/static/logo [get] -func GetLogo(c echo.Context) error { - return getLogo(c) -} - -type PersonaliseReqV1 struct { - Title *string `json:"title"` -} - -// UpdatePersonaliseConfig -// @Summary 更新个性化设置 -// @Description update personalise config -// @Id personalise -// @Tags configuration -// @Security ApiKeyAuth -// @Param conf body v1.PersonaliseReqV1 true "personalise req" -// @Success 200 {object} controller.BaseRes -// @router /v1/configurations/personalise [patch] -func UpdatePersonaliseConfig(c echo.Context) error { - return updatePersonaliseConfig(c) -} - -type WebHookConfigV1 struct { - Enable *bool `json:"enable" description:"是否启用"` - MaxRetryTimes *int `json:"max_retry_times" description:"最大重试次数"` - RetryIntervalSeconds *int `json:"retry_interval_seconds" description:"请求重试间隔"` - Token *string `json:"token" description:"token 令牌"` - URL *string `json:"url" description:"回调API URL"` -} - -// UpdateWorkflowWebHookConfig -// @Summary 更新工单 WebHook 配置 -// @Description update webhook config -// @Id updateGlobalWebHookConfig -// @Tags configuration -// @Security ApiKeyAuth -// @Param request body v1.WebHookConfigV1 true "update webhook config" -// @Success 200 {object} controller.BaseRes -// @Router /v1/configurations/webhook [patch] -func UpdateWorkflowWebHookConfig(c echo.Context) error { - req := new(WebHookConfigV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - cfg, _, err := s.GetWorkflowWebHookConfig() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - { - if req.Enable != nil && !(*req.Enable) { - cfg.Enable = false - return controller.JSONBaseErrorReq(c, s.Save(cfg)) - } - } - - if req.Enable != nil { - cfg.Enable = *req.Enable - } - if req.MaxRetryTimes != nil { - if *req.MaxRetryTimes < 0 || *req.MaxRetryTimes > 5 { - err = errors.NewDataInvalidErr( - "ouf of range[0-5] for max_retry_times[%v]", *req.MaxRetryTimes) - return controller.JSONBaseErrorReq(c, err) - } - cfg.MaxRetryTimes = *req.MaxRetryTimes - } - if req.RetryIntervalSeconds != nil { - if *req.RetryIntervalSeconds < 1 || *req.RetryIntervalSeconds > 5 { - err = errors.NewDataInvalidErr( - "out of range[1-5] for retry_interval_seconds[%v]", *req.RetryIntervalSeconds) - return controller.JSONBaseErrorReq(c, err) - } - cfg.RetryIntervalSeconds = *req.RetryIntervalSeconds - } - if req.Token != nil { - cfg.Token = *req.Token - } - if req.URL != nil { - if !strings.HasPrefix(*req.URL, "http://") { - err = errors.NewDataInvalidErr("url must start with 'http://'") - return controller.JSONBaseErrorReq(c, err) - } - cfg.URL = *req.URL - } - return controller.JSONBaseErrorReq(c, s.Save(cfg)) -} - -type GetWorkflowWebHookConfigResV1 struct { - controller.BaseRes - Data WebHookConfigV1 `json:"data"` -} - -// GetWorkflowWebHookConfig -// @Summary 获取全局工单 WebHook 配置 -// @Description get workflow webhook config -// @Id getGlobalWorkflowWebHookConfig -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetWorkflowWebHookConfigResV1 -// @Router /v1/configurations/webhook [get] -func GetWorkflowWebHookConfig(c echo.Context) error { - s := model.GetStorage() - cfg, _, err := s.GetWorkflowWebHookConfig() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return c.JSON(http.StatusOK, &GetWorkflowWebHookConfigResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: WebHookConfigV1{ - Enable: &cfg.Enable, - MaxRetryTimes: &cfg.MaxRetryTimes, - RetryIntervalSeconds: &cfg.RetryIntervalSeconds, - Token: &cfg.Token, - URL: &cfg.URL, - }, - }) -} - -type TestWorkflowWebHookConfigResDataV1 struct { - SendErrorMessage string `json:"send_error_message,omitempty"` -} - -type TestWorkflowWebHookConfigResV1 struct { - controller.BaseRes - Data TestWorkflowWebHookConfigResDataV1 `json:"data"` -} - -// TestWorkflowWebHookConfig -// @Summary 测试全局工单 WebHook 配置 -// @Description test workflow webhook config -// @Id testGlobalWorkflowWebHookConfig -// @Tags configuration -// @Security ApiKeyAuth -// @Success 200 {object} v1.TestWorkflowWebHookConfigResV1 -// @Router /v1/configurations/webhook/test [post] -func TestWorkflowWebHookConfig(c echo.Context) error { - data := &TestWorkflowWebHookConfigResDataV1{} - err := notification.TestWorkflowConfig() - if err != nil { - data.SendErrorMessage = err.Error() - } - return c.JSON(http.StatusOK, &TestWorkflowWebHookConfigResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: *data, - }) -} - type GetFeishuAuditConfigurationResV1 struct { controller.BaseRes Data FeishuConfigurationV1 `json:"data"` } +type FeishuConfigurationV1 struct { + AppID string `json:"app_id"` + IsFeishuNotificationEnabled bool `json:"is_feishu_notification_enabled"` +} + // GetFeishuAuditConfigurationV1 // @Summary 获取飞书审核配置 // @Description get feishu audit configuration @@ -1378,6 +309,12 @@ func GetFeishuAuditConfigurationV1(c echo.Context) error { return getFeishuAuditConfigurationV1(c) } +type UpdateFeishuConfigurationReqV1 struct { + AppID *string `json:"app_id" form:"app_id" validate:"required" description:"飞书应用ID"` + AppSecret *string `json:"app_secret" form:"app_secret" validate:"required" description:"飞书应用Secret"` + IsFeishuNotificationEnabled *bool `json:"is_feishu_notification_enabled" from:"is_feishu_notification_enabled" validate:"required" description:"是否启用飞书推送"` +} + // UpdateFeishuAuditConfigurationV1 // @Summary 添加或更新飞书配置 // @Description update feishu audit configuration @@ -1392,6 +329,26 @@ func UpdateFeishuAuditConfigurationV1(c echo.Context) error { return updateFeishuAuditConfigurationV1(c) } +type TestFeishuConfigurationReqV1 struct { + AccountType string `json:"account_type" form:"account_type" enums:"email,phone" valid:"required"` + Account string `json:"account" form:"account" valid:"required" description:"绑定了飞书的手机号或邮箱"` +} + +type TestFeishuConfigResDataV1 struct { + IsMessageSentNormally bool `json:"is_message_sent_normally"` + ErrorMessage string `json:"error_message,omitempty"` +} + +type TestFeishuConfigResV1 struct { + controller.BaseRes + Data TestFeishuConfigResDataV1 `json:"data"` +} + +const ( + FeishuAccountTypeEmail = "email" + FeishuAccountTypePhone = "phone" +) + // TestFeishuAuditConfigV1 // @Summary 测试飞书审批配置 // @Description test feishu audit configuration diff --git a/sqle/api/controller/v1/configuration_ce.go b/sqle/api/controller/v1/configuration_ce.go index d8d598b967..aa14b95f45 100644 --- a/sqle/api/controller/v1/configuration_ce.go +++ b/sqle/api/controller/v1/configuration_ce.go @@ -5,53 +5,17 @@ package v1 import ( e "errors" - "net/http" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/config" "github.com/labstack/echo/v4" ) var ( - errCommunityEditionNotSupportCostumeLogo = errors.New(errors.EnterpriseEditionFeatures, e.New("costume logo is enterprise version feature")) - errCommunityEditionNotSupportUpdatePersonaliseConfig = errors.New(errors.EnterpriseEditionFeatures, e.New("update personalise config is enterprise version feature")) - errCommunityEditionNotSupportFeishuAudit = errors.New(errors.EnterpriseEditionFeatures, e.New("feishu audit is enterprise version feature")) + errCommunityEditionNotSupportFeishuAudit = errors.New(errors.EnterpriseEditionFeatures, e.New("feishu audit is enterprise version feature")) ) -const ( - Title = "SQLE" -) - -func uploadLogo(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionNotSupportCostumeLogo) -} - -func getLogo(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionNotSupportCostumeLogo) -} - -func updatePersonaliseConfig(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionNotSupportUpdatePersonaliseConfig) -} - -func getSQLEInfo(c echo.Context) error { - logoUrl, err := GetDefaultLogoUrl() - if err != nil { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, e.New("no logo file"))) - } - - return c.JSON(http.StatusOK, &GetSQLEInfoResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: GetSQLEInfoResDataV1{ - Version: config.Version, - LogoUrl: logoUrl, - Title: Title, - }, - }) -} - func updateFeishuAuditConfigurationV1(c echo.Context) error { return controller.JSONBaseErrorReq(c, errCommunityEditionNotSupportFeishuAudit) } diff --git a/sqle/api/controller/v1/configuration_comm.go b/sqle/api/controller/v1/configuration_comm.go deleted file mode 100644 index 07491267e1..0000000000 --- a/sqle/api/controller/v1/configuration_comm.go +++ /dev/null @@ -1,50 +0,0 @@ -package v1 - -import ( - e "errors" - "fmt" - "io/fs" - "io/ioutil" - "strings" -) - -const ( - // LogoUrlBase sqle static 服务接口的url前缀 - LogoUrlBase = "/static/media" - - // LogoDir sqle logo 的本地目录 - LogoDir = "./ui/static/media" -) - -// GetDefaultLogoUrl 获取默认logo的静态资源url -func GetDefaultLogoUrl() (string, error) { - fileInfo, err := getLogoFileInfo() - if err != nil { - return "", e.New("failed to get logo file info") - } - - modifyTime := fileInfo.ModTime().Unix() - return fmt.Sprintf("%s/%s?timestamp=%d", LogoUrlBase, fileInfo.Name(), modifyTime), nil -} - -func getLogoFileInfo() (fs.FileInfo, error) { - fileInfos, err := ioutil.ReadDir(LogoDir) - if err != nil { - return nil, e.New("read logo dir failed") - } - - var hasLogoFile bool - var logoFileInfo fs.FileInfo - for _, fileInfo := range fileInfos { - if strings.HasPrefix(fileInfo.Name(), "logo.") { - hasLogoFile = true - logoFileInfo = fileInfo - break - } - } - if !hasLogoFile { - return nil, e.New("no logo file") - } - - return logoFileInfo, nil -} diff --git a/sqle/api/controller/v1/dashboard.go b/sqle/api/controller/v1/dashboard.go index 947963e01d..22c9c9933b 100644 --- a/sqle/api/controller/v1/dashboard.go +++ b/sqle/api/controller/v1/dashboard.go @@ -2,9 +2,9 @@ package v1 import ( "net/http" - "sort" "github.com/actiontech/sqle/sqle/api/controller" + dms "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/model" "github.com/labstack/echo/v4" ) @@ -28,7 +28,7 @@ type WorkflowStatisticsResV1 struct { } type GetDashboardReqV1 struct { - FilterProjectName string `json:"filter_project_name" query:"filter_project_name" form:"filter_project_name"` + FilterProjectName string `json:"filter_project_id" query:"filter_project_id" form:"filter_project_id"` } // @Summary 获取 dashboard 信息 @@ -45,38 +45,42 @@ func Dashboard(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return controller.JSONBaseErrorReq(c, err) } + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), req.FilterProjectName) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } - user, err := controller.GetCurrentUser(c) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() createdNumber, err := s.GetWorkflowCountByReq(map[string]interface{}{ - "filter_project_name": req.FilterProjectName, - "filter_create_user_name": user.Name, - "filter_status": model.WorkflowStatusWaitForAudit, - "check_user_can_access": false, + "filter_project_id": projectUid, + "filter_create_user_id": user.GetIDStr(), + "filter_status": model.WorkflowStatusWaitForAudit, + "check_user_can_access": false, }) if err != nil { return controller.JSONBaseErrorReq(c, err) } rejectedNumber, err := s.GetWorkflowCountByReq(map[string]interface{}{ - "filter_project_name": req.FilterProjectName, - "filter_create_user_name": user.Name, - "filter_status": model.WorkflowStatusReject, - "check_user_can_access": false, + "filter_project_id": projectUid, + "filter_create_user_id": user.GetIDStr(), + "filter_status": model.WorkflowStatusReject, + "check_user_can_access": false, }) if err != nil { return controller.JSONBaseErrorReq(c, err) } myNeedReviewNumber, err := s.GetWorkflowCountByReq(map[string]interface{}{ - "filter_project_name": req.FilterProjectName, + "filter_project_id": projectUid, "filter_status": model.WorkflowStatusWaitForAudit, "filter_current_step_type": model.WorkflowStepTypeSQLReview, - "filter_create_user_name": user.Name, + "filter_create_user_id": user.GetIDStr(), "check_user_can_access": false, }) if err != nil { @@ -84,10 +88,10 @@ func Dashboard(c echo.Context) error { } myNeedExecuteNumber, err := s.GetWorkflowCountByReq(map[string]interface{}{ - "filter_project_name": req.FilterProjectName, + "filter_project_id": projectUid, "filter_status": model.WorkflowStatusWaitForExecution, "filter_current_step_type": model.WorkflowStepTypeSQLExecute, - "filter_create_user_name": user.Name, + "filter_create_user_id": user.GetIDStr(), "check_user_can_access": false, }) if err != nil { @@ -95,22 +99,22 @@ func Dashboard(c echo.Context) error { } reviewNumber, err := s.GetWorkflowCountByReq(map[string]interface{}{ - "filter_project_name": req.FilterProjectName, - "filter_status": model.WorkflowStatusWaitForAudit, - "filter_current_step_type": model.WorkflowStepTypeSQLReview, - "filter_current_step_assignee_user_name": user.Name, - "check_user_can_access": false, + "filter_project_id": projectUid, + "filter_status": model.WorkflowStatusWaitForAudit, + "filter_current_step_type": model.WorkflowStepTypeSQLReview, + "filter_current_step_assignee_user_id": user.GetIDStr(), + "check_user_can_access": false, }) if err != nil { return controller.JSONBaseErrorReq(c, err) } executeNumber, err := s.GetWorkflowCountByReq(map[string]interface{}{ - "filter_project_name": req.FilterProjectName, - "filter_status": model.WorkflowStatusWaitForExecution, - "filter_current_step_type": model.WorkflowStepTypeSQLExecute, - "filter_current_step_assignee_user_name": user.Name, - "check_user_can_access": false, + "filter_project_id": projectUid, + "filter_status": model.WorkflowStatusWaitForExecution, + "filter_current_step_type": model.WorkflowStepTypeSQLExecute, + "filter_current_step_assignee_user_id": user.GetIDStr(), + "check_user_can_access": false, }) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -130,108 +134,3 @@ func Dashboard(c echo.Context) error { }, }) } - -type DashboardProjectTipV1 struct { - Name string `json:"project_name"` - UnfinishedWorkflowCount int `json:"unfinished_workflow_count"` // 只统计与当前用户相关的未完成工单 -} - -type GetDashboardProjectTipsResV1 struct { - controller.BaseRes - Data []*DashboardProjectTipV1 `json:"data"` -} - -// DashboardProjectTipsV1 -// @Summary 获取dashboard项目提示列表 -// @Description get dashboard project tips -// @Tags dashboard -// @Id getDashboardProjectTipsV1 -// @Security ApiKeyAuth -// @Produce json -// @Success 200 {object} v1.GetDashboardProjectTipsResV1 -// @router /v1/dashboard/project_tips [get] -func DashboardProjectTipsV1(c echo.Context) error { - user, err := controller.GetCurrentUser(c) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - allProjectsByCurrentUser, err := s.GetProjectTips(controller.GetUserName(c)) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - createdByMeWorkflowCounts, err := s.GetWorkflowCountForDashboardProjectTipsByReq(map[string]interface{}{ - "filter_create_user_name": user.Name, - "filter_status": []string{model.WorkflowStatusReject, model.WorkflowStatusWaitForAudit, model.WorkflowStatusWaitForExecution}, - "check_user_can_access": false, - }) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - needMeHandleWorkflowCounts, err := s.GetWorkflowCountForDashboardProjectTipsByReq(map[string]interface{}{ - "filter_status": []string{model.WorkflowStatusWaitForAudit, model.WorkflowStatusWaitForExecution}, - "filter_current_step_assignee_user_name": user.Name, - "check_user_can_access": false, - }) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - projectToWorkflowCount := make(map[string]int) - summingUpWorkflowCount := func(projectName string, records []*model.ProjectWorkflowCount) { - for _, record := range records { - if record.ProjectName != projectName { - continue - } - if workflowCount, ok := projectToWorkflowCount[record.ProjectName]; ok { - projectToWorkflowCount[record.ProjectName] = workflowCount + record.WorkflowCount - } else { - projectToWorkflowCount[record.ProjectName] = record.WorkflowCount - } - } - } - - for _, p := range allProjectsByCurrentUser { - projectToWorkflowCount[p.Name] = 0 - summingUpWorkflowCount(p.Name, createdByMeWorkflowCounts) - summingUpWorkflowCount(p.Name, needMeHandleWorkflowCounts) - } - - // sort by unfinished workflow count, project name - i := 0 - projectTips := make(dashboardProjectTipSort, len(projectToWorkflowCount)) - for pName, count := range projectToWorkflowCount { - projectTips[i] = &DashboardProjectTipV1{ - Name: pName, - UnfinishedWorkflowCount: count, - } - i++ - } - sort.Sort(projectTips) - - data := make([]*DashboardProjectTipV1, len(projectTips)) - for j, projectTip := range projectTips { - data[j] = projectTip - } - - return c.JSON(http.StatusOK, &GetDashboardProjectTipsResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: data, - }) -} - -type dashboardProjectTipSort []*DashboardProjectTipV1 - -func (m dashboardProjectTipSort) Len() int { - return len(m) -} - -func (m dashboardProjectTipSort) Less(i, j int) bool { - return m[i].UnfinishedWorkflowCount < m[j].UnfinishedWorkflowCount -} - -func (m dashboardProjectTipSort) Swap(i, j int) { - m[i], m[j] = m[j], m[i] -} diff --git a/sqle/api/controller/v1/default_logo.go b/sqle/api/controller/v1/default_logo.go deleted file mode 100644 index 97f75fd6cc..0000000000 --- a/sqle/api/controller/v1/default_logo.go +++ /dev/null @@ -1,4 +0,0 @@ -package v1 - -// 默认实例logo的二进制数据 -var defaultInstanceLogo = []byte{137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 225, 0, 0, 0, 225, 8, 6, 0, 0, 0, 62, 179, 210, 122, 0, 0, 20, 81, 73, 68, 65, 84, 120, 94, 237, 157, 45, 111, 28, 73, 23, 70, 67, 243, 7, 2, 66, 44, 5, 174, 20, 24, 102, 156, 48, 67, 147, 16, 179, 144, 160, 240, 192, 128, 252, 129, 4, 133, 45, 13, 92, 184, 112, 193, 254, 1, 75, 38, 65, 11, 195, 162, 149, 2, 86, 154, 87, 103, 164, 199, 239, 157, 235, 234, 219, 93, 61, 118, 106, 236, 121, 142, 84, 242, 184, 63, 170, 171, 90, 117, 186, 62, 186, 187, 250, 209, 198, 24, 51, 148, 71, 121, 129, 49, 230, 215, 98, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 194, 3, 228, 191, 255, 254, 219, 252, 251, 239, 191, 155, 127, 254, 249, 103, 115, 121, 121, 185, 249, 251, 239, 191, 55, 127, 253, 245, 215, 230, 143, 63, 254, 216, 124, 253, 250, 117, 243, 251, 239, 191, 111, 190, 124, 249, 178, 13, 159, 63, 127, 190, 254, 205, 114, 214, 179, 29, 219, 179, 31, 251, 19, 15, 241, 17, 175, 57, 60, 44, 225, 32, 126, 252, 248, 177, 185, 186, 186, 218, 10, 243, 233, 211, 167, 205, 187, 119, 239, 54, 103, 103, 103, 155, 223, 126, 251, 109, 243, 232, 209, 163, 59, 11, 196, 207, 113, 56, 30, 199, 229, 248, 164, 131, 244, 152, 49, 88, 194, 95, 0, 181, 16, 181, 18, 181, 213, 197, 197, 197, 230, 241, 227, 199, 55, 228, 56, 132, 64, 186, 72, 31, 233, 36, 189, 164, 219, 220, 61, 150, 240, 142, 160, 16, 127, 252, 248, 113, 115, 122, 122, 122, 163, 176, 223, 167, 64, 250, 201, 7, 249, 49, 119, 131, 37, 220, 131, 220, 199, 162, 31, 70, 51, 47, 23, 228, 181, 225, 217, 179, 103, 91, 9, 104, 62, 82, 67, 17, 247, 251, 247, 239, 55, 31, 62, 124, 216, 138, 65, 160, 73, 169, 223, 44, 103, 61, 219, 177, 61, 251, 177, 63, 241, 228, 184, 215, 6, 226, 38, 159, 145, 124, 30, 76, 31, 150, 112, 79, 190, 127, 255, 190, 21, 224, 201, 147, 39, 55, 10, 236, 92, 96, 31, 100, 97, 127, 6, 84, 168, 109, 190, 125, 251, 182, 109, 6, 254, 252, 249, 51, 31, 106, 47, 136, 143, 120, 137, 159, 227, 112, 60, 142, 203, 241, 215, 166, 157, 253, 201, 191, 217, 15, 75, 216, 65, 188, 226, 83, 248, 122, 106, 189, 231, 207, 159, 111, 183, 167, 240, 51, 98, 121, 104, 253, 45, 210, 67, 186, 72, 31, 233, 36, 189, 57, 15, 83, 129, 237, 163, 140, 174, 25, 251, 176, 132, 11, 137, 5, 139, 26, 32, 23, 196, 86, 120, 251, 246, 237, 118, 244, 241, 190, 214, 22, 164, 155, 244, 147, 143, 156, 183, 86, 224, 188, 8, 139, 184, 28, 75, 56, 3, 133, 73, 5, 138, 251, 109, 115, 253, 43, 106, 133, 135, 58, 136, 65, 190, 230, 106, 127, 206, 15, 231, 9, 44, 226, 50, 44, 225, 12, 42, 72, 12, 70, 228, 2, 23, 11, 30, 55, 202, 111, 187, 31, 119, 168, 144, 79, 242, 91, 93, 144, 52, 120, 99, 17, 231, 177, 132, 11, 160, 175, 148, 11, 153, 2, 125, 168, 200, 67, 47, 116, 57, 127, 228, 63, 159, 19, 5, 206, 155, 153, 199, 18, 206, 192, 85, 63, 23, 46, 2, 253, 164, 99, 169, 249, 230, 64, 204, 169, 126, 163, 207, 209, 60, 150, 112, 6, 238, 195, 229, 130, 197, 50, 145, 107, 134, 99, 35, 230, 159, 231, 88, 171, 115, 101, 218, 88, 194, 25, 114, 161, 226, 134, 56, 28, 187, 124, 25, 157, 15, 206, 79, 62, 103, 166, 198, 103, 168, 128, 33, 250, 92, 160, 14, 237, 254, 222, 161, 193, 249, 201, 231, 236, 190, 222, 162, 249, 85, 88, 194, 2, 134, 218, 99, 97, 226, 1, 103, 225, 154, 112, 151, 120, 62, 242, 3, 234, 186, 101, 97, 218, 88, 194, 130, 44, 33, 65, 35, 126, 150, 112, 23, 157, 143, 214, 72, 178, 37, 172, 177, 132, 5, 45, 9, 185, 55, 230, 38, 105, 27, 206, 75, 235, 222, 161, 37, 172, 177, 132, 5, 45, 9, 9, 60, 87, 233, 130, 181, 11, 231, 99, 234, 121, 83, 159, 171, 26, 75, 88, 48, 37, 161, 2, 79, 141, 152, 205, 246, 60, 228, 115, 99, 9, 151, 99, 9, 11, 230, 36, 36, 208, 252, 250, 243, 207, 63, 175, 247, 137, 207, 154, 62, 52, 114, 222, 200, 119, 171, 249, 153, 131, 37, 172, 177, 132, 5, 115, 18, 198, 81, 192, 147, 147, 147, 237, 180, 16, 15, 125, 174, 22, 242, 71, 62, 163, 124, 121, 52, 52, 7, 75, 88, 99, 9, 11, 178, 132, 76, 146, 196, 171, 61, 185, 144, 229, 192, 27, 237, 60, 83, 217, 186, 63, 150, 107, 147, 67, 98, 42, 109, 228, 131, 252, 144, 175, 156, 215, 28, 56, 63, 121, 178, 42, 75, 88, 99, 9, 11, 178, 132, 188, 77, 14, 20, 202, 169, 103, 37, 115, 120, 241, 226, 197, 246, 41, 18, 222, 42, 104, 73, 121, 136, 144, 78, 210, 75, 186, 73, 127, 206, 83, 43, 112, 62, 148, 191, 252, 166, 190, 37, 172, 177, 132, 5, 83, 18, 10, 166, 138, 152, 123, 191, 46, 7, 226, 120, 243, 230, 205, 246, 57, 75, 250, 84, 28, 99, 212, 45, 15, 205, 109, 74, 58, 72, 15, 233, 202, 2, 205, 5, 242, 207, 121, 136, 228, 56, 44, 97, 141, 37, 44, 168, 36, 140, 205, 54, 106, 0, 250, 73, 83, 67, 244, 75, 2, 125, 202, 56, 31, 40, 35, 142, 200, 17, 39, 240, 229, 56, 244, 201, 120, 51, 33, 55, 27, 249, 159, 229, 172, 103, 59, 196, 208, 196, 193, 196, 67, 124, 113, 126, 83, 142, 151, 211, 176, 52, 144, 79, 242, 59, 53, 165, 133, 37, 236, 195, 18, 22, 84, 18, 78, 65, 225, 167, 128, 190, 124, 249, 242, 70, 225, 189, 207, 129, 252, 144, 175, 92, 235, 65, 190, 32, 88, 194, 62, 44, 97, 193, 26, 9, 35, 212, 74, 212, 66, 61, 125, 171, 67, 9, 234, 203, 146, 254, 222, 17, 95, 75, 216, 135, 37, 44, 216, 87, 194, 76, 156, 209, 140, 249, 65, 207, 207, 207, 111, 20, 254, 17, 129, 230, 41, 233, 185, 173, 153, 224, 44, 97, 31, 150, 176, 224, 182, 37, 156, 130, 190, 92, 156, 15, 148, 190, 27, 82, 48, 80, 130, 32, 212, 74, 12, 251, 63, 125, 250, 244, 134, 64, 173, 192, 118, 108, 207, 126, 236, 79, 60, 196, 71, 188, 196, 207, 200, 39, 199, 187, 171, 183, 222, 45, 97, 31, 150, 176, 224, 174, 37, 204, 125, 169, 37, 32, 142, 38, 242, 165, 153, 200, 223, 24, 214, 136, 181, 38, 29, 21, 150, 176, 15, 75, 88, 112, 215, 18, 62, 84, 44, 97, 31, 150, 176, 192, 18, 174, 195, 18, 246, 97, 9, 11, 44, 225, 58, 44, 97, 31, 150, 176, 192, 18, 174, 195, 18, 246, 97, 9, 11, 44, 225, 58, 44, 97, 31, 150, 176, 192, 18, 174, 195, 18, 246, 97, 9, 11, 44, 225, 58, 44, 97, 31, 150, 176, 192, 18, 174, 195, 18, 246, 97, 9, 11, 44, 225, 58, 44, 97, 31, 150, 176, 192, 18, 174, 195, 18, 246, 97, 9, 11, 178, 132, 132, 53, 143, 133, 29, 19, 173, 175, 88, 89, 194, 26, 75, 88, 208, 146, 48, 126, 18, 218, 220, 164, 245, 41, 113, 75, 88, 99, 9, 11, 90, 18, 18, 60, 223, 104, 155, 169, 249, 71, 45, 97, 141, 37, 44, 152, 146, 144, 192, 52, 17, 183, 253, 246, 193, 125, 133, 243, 80, 205, 181, 99, 9, 107, 44, 97, 65, 37, 33, 129, 249, 54, 153, 226, 239, 152, 33, 255, 158, 119, 116, 63, 44, 97, 193, 156, 132, 10, 76, 124, 196, 203, 178, 199, 82, 51, 146, 79, 242, 187, 116, 98, 43, 75, 88, 99, 9, 11, 178, 132, 188, 177, 126, 122, 122, 186, 253, 61, 117, 245, 167, 89, 198, 27, 242, 15, 13, 196, 35, 95, 83, 205, 78, 157, 15, 206, 79, 158, 1, 192, 18, 214, 88, 194, 130, 150, 132, 208, 250, 36, 116, 14, 220, 43, 163, 192, 174, 153, 40, 233, 80, 208, 68, 85, 228, 35, 223, 251, 107, 5, 125, 74, 220, 18, 246, 97, 9, 11, 178, 132, 241, 102, 61, 235, 150, 206, 194, 77, 96, 206, 23, 230, 121, 161, 15, 197, 252, 46, 115, 147, 41, 77, 77, 73, 191, 134, 37, 241, 144, 30, 210, 69, 250, 72, 231, 146, 15, 189, 40, 112, 30, 162, 104, 89, 88, 75, 88, 99, 9, 11, 166, 36, 140, 133, 154, 109, 90, 247, 198, 150, 4, 38, 98, 98, 18, 38, 77, 192, 68, 115, 143, 248, 238, 234, 129, 0, 226, 37, 254, 56, 161, 20, 199, 95, 59, 29, 35, 249, 142, 130, 233, 188, 88, 194, 62, 44, 97, 193, 148, 132, 83, 48, 139, 89, 79, 237, 56, 23, 152, 37, 155, 73, 119, 47, 46, 46, 182, 241, 210, 44, 164, 201, 71, 225, 71, 160, 28, 88, 206, 122, 182, 99, 123, 246, 99, 255, 125, 102, 219, 206, 129, 120, 201, 103, 133, 37, 236, 195, 18, 22, 244, 74, 40, 52, 136, 129, 20, 107, 107, 153, 67, 9, 164, 159, 124, 144, 159, 37, 205, 90, 176, 132, 125, 88, 194, 130, 181, 18, 102, 24, 224, 160, 246, 160, 182, 122, 253, 250, 245, 141, 66, 122, 40, 129, 116, 145, 62, 210, 73, 122, 215, 14, 40, 229, 252, 89, 194, 26, 75, 88, 112, 91, 18, 182, 160, 128, 107, 54, 110, 10, 61, 205, 188, 214, 240, 254, 109, 7, 221, 102, 225, 120, 234, 139, 146, 142, 181, 194, 181, 176, 132, 125, 88, 194, 130, 219, 150, 112, 105, 115, 142, 145, 74, 190, 120, 196, 241, 17, 132, 90, 137, 81, 75, 132, 225, 249, 76, 62, 204, 66, 136, 253, 65, 45, 99, 61, 219, 177, 61, 251, 197, 47, 58, 205, 141, 200, 138, 165, 233, 156, 194, 18, 246, 97, 9, 11, 110, 91, 194, 99, 193, 18, 246, 97, 9, 11, 44, 225, 58, 44, 97, 31, 150, 176, 192, 18, 174, 195, 18, 246, 97, 9, 11, 44, 225, 58, 44, 97, 31, 150, 176, 192, 18, 174, 195, 18, 246, 97, 9, 11, 44, 225, 58, 44, 97, 31, 150, 176, 192, 18, 174, 195, 18, 246, 97, 9, 11, 142, 65, 66, 238, 9, 198, 143, 140, 238, 123, 143, 16, 44, 97, 31, 150, 176, 224, 161, 75, 200, 91, 21, 122, 101, 74, 2, 234, 75, 192, 251, 96, 9, 251, 176, 132, 5, 15, 89, 194, 40, 28, 143, 172, 233, 175, 126, 239, 83, 35, 90, 194, 62, 44, 97, 65, 150, 144, 41, 28, 30, 10, 18, 13, 233, 162, 144, 250, 238, 253, 62, 181, 97, 158, 250, 195, 18, 214, 88, 194, 130, 44, 33, 65, 243, 199, 236, 83, 83, 28, 2, 106, 126, 170, 230, 227, 255, 248, 187, 87, 66, 157, 15, 206, 79, 62, 103, 150, 176, 198, 18, 22, 68, 9, 185, 186, 51, 229, 3, 211, 84, 220, 230, 27, 7, 163, 80, 95, 80, 226, 197, 102, 233, 26, 9, 129, 253, 90, 211, 98, 88, 194, 26, 75, 88, 16, 37, 164, 112, 33, 34, 253, 29, 126, 51, 31, 203, 125, 65, 82, 229, 218, 91, 162, 197, 145, 81, 137, 56, 71, 142, 139, 243, 33, 1, 221, 28, 237, 195, 18, 22, 68, 9, 79, 78, 78, 174, 107, 67, 45, 227, 213, 161, 67, 71, 35, 159, 83, 181, 91, 188, 61, 177, 246, 22, 5, 231, 33, 215, 126, 150, 112, 57, 150, 112, 2, 10, 35, 87, 119, 10, 17, 181, 159, 36, 228, 111, 44, 96, 76, 255, 192, 187, 123, 177, 240, 170, 73, 55, 85, 176, 179, 24, 173, 90, 74, 131, 37, 113, 155, 24, 111, 222, 94, 180, 142, 157, 69, 139, 235, 226, 250, 169, 60, 232, 216, 121, 228, 148, 124, 199, 243, 193, 11, 195, 92, 164, 8, 113, 132, 212, 18, 214, 88, 194, 6, 18, 64, 18, 82, 168, 40, 108, 72, 24, 155, 90, 244, 15, 245, 155, 109, 120, 185, 86, 5, 78, 133, 91, 133, 89, 5, 55, 47, 143, 191, 243, 241, 179, 80, 121, 31, 66, 68, 235, 243, 126, 26, 1, 141, 203, 20, 180, 156, 109, 148, 134, 214, 241, 148, 126, 206, 9, 249, 204, 125, 191, 44, 30, 231, 139, 96, 9, 231, 177, 132, 13, 84, 192, 115, 77, 72, 65, 99, 50, 92, 45, 139, 130, 198, 2, 249, 234, 213, 171, 237, 219, 237, 177, 240, 169, 16, 79, 137, 18, 69, 108, 109, 147, 37, 138, 210, 136, 184, 62, 199, 155, 127, 235, 255, 24, 175, 164, 214, 114, 165, 153, 124, 240, 198, 254, 249, 249, 249, 117, 30, 169, 245, 116, 65, 138, 83, 114, 112, 126, 152, 225, 141, 223, 186, 72, 89, 194, 26, 75, 152, 136, 53, 149, 36, 212, 149, 93, 51, 112, 51, 85, 4, 19, 228, 178, 60, 214, 140, 136, 169, 160, 101, 72, 202, 52, 132, 52, 221, 52, 197, 68, 44, 224, 192, 177, 226, 128, 136, 254, 215, 182, 45, 25, 167, 36, 204, 3, 43, 49, 63, 90, 174, 101, 250, 29, 211, 195, 95, 164, 65, 38, 242, 24, 243, 18, 47, 60, 228, 59, 202, 199, 156, 53, 228, 15, 88, 206, 249, 210, 246, 150, 176, 198, 18, 38, 40, 132, 42, 200, 89, 66, 61, 49, 163, 66, 203, 122, 201, 168, 66, 170, 193, 27, 53, 215, 114, 179, 141, 62, 36, 243, 129, 210, 164, 163, 160, 95, 93, 93, 93, 55, 23, 99, 26, 84, 27, 233, 127, 73, 8, 81, 202, 72, 75, 66, 200, 162, 9, 182, 229, 248, 92, 32, 72, 15, 233, 34, 159, 49, 189, 45, 233, 226, 54, 228, 95, 35, 197, 202, 7, 53, 96, 20, 212, 18, 214, 88, 194, 132, 10, 252, 156, 132, 218, 6, 248, 77, 115, 77, 31, 139, 33, 228, 145, 212, 88, 160, 249, 155, 31, 237, 34, 156, 157, 157, 109, 107, 20, 230, 249, 252, 252, 249, 243, 245, 100, 77, 220, 0, 71, 22, 10, 51, 181, 141, 38, 129, 82, 205, 74, 225, 143, 203, 9, 164, 157, 253, 16, 157, 120, 24, 193, 36, 94, 226, 231, 56, 249, 216, 74, 179, 210, 24, 155, 155, 57, 31, 236, 79, 124, 28, 23, 242, 69, 33, 246, 149, 9, 164, 37, 94, 84, 204, 46, 150, 176, 65, 150, 80, 133, 144, 79, 129, 65, 172, 153, 8, 177, 112, 177, 15, 5, 52, 22, 116, 132, 83, 205, 16, 155, 172, 42, 236, 8, 30, 107, 26, 9, 154, 239, 183, 229, 16, 183, 171, 182, 213, 58, 254, 106, 31, 29, 147, 223, 26, 84, 137, 205, 205, 124, 145, 160, 159, 75, 190, 16, 92, 181, 170, 164, 211, 249, 210, 69, 137, 243, 20, 107, 75, 213, 246, 146, 214, 236, 98, 9, 27, 168, 128, 73, 66, 10, 43, 133, 138, 43, 124, 92, 31, 107, 195, 184, 175, 164, 164, 102, 162, 38, 162, 79, 56, 85, 251, 16, 47, 242, 73, 74, 45, 139, 255, 75, 16, 213, 48, 81, 98, 109, 175, 229, 185, 214, 82, 250, 217, 87, 178, 74, 252, 152, 134, 184, 61, 235, 73, 47, 233, 166, 38, 38, 31, 49, 95, 170, 125, 37, 33, 203, 99, 51, 152, 116, 16, 167, 36, 71, 66, 214, 41, 30, 179, 139, 37, 44, 144, 132, 106, 154, 81, 184, 132, 154, 96, 173, 66, 21, 155, 103, 106, 134, 17, 248, 173, 62, 24, 77, 67, 102, 187, 110, 73, 35, 113, 178, 24, 113, 89, 172, 173, 84, 232, 115, 237, 181, 36, 176, 15, 163, 158, 164, 135, 116, 181, 250, 168, 57, 175, 173, 11, 144, 242, 7, 212, 132, 49, 45, 138, 83, 210, 154, 93, 44, 97, 65, 124, 98, 70, 5, 246, 46, 160, 112, 114, 44, 250, 112, 234, 191, 81, 11, 209, 127, 67, 16, 134, 252, 41, 216, 113, 176, 163, 10, 108, 199, 246, 236, 199, 254, 196, 67, 124, 196, 75, 252, 250, 250, 211, 26, 41, 90, 23, 157, 76, 190, 24, 120, 96, 166, 198, 18, 22, 252, 42, 9, 247, 97, 137, 20, 191, 26, 75, 216, 135, 37, 44, 184, 15, 18, 102, 14, 65, 74, 75, 216, 135, 37, 44, 184, 143, 18, 30, 2, 150, 176, 15, 75, 88, 96, 9, 215, 97, 9, 251, 176, 132, 5, 150, 112, 29, 150, 176, 15, 75, 88, 96, 9, 215, 97, 9, 251, 176, 132, 5, 150, 112, 29, 150, 176, 15, 75, 88, 96, 9, 215, 97, 9, 251, 176, 132, 5, 150, 112, 29, 150, 176, 15, 75, 88, 96, 9, 215, 97, 9, 251, 176, 132, 5, 150, 112, 29, 150, 176, 15, 75, 88, 192, 83, 255, 177, 48, 17, 214, 60, 111, 121, 76, 112, 126, 242, 57, 211, 27, 247, 166, 141, 37, 156, 33, 23, 40, 30, 132, 54, 55, 209, 227, 114, 156, 159, 124, 206, 76, 141, 207, 208, 12, 76, 251, 144, 11, 21, 111, 189, 139, 67, 120, 86, 115, 36, 49, 255, 173, 115, 197, 50, 83, 99, 9, 103, 224, 29, 185, 92, 176, 8, 188, 30, 148, 95, 232, 61, 86, 56, 15, 156, 143, 124, 142, 8, 62, 71, 243, 88, 194, 5, 92, 94, 94, 222, 40, 92, 10, 76, 109, 24, 121, 232, 53, 99, 206, 31, 249, 207, 231, 68, 129, 243, 102, 230, 177, 132, 51, 168, 208, 49, 205, 67, 46, 100, 10, 188, 229, 206, 68, 79, 199, 114, 213, 39, 159, 228, 119, 106, 86, 0, 2, 231, 11, 178, 180, 230, 38, 150, 112, 6, 77, 77, 1, 12, 181, 87, 5, 143, 240, 238, 221, 187, 235, 207, 167, 61, 52, 200, 23, 249, 203, 121, 142, 129, 243, 163, 91, 18, 241, 220, 153, 105, 44, 225, 66, 98, 97, 98, 62, 150, 92, 248, 90, 129, 126, 146, 38, 253, 189, 143, 144, 110, 210, 63, 213, 223, 203, 129, 243, 34, 44, 223, 114, 44, 97, 7, 177, 96, 81, 64, 231, 106, 133, 24, 152, 243, 133, 237, 233, 67, 209, 87, 58, 180, 251, 141, 164, 135, 9, 153, 72, 31, 233, 36, 189, 57, 15, 83, 129, 237, 227, 133, 198, 2, 246, 97, 9, 247, 132, 194, 71, 13, 144, 159, 18, 89, 18, 216, 135, 89, 175, 217, 159, 194, 79, 63, 138, 25, 222, 90, 179, 104, 239, 11, 241, 17, 47, 241, 115, 28, 142, 199, 113, 57, 254, 218, 180, 179, 255, 125, 173, 229, 15, 9, 75, 184, 7, 249, 138, 79, 225, 238, 169, 29, 231, 2, 253, 43, 102, 245, 102, 14, 80, 100, 33, 110, 166, 157, 231, 134, 56, 2, 112, 15, 78, 129, 255, 89, 206, 122, 182, 99, 123, 246, 99, 255, 185, 126, 108, 79, 32, 110, 13, 186, 136, 124, 30, 76, 31, 150, 240, 142, 96, 16, 3, 49, 226, 212, 248, 247, 49, 144, 126, 242, 241, 80, 7, 155, 14, 1, 75, 248, 11, 160, 191, 69, 33, 102, 222, 79, 106, 168, 60, 177, 239, 161, 4, 210, 69, 250, 72, 39, 233, 61, 180, 126, 235, 67, 197, 18, 14, 34, 126, 17, 137, 199, 224, 104, 230, 209, 124, 204, 31, 83, 185, 237, 64, 252, 28, 135, 227, 233, 163, 51, 154, 33, 219, 140, 193, 18, 30, 32, 244, 177, 52, 43, 55, 35, 169, 241, 235, 74, 12, 168, 112, 163, 156, 218, 138, 128, 72, 250, 205, 114, 214, 199, 175, 57, 177, 63, 241, 76, 77, 217, 111, 198, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 23, 208, 251, 113, 77, 182, 207, 251, 228, 255, 123, 200, 251, 230, 255, 167, 150, 221, 53, 107, 142, 185, 102, 159, 135, 142, 37, 12, 236, 83, 64, 230, 246, 157, 91, 223, 67, 142, 43, 255, 127, 215, 252, 252, 249, 115, 27, 204, 237, 96, 9, 19, 231, 231, 231, 155, 103, 207, 158, 109, 191, 237, 174, 240, 252, 249, 243, 205, 197, 197, 197, 246, 19, 212, 208, 170, 233, 224, 228, 228, 100, 187, 253, 147, 39, 79, 182, 159, 174, 206, 240, 157, 248, 28, 119, 14, 143, 31, 63, 222, 126, 222, 90, 240, 155, 101, 138, 151, 79, 96, 103, 248, 20, 182, 182, 137, 225, 244, 244, 116, 243, 225, 195, 135, 205, 247, 239, 223, 183, 219, 181, 210, 204, 103, 184, 137, 87, 241, 107, 219, 136, 246, 35, 79, 228, 241, 209, 163, 71, 219, 208, 202, 39, 159, 234, 86, 124, 173, 64, 254, 45, 240, 46, 150, 48, 241, 242, 229, 203, 235, 66, 214, 10, 31, 63, 126, 220, 110, 151, 11, 52, 178, 196, 237, 222, 190, 125, 187, 179, 30, 16, 60, 199, 215, 10, 81, 66, 36, 137, 235, 248, 70, 125, 6, 9, 115, 28, 57, 196, 56, 35, 228, 39, 110, 215, 146, 28, 242, 118, 49, 32, 186, 248, 250, 245, 235, 141, 245, 57, 88, 194, 93, 44, 97, 66, 18, 190, 127, 255, 126, 243, 237, 219, 183, 205, 213, 213, 213, 230, 242, 242, 114, 243, 230, 205, 155, 235, 66, 212, 42, 208, 89, 22, 174, 248, 25, 246, 35, 62, 2, 113, 83, 123, 177, 237, 151, 47, 95, 118, 142, 21, 5, 255, 244, 233, 211, 78, 188, 164, 35, 19, 37, 36, 29, 138, 43, 10, 209, 186, 40, 192, 235, 215, 175, 119, 226, 207, 53, 27, 80, 59, 106, 61, 231, 229, 199, 143, 31, 219, 64, 186, 181, 92, 53, 168, 142, 73, 173, 167, 116, 196, 64, 254, 204, 46, 150, 48, 33, 9, 41, 252, 25, 10, 214, 212, 58, 201, 66, 97, 87, 193, 164, 160, 86, 72, 66, 154, 112, 83, 72, 18, 93, 4, 72, 67, 38, 74, 72, 193, 143, 80, 115, 178, 252, 233, 211, 167, 59, 203, 5, 235, 72, 135, 226, 151, 172, 241, 66, 64, 250, 180, 93, 134, 38, 47, 235, 144, 15, 162, 132, 102, 25, 150, 48, 81, 73, 72, 179, 139, 117, 244, 237, 50, 106, 106, 210, 111, 148, 16, 115, 87, 253, 37, 18, 106, 155, 24, 111, 150, 59, 74, 72, 109, 19, 161, 121, 169, 117, 185, 9, 173, 26, 142, 90, 91, 162, 73, 158, 184, 173, 68, 38, 143, 90, 167, 245, 156, 11, 214, 169, 153, 110, 9, 251, 177, 132, 137, 74, 66, 245, 139, 114, 147, 144, 2, 201, 96, 4, 235, 16, 66, 181, 67, 171, 105, 23, 153, 147, 48, 54, 3, 65, 191, 115, 191, 109, 137, 132, 28, 43, 75, 40, 177, 201, 79, 236, 211, 18, 95, 68, 18, 158, 157, 157, 109, 255, 143, 241, 32, 29, 34, 186, 38, 92, 143, 37, 76, 172, 145, 80, 178, 32, 34, 168, 118, 160, 255, 84, 49, 39, 161, 4, 82, 13, 52, 37, 247, 82, 9, 51, 146, 139, 188, 34, 150, 226, 200, 53, 184, 106, 73, 66, 174, 133, 51, 150, 176, 31, 75, 152, 88, 35, 161, 106, 20, 250, 111, 128, 36, 252, 255, 226, 197, 139, 157, 237, 50, 115, 18, 106, 224, 67, 77, 61, 164, 230, 255, 220, 28, 174, 36, 84, 95, 85, 181, 88, 132, 219, 46, 172, 99, 48, 7, 184, 21, 195, 255, 170, 213, 68, 140, 95, 199, 158, 186, 77, 51, 39, 97, 107, 159, 99, 199, 18, 38, 214, 72, 40, 89, 180, 15, 53, 137, 10, 109, 85, 232, 230, 36, 212, 32, 143, 36, 153, 42, 224, 83, 163, 163, 186, 24, 16, 114, 19, 22, 232, 11, 178, 78, 163, 189, 85, 13, 30, 71, 66, 117, 81, 104, 161, 52, 34, 180, 89, 134, 37, 76, 172, 145, 80, 35, 139, 146, 133, 38, 155, 10, 108, 174, 153, 34, 115, 18, 170, 102, 146, 36, 81, 238, 120, 175, 109, 238, 62, 161, 4, 140, 23, 132, 220, 223, 4, 73, 75, 179, 183, 133, 36, 37, 80, 139, 42, 190, 88, 43, 198, 219, 34, 156, 75, 226, 82, 80, 179, 218, 236, 98, 9, 19, 107, 36, 148, 76, 241, 254, 161, 106, 153, 41, 193, 160, 146, 16, 201, 84, 152, 99, 97, 215, 178, 216, 111, 139, 18, 18, 167, 130, 150, 145, 150, 124, 111, 51, 247, 55, 97, 74, 242, 72, 188, 105, 79, 115, 59, 247, 17, 171, 155, 245, 173, 126, 169, 177, 132, 55, 232, 149, 48, 10, 16, 81, 83, 50, 62, 77, 146, 169, 36, 148, 16, 164, 39, 162, 123, 149, 177, 223, 22, 211, 16, 101, 163, 182, 211, 125, 198, 92, 187, 169, 214, 139, 77, 203, 234, 126, 99, 36, 14, 212, 240, 24, 91, 20, 81, 18, 34, 62, 121, 200, 193, 220, 196, 18, 38, 122, 37, 84, 141, 242, 234, 213, 171, 176, 229, 255, 11, 121, 150, 40, 82, 73, 168, 253, 179, 196, 173, 126, 91, 53, 48, 19, 155, 157, 81, 80, 197, 147, 143, 77, 237, 214, 90, 158, 137, 247, 31, 53, 32, 5, 83, 253, 86, 51, 141, 37, 76, 244, 74, 216, 170, 81, 96, 73, 211, 174, 146, 112, 74, 18, 21, 242, 40, 247, 148, 132, 106, 198, 106, 157, 30, 64, 7, 61, 136, 157, 155, 169, 58, 110, 150, 191, 69, 108, 122, 170, 150, 179, 132, 253, 88, 194, 68, 175, 132, 42, 180, 52, 63, 17, 146, 81, 68, 130, 110, 13, 180, 10, 186, 168, 36, 84, 141, 132, 12, 138, 151, 191, 186, 77, 65, 144, 100, 83, 18, 10, 173, 139, 111, 129, 104, 153, 210, 171, 160, 219, 22, 177, 102, 103, 192, 137, 123, 138, 173, 1, 158, 24, 15, 88, 194, 126, 44, 97, 162, 87, 66, 221, 64, 175, 130, 70, 77, 51, 83, 18, 206, 141, 118, 42, 168, 223, 214, 43, 97, 172, 165, 171, 32, 242, 163, 105, 32, 17, 53, 50, 172, 230, 177, 37, 236, 199, 18, 38, 42, 9, 115, 127, 44, 22, 126, 106, 138, 92, 171, 72, 208, 220, 84, 21, 83, 18, 34, 18, 203, 121, 232, 58, 199, 73, 96, 121, 220, 111, 74, 194, 220, 28, 85, 77, 22, 155, 180, 177, 246, 38, 180, 106, 112, 61, 51, 171, 38, 106, 172, 9, 245, 204, 172, 242, 104, 9, 251, 177, 132, 9, 73, 152, 223, 219, 139, 247, 254, 244, 216, 152, 106, 148, 169, 2, 167, 154, 115, 234, 254, 216, 148, 132, 26, 125, 164, 105, 216, 34, 23, 252, 106, 84, 51, 190, 98, 165, 215, 141, 212, 164, 205, 121, 20, 218, 62, 63, 36, 144, 111, 192, 199, 102, 173, 70, 107, 45, 97, 63, 150, 48, 33, 9, 17, 0, 217, 8, 212, 14, 186, 239, 71, 208, 144, 188, 10, 220, 148, 44, 81, 128, 22, 83, 18, 170, 230, 105, 213, 198, 144, 31, 69, 139, 18, 34, 166, 210, 173, 120, 226, 182, 160, 26, 58, 14, 212, 68, 216, 54, 30, 63, 142, 176, 146, 87, 106, 84, 242, 166, 115, 69, 208, 224, 147, 206, 9, 181, 181, 210, 161, 160, 218, 182, 122, 138, 232, 24, 105, 151, 142, 35, 102, 174, 143, 23, 251, 119, 170, 81, 166, 100, 161, 86, 210, 126, 173, 105, 35, 180, 78, 18, 170, 112, 170, 112, 79, 245, 37, 179, 220, 115, 125, 72, 70, 66, 117, 252, 248, 16, 64, 43, 77, 32, 121, 163, 184, 213, 77, 248, 120, 17, 169, 182, 83, 152, 26, 45, 62, 86, 44, 97, 2, 161, 144, 43, 6, 141, 80, 230, 167, 67, 216, 150, 126, 226, 212, 77, 104, 164, 98, 61, 161, 53, 96, 66, 220, 172, 203, 163, 142, 218, 103, 74, 18, 150, 107, 27, 210, 68, 161, 230, 119, 78, 55, 181, 98, 22, 89, 251, 178, 126, 170, 70, 34, 61, 108, 147, 111, 83, 144, 7, 150, 115, 145, 96, 244, 180, 149, 47, 237, 155, 211, 18, 195, 212, 113, 143, 21, 75, 24, 248, 149, 133, 99, 237, 177, 214, 238, 103, 14, 23, 75, 184, 39, 75, 164, 96, 155, 185, 237, 242, 250, 252, 127, 102, 110, 253, 20, 218, 111, 105, 154, 242, 54, 173, 101, 75, 217, 103, 223, 135, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 140, 37, 52, 102, 48, 150, 208, 152, 193, 88, 66, 99, 6, 99, 9, 141, 25, 204, 255, 0, 212, 20, 62, 205, 71, 79, 97, 57, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130} diff --git a/sqle/api/controller/v1/dms_handle.go b/sqle/api/controller/v1/dms_handle.go new file mode 100644 index 0000000000..aff13c90b0 --- /dev/null +++ b/sqle/api/controller/v1/dms_handle.go @@ -0,0 +1,64 @@ +package v1 + +import ( + "context" + "fmt" + "net/http" + "strconv" + + baseV1 "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/common" + "github.com/labstack/echo/v4" +) + +func init() { + dmsobject.InitOperateHandlers([]dmsobject.OperationHandler{ + AfterDeleteProject{}, + BeforeDeleteProject{}, + BeforeArchiveProject{}, + AfterCreateProject{}, + BeforeDeleteDbService{}, + }) +} + +// 内部接口 +func OperateDataResourceHandle(c echo.Context) error { + req := new(dmsV1.OperateDataResourceHandleReq) + if err := controller.BindAndValidateReq(c, req); err != nil { + return controller.JSONBaseErrorReq(c, err) + } + h := dmsobject.GetOperateHandle(fmt.Sprintf("%s_%s_%s", req.OperationTiming, req.OperationType, req.DataResourceType)) + + if err := h.Handle(c.Request().Context(), "", req.DataResourceUid); err != nil { + return c.JSON(http.StatusOK, dmsV1.OperateDataResourceHandleReply{GenericResp: baseV1.GenericResp{Code: http.StatusBadRequest, Message: err.Error()}}) + } + + return c.JSON(http.StatusOK, dmsV1.OperateDataResourceHandleReply{GenericResp: baseV1.GenericResp{Message: "OK"}}) +} + +type AfterDeleteProject struct { +} + +type BeforeArchiveProject struct { +} + +type BeforeDeleteProject struct { +} + +type AfterCreateProject struct { +} + +type BeforeDeleteDbService struct { +} + +func (h BeforeDeleteDbService) Handle(ctx context.Context, currentUserId string, instanceIdStr string) error { + instanceId, err := strconv.ParseInt(instanceIdStr, 10, 64) + if err != nil { + return err + } + + return common.CheckDeleteInstance(instanceId) +} diff --git a/sqle/api/controller/v1/dms_handle_ce.go b/sqle/api/controller/v1/dms_handle_ce.go new file mode 100644 index 0000000000..788552a6a9 --- /dev/null +++ b/sqle/api/controller/v1/dms_handle_ce.go @@ -0,0 +1,21 @@ +//go:build !enterprise +// +build !enterprise + +package v1 + +import ( + "context" +) + +func (h BeforeArchiveProject) Handle(ctx context.Context, currentUserId string, dataResourceId string) error { + return nil +} +func (h AfterDeleteProject) Handle(ctx context.Context, currentUserId string, dataResourceId string) error { + return nil +} +func (h BeforeDeleteProject) Handle(ctx context.Context, currentUserId string, dataResourceId string) error { + return nil +} +func (h AfterCreateProject) Handle(ctx context.Context, currentUserId string, dataResourceId string) error { + return nil +} diff --git a/sqle/api/controller/v1/instance.go b/sqle/api/controller/v1/instance.go index e040fa2600..c48e472830 100644 --- a/sqle/api/controller/v1/instance.go +++ b/sqle/api/controller/v1/instance.go @@ -5,14 +5,16 @@ import ( "fmt" "net/http" + baseV1 "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" "github.com/actiontech/sqle/sqle/api/controller" "github.com/actiontech/sqle/sqle/common" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/driver" driverV2 "github.com/actiontech/sqle/sqle/driver/v2" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/pkg/params" "github.com/actiontech/sqle/sqle/utils" "github.com/labstack/echo/v4" @@ -23,16 +25,6 @@ var ErrInstanceNoAccess = errors.New(errors.DataNotExist, fmt.Errorf("instance i var errInstanceBind = errors.New(errors.DataExist, fmt.Errorf("an instance can only bind one rule template")) var ErrWrongTimePeriod = errors.New(errors.DataInvalid, fmt.Errorf("wrong time period")) -type GetInstanceAdditionalMetasResV1 struct { - controller.BaseRes - Metas []*InstanceAdditionalMetaV1 `json:"data"` -} - -type InstanceAdditionalMetaV1 struct { - DBType string `json:"db_type"` - Params []*InstanceAdditionalParamResV1 `json:"params"` -} - type InstanceAdditionalParamResV1 struct { Name string `json:"name" example:"param name" form:"name"` Description string `json:"description" example:"参数项中文名" form:"description"` @@ -40,123 +32,11 @@ type InstanceAdditionalParamResV1 struct { Value string `json:"value" example:"0" form:"value"` } -// GetInstanceAdditionalMetas get instance additional metas -// @Summary 获取实例的额外属性列表 -// @Description get instance additional metas -// @Id getInstanceAdditionalMetas -// @Tags instance -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetInstanceAdditionalMetasResV1 -// @router /v1/instance_additional_metas [get] -func GetInstanceAdditionalMetas(c echo.Context) error { - additionalParams := driver.GetPluginManager().AllAdditionalParams() - res := &GetInstanceAdditionalMetasResV1{ - BaseRes: controller.NewBaseReq(nil), - Metas: []*InstanceAdditionalMetaV1{}, - } - for name, params := range additionalParams { - meta := &InstanceAdditionalMetaV1{ - DBType: name, - Params: convertParamsToInstanceAdditionalParamRes(params), - } - - res.Metas = append(res.Metas, meta) - } - return c.JSON(http.StatusOK, res) -} - -func convertParamsToInstanceAdditionalParamRes(params params.Params) []*InstanceAdditionalParamResV1 { - res := make([]*InstanceAdditionalParamResV1, len(params)) - for i, param := range params { - res[i] = &InstanceAdditionalParamResV1{ - Name: param.Key, - Description: param.Desc, - Type: string(param.Type), - Value: param.Value, - } - } - return res -} - -type CreateInstanceReqV1 struct { - Name string `json:"instance_name" form:"instance_name" example:"test" valid:"required,name"` - DBType string `json:"db_type" form:"db_type" example:"mysql"` - User string `json:"db_user" form:"db_user" example:"root" valid:"required"` - Host string `json:"db_host" form:"db_host" example:"10.10.10.10" valid:"required,ip_addr|uri|hostname|hostname_rfc1123"` - Port string `json:"db_port" form:"db_port" example:"3306" valid:"required,port"` - Password string `json:"db_password" form:"db_password" example:"123456" valid:"required"` - Desc string `json:"desc" example:"this is a test instance"` - SQLQueryConfig *SQLQueryConfigReqV1 `json:"sql_query_config" form:"sql_query_config"` - MaintenanceTimes []*MaintenanceTimeReqV1 `json:"maintenance_times" form:"maintenance_times"` - RuleTemplateName string `json:"rule_template_name" form:"rule_template_name"` - AdditionalParams []*InstanceAdditionalParamReqV1 `json:"additional_params" form:"additional_params"` -} - -type SQLQueryConfigReqV1 struct { - MaxPreQueryRows int `json:"max_pre_query_rows" from:"max_pre_query_rows" example:"100"` - QueryTimeoutSecond int `json:"query_timeout_second" from:"query_timeout_second" example:"10"` - AuditEnabled bool `json:"audit_enabled" from:"audit_enabled" example:"false"` - AllowQueryWhenLessThanAuditLevel string `json:"allow_query_when_less_than_audit_level" from:"allow_query_when_less_than_audit_level" enums:"normal,notice,warn,error" valid:"omitempty,oneof=normal notice warn error " example:"error"` -} - type InstanceAdditionalParamReqV1 struct { Name string `json:"name"` Value string `json:"value"` } -type MaintenanceTimeReqV1 struct { - MaintenanceStartTime *TimeReqV1 `json:"maintenance_start_time"` - MaintenanceStopTime *TimeReqV1 `json:"maintenance_stop_time"` -} - -type TimeReqV1 struct { - Hour int `json:"hour"` - Minute int `json:"minute"` -} - -func ConvertMaintenanceTimeReqV1ToPeriod(mt []*MaintenanceTimeReqV1) model.Periods { - periods := make(model.Periods, len(mt)) - for i, time := range mt { - periods[i] = &model.Period{ - StartHour: time.MaintenanceStartTime.Hour, - StartMinute: time.MaintenanceStartTime.Minute, - EndHour: time.MaintenanceStopTime.Hour, - EndMinute: time.MaintenanceStopTime.Minute, - } - } - return periods -} - -// CreateInstance create instance -// @Deprecated -// @Summary 添加实例 -// @Description create a instance -// @Id createInstanceV1 -// @Tags instance -// @Security ApiKeyAuth -// @Accept json -// @Param project_name path string true "project name" -// @Param instance body v1.CreateInstanceReqV1 true "add instance" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/instances [post] -func CreateInstance(c echo.Context) error { - return nil -} - -type InstanceResV1 struct { - Name string `json:"instance_name"` - DBType string `json:"db_type" example:"mysql"` - Host string `json:"db_host" example:"10.10.10.10"` - Port string `json:"db_port" example:"3306"` - User string `json:"db_user" example:"root"` - Desc string `json:"desc" example:"this is a instance"` - MaintenanceTimes []*MaintenanceTimeResV1 `json:"maintenance_times" from:"maintenance_times"` - RuleTemplateName string `json:"rule_template_name,omitempty"` - AdditionalParams []*InstanceAdditionalParamResV1 `json:"additional_params"` - SQLQueryConfig *SQLQueryConfigResV1 `json:"sql_query_config"` - Source string `json:"source" example:"SQLE"` -} - type SQLQueryConfigResV1 struct { MaxPreQueryRows int `json:"max_pre_query_rows"` QueryTimeoutSecond int `json:"query_timeout_second"` @@ -191,396 +71,6 @@ func ConvertPeriodToMaintenanceTimeResV1(mt model.Periods) []*MaintenanceTimeRes return periods } -type GetInstanceResV1 struct { - controller.BaseRes - Data InstanceResV1 `json:"data"` -} - -func convertInstanceToRes(instance *model.Instance) InstanceResV1 { - instanceResV1 := InstanceResV1{ - Name: instance.Name, - Host: instance.Host, - Port: instance.Port, - User: instance.User, - Desc: instance.Desc, - DBType: instance.DbType, - MaintenanceTimes: ConvertPeriodToMaintenanceTimeResV1(instance.MaintenancePeriod), - AdditionalParams: []*InstanceAdditionalParamResV1{}, - SQLQueryConfig: &SQLQueryConfigResV1{ - MaxPreQueryRows: instance.SqlQueryConfig.MaxPreQueryRows, - QueryTimeoutSecond: instance.SqlQueryConfig.QueryTimeoutSecond, - AuditEnabled: instance.SqlQueryConfig.AuditEnabled, - AllowQueryWhenLessThanAuditLevel: instance.SqlQueryConfig.AllowQueryWhenLessThanAuditLevel, - }, - Source: instance.Source, - } - - if len(instance.RuleTemplates) > 0 { - instanceResV1.RuleTemplateName = instance.RuleTemplates[0].Name - } - - for _, param := range instance.AdditionalParams { - instanceResV1.AdditionalParams = append(instanceResV1.AdditionalParams, &InstanceAdditionalParamResV1{ - Name: param.Key, - Description: param.Desc, - Type: string(param.Type), - Value: fmt.Sprintf("%v", param.Value), - }) - } - return instanceResV1 -} - -// GetInstance get instance -// @Summary 获取实例信息 -// @Description get instance db -// @Id getInstanceV1 -// @Tags instance -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param instance_name path string true "instance name" -// @Success 200 {object} v1.GetInstanceResV1 -// @router /v1/projects/{project_name}/instances/{instance_name}/ [get] -func GetInstance(c echo.Context) error { - s := model.GetStorage() - instanceName := c.Param("instance_name") - projectName := c.Param("project_name") - username := controller.GetUserName(c) - err := CheckIsProjectMember(username, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - instance, exist, err := s.GetInstanceDetailByNameAndProjectName(instanceName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrInstanceNoAccess) - } - - return c.JSON(http.StatusOK, &GetInstanceResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: convertInstanceToRes(instance), - }) -} - -// DeleteInstance delete instance -// @Summary 删除实例 -// @Description delete instance db -// @Id deleteInstanceV1 -// @Tags instance -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param instance_name path string true "instance name" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/instances/{instance_name}/ [delete] -func DeleteInstance(c echo.Context) error { - instanceName := c.Param("instance_name") - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - - err := CheckIsProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - instance, exist, err := s.GetInstanceByNameAndProjectName(instanceName, projectName) - if err != nil { - return err - } - if !exist { - return fmt.Errorf("instance %s not exist", instanceName) - } - - if err = common.CheckDeleteInstance(instance.ID); err != nil { - return controller.JSONBaseErrorReq(c, fmt.Errorf("%v can't be deleted. Cause: %v", instance.Name, err)) - } - - if err := s.DeleteInstance(instance); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) -} - -type UpdateInstanceReqV1 struct { - DBType *string `json:"db_type" form:"db_type" example:"mysql"` - User *string `json:"db_user" form:"db_user" example:"root"` - Host *string `json:"db_host" form:"db_host" example:"10.10.10.10" valid:"omitempty,ip_addr|uri|hostname|hostname_rfc1123"` - Port *string `json:"db_port" form:"db_port" example:"3306" valid:"omitempty,port"` - Password *string `json:"db_password" form:"db_password" example:"123456"` - Desc *string `json:"desc" example:"this is a test instance"` - MaintenanceTimes []*MaintenanceTimeReqV1 `json:"maintenance_times" from:"maintenance_times"` - RuleTemplateName *string `json:"rule_template_name" form:"rule_template_name"` - SQLQueryConfig *SQLQueryConfigReqV1 `json:"sql_query_config" from:"sql_query_config"` - AdditionalParams []*InstanceAdditionalParamReqV1 `json:"additional_params" from:"additional_params"` -} - -// UpdateInstance update instance -// @Summary 更新实例 -// @Description update instance -// @Id updateInstanceV1 -// @Tags instance -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param instance_name path string true "instance name" -// @param instance body v1.UpdateInstanceReqV1 true "update instance request" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/instances/{instance_name}/ [patch] -func UpdateInstance(c echo.Context) error { - req := new(UpdateInstanceReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - maintenancePeriod := ConvertMaintenanceTimeReqV1ToPeriod(req.MaintenanceTimes) - if !maintenancePeriod.SelfCheck() { - return controller.JSONBaseErrorReq(c, ErrWrongTimePeriod) - } - - instanceName := c.Param("instance_name") - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - - err := CheckIsProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - instance, exist, err := s.GetInstanceByNameAndProjectName(instanceName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrInstanceNotExist) - } - - if instance.Source != model.InstanceSourceSQLE { - if req.Desc != nil || - req.Host != nil || - req.Port != nil || - req.User != nil || - req.Password != nil { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, fmt.Errorf("description, host, port, user, password of external instance can not be changed"))) - } - } - - updateMap := map[string]interface{}{} - if req.Desc != nil { - updateMap["desc"] = *req.Desc - } - if req.Host != nil { - updateMap["db_host"] = *req.Host - } - if req.Port != nil { - updateMap["db_port"] = *req.Port - } - if req.User != nil { - updateMap["db_user"] = *req.User - } - - if req.MaintenanceTimes != nil { - updateMap["maintenance_period"] = maintenancePeriod - } - - if req.Password != nil { - password, err := utils.AesEncrypt(*req.Password) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - updateMap["db_password"] = password - } - - if req.RuleTemplateName != nil { - var ruleTemplates []*model.RuleTemplate - if *req.RuleTemplateName != "" { - ruleTemplate, exist, err := s.GetGlobalAndProjectRuleTemplateByNameAndProjectId(*req.RuleTemplateName, instance.ProjectId) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrRuleTemplateNotExist) - } - err = CheckInstanceAndRuleTemplateDbType([]*model.RuleTemplate{ruleTemplate}, instance) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - ruleTemplates = append(ruleTemplates, ruleTemplate) - } - - err = s.UpdateInstanceRuleTemplates(instance, ruleTemplates...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - - if req.AdditionalParams != nil { - additionalParams := driver.GetPluginManager().AllAdditionalParams()[instance.DbType] - for _, additionalParam := range req.AdditionalParams { - err = additionalParams.SetParamValue(additionalParam.Name, additionalParam.Value) - if err != nil { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, err)) - } - } - updateMap["additional_params"] = additionalParams - } - - if req.SQLQueryConfig != nil { - if req.SQLQueryConfig.AuditEnabled && req.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel == "" { - req.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel = string(driverV2.RuleLevelError) - } - - maxPreQueryRows := req.SQLQueryConfig.MaxPreQueryRows - queryTimeout := req.SQLQueryConfig.QueryTimeoutSecond - - // default value - if queryTimeout == 0 { - queryTimeout = 10 - } - // default value - if maxPreQueryRows == 0 { - maxPreQueryRows = 100 - } - - updateMap["sql_query_config"] = model.SqlQueryConfig{ - MaxPreQueryRows: maxPreQueryRows, - QueryTimeoutSecond: queryTimeout, - AuditEnabled: req.SQLQueryConfig.AuditEnabled, - AllowQueryWhenLessThanAuditLevel: req.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel, - } - } - - err = s.UpdateInstanceById(instance.ID, updateMap) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) -} - -type GetInstancesReqV1 struct { - FilterInstanceName string `json:"filter_instance_name" query:"filter_instance_name"` - FilterDBType string `json:"filter_db_type" query:"filter_db_type"` - FilterDBHost string `json:"filter_db_host" query:"filter_db_host"` - FilterDBPort string `json:"filter_db_port" query:"filter_db_port"` - FilterDBUser string `json:"filter_db_user" query:"filter_db_user"` - FilterRuleTemplateName string `json:"filter_rule_template_name" query:"filter_rule_template_name"` - PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` - PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` -} - -type GetInstancesResV1 struct { - controller.BaseRes - Data []InstanceResV1 `json:"data"` - TotalNums uint64 `json:"total_nums"` -} - -// GetInstances get instances -// @Summary 获取实例信息列表 -// @Description get instance info list -// @Id getInstanceListV1 -// @Tags instance -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param filter_instance_name query string false "filter instance name" -// @Param filter_db_type query string false "filter db type" -// @Param filter_db_host query string false "filter db host" -// @Param filter_db_port query string false "filter db port" -// @Param filter_db_user query string false "filter db user" -// @Param filter_rule_template_name query string false "filter rule template name" -// @Param page_index query uint32 true "page index" -// @Param page_size query uint32 true "size of per page" -// @Success 200 {object} v1.GetInstancesResV1 -// @router /v1/projects/{project_name}/instances [get] -func GetInstances(c echo.Context) error { - req := new(GetInstancesReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - - user, err := controller.GetCurrentUser(c) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - projectName := c.Param("project_name") - err = CheckIsProjectMember(user.Name, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - var offset uint32 - if req.PageIndex >= 1 { - offset = req.PageSize * (req.PageIndex - 1) - } - data := map[string]interface{}{ - "filter_instance_name": req.FilterInstanceName, - "filter_project_name": projectName, - "filter_db_host": req.FilterDBHost, - "filter_db_port": req.FilterDBPort, - "filter_db_user": req.FilterDBUser, - "filter_rule_template_name": req.FilterRuleTemplateName, - "filter_db_type": req.FilterDBType, - "limit": req.PageSize, - "offset": offset, - } - - instances, count, err := s.GetInstancesByReq(data, user) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - instancesRes := []InstanceResV1{} - for _, instance := range instances { - ruleTemplateName := "" - if len(instance.RuleTemplateNames) >= 1 { - ruleTemplateName = instance.RuleTemplateNames[0] - } - - instanceReq := InstanceResV1{ - Name: instance.Name, - DBType: instance.DbType, - Host: instance.Host, - Port: instance.Port, - User: instance.User, - Desc: instance.Desc, - MaintenanceTimes: ConvertPeriodToMaintenanceTimeResV1(instance.MaintenancePeriod), - RuleTemplateName: ruleTemplateName, - SQLQueryConfig: &SQLQueryConfigResV1{ - MaxPreQueryRows: instance.SqlQueryConfig.MaxPreQueryRows, - QueryTimeoutSecond: instance.SqlQueryConfig.QueryTimeoutSecond, - AuditEnabled: instance.SqlQueryConfig.AuditEnabled, - AllowQueryWhenLessThanAuditLevel: instance.SqlQueryConfig.AllowQueryWhenLessThanAuditLevel, - }, - Source: instance.Source, - } - instancesRes = append(instancesRes, instanceReq) - } - return c.JSON(http.StatusOK, &GetInstancesResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: instancesRes, - TotalNums: count, - }) -} - type GetInstanceConnectableResV1 struct { controller.BaseRes Data InstanceConnectableResV1 `json:"data"` @@ -614,33 +104,29 @@ func newInstanceConnectableResV1(err error) InstanceConnectableResV1 { // @Success 200 {object} v1.GetInstanceConnectableResV1 // @router /v1/projects/{project_name}/instances/{instance_name}/connection [get] func CheckInstanceIsConnectableByName(c echo.Context) error { - s := model.GetStorage() - instanceName := c.Param("instance_name") - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - instance, exist, err := s.GetInstanceByNameAndProjectName(instanceName, projectName) + instance, exist, err := dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, instanceName) if err != nil { return controller.JSONBaseErrorReq(c, err) } if !exist { return controller.JSONBaseErrorReq(c, ErrInstanceNoAccess) } - can, err := checkCurrentUserCanAccessInstance(c, instance) + + can, err := CheckCurrentUserCanAccessInstances(c.Request().Context(), projectUid, controller.GetUserID(c), []*model.Instance{instance}) if err != nil { return controller.JSONBaseErrorReq(c, err) } if !can { return controller.JSONBaseErrorReq(c, ErrInstanceNoAccess) } - l := log.NewEntry() + l := log.NewEntry() err = common.CheckInstanceIsConnectable(instance) if err != nil { l.Warnf("instance %s is not connectable, err: %s", instanceName, err) @@ -686,10 +172,7 @@ func BatchCheckInstanceConnections(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -701,8 +184,7 @@ func BatchCheckInstanceConnections(c echo.Context) error { distinctInstNames := utils.RemoveDuplicate(instanceNames) - s := model.GetStorage() - instances, err := s.GetInstancesByNamesAndProjectName(distinctInstNames, projectName) + instances, err := dms.GetInstancesInProjectByNames(c.Request().Context(), projectUid, distinctInstNames) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -711,7 +193,7 @@ func BatchCheckInstanceConnections(c echo.Context) error { return controller.JSONBaseErrorReq(c, ErrInstanceNoAccess) } - can, err := checkCurrentUserCanAccessInstances(c, instances) + can, err := CheckCurrentUserCanAccessInstances(c.Request().Context(), projectUid, controller.GetUserID(c), instances) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -747,18 +229,8 @@ type GetInstanceConnectableReqV1 struct { AdditionalParams []*InstanceAdditionalParamReqV1 `json:"additional_params" from:"additional_params"` } -// CheckInstanceIsConnectable test instance db connection -// @Summary 实例连通性测试(实例提交前) -// @Description test instance db connection 注:可直接提交创建实例接口的body,该接口的json 内容是创建实例的 json 的子集 -// @Accept json -// @Id checkInstanceIsConnectableV1 -// @Tags instance -// @Security ApiKeyAuth -// @Param instance body v1.GetInstanceConnectableReqV1 true "instance info" -// @Success 200 {object} v1.GetInstanceConnectableResV1 -// @router /v1/instance_connection [post] func CheckInstanceIsConnectable(c echo.Context) error { - req := new(GetInstanceConnectableReqV1) + req := new(v1.CheckDbConnectable) if err := controller.BindAndValidateReq(c, req); err != nil { return err } @@ -788,12 +260,9 @@ func CheckInstanceIsConnectable(c echo.Context) error { err := common.CheckInstanceIsConnectable(instance) if err != nil { l.Warnf("check instance is connectable failed: %v", err) + return c.JSON(http.StatusOK, baseV1.GenericResp{Code: http.StatusBadRequest, Message: err.Error()}) } - - return c.JSON(http.StatusOK, GetInstanceConnectableResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: newInstanceConnectableResV1(err), - }) + return c.JSON(http.StatusOK, baseV1.GenericResp{Message: "OK"}) } type GetInstanceSchemaResV1 struct { @@ -816,25 +285,21 @@ type InstanceSchemaResV1 struct { // @Success 200 {object} v1.GetInstanceSchemaResV1 // @router /v1/projects/{project_name}/instances/{instance_name}/schemas [get] func GetInstanceSchemas(c echo.Context) error { - s := model.GetStorage() - instanceName := c.Param("instance_name") - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - instance, exist, err := s.GetInstanceByNameAndProjectName(instanceName, projectName) + instance, exist, err := dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, instanceName) if err != nil { return controller.JSONBaseErrorReq(c, err) } if !exist { return controller.JSONBaseErrorReq(c, ErrInstanceNoAccess) } - can, err := checkCurrentUserCanAccessInstance(c, instance) + + can, err := CheckCurrentUserCanAccessInstances(c.Request().Context(), projectUid, controller.GetUserID(c), []*model.Instance{instance}) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -872,6 +337,7 @@ type InstanceTipReqV1 struct { } type InstanceTipResV1 struct { + ID string `json:"instance_id"` Name string `json:"instance_name"` Type string `json:"instance_type"` WorkflowTemplateId uint32 `json:"workflow_template_id"` @@ -901,35 +367,46 @@ func GetInstanceTips(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } - s := model.GetStorage() - user, err := controller.GetCurrentUser(c) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - var instances []*model.Instance + var operationType v1.OpPermissionType switch req.FunctionalModule { case create_audit_plan: - instances, err = s.GetInstanceTipsByUserAndOperation(user, req.FilterDBType, projectName, model.OP_AUDIT_PLAN_SAVE) + operationType = v1.OpPermissionTypeSaveAuditPlan case create_workflow: - instances, err = s.GetInstanceTipsByUserAndOperation(user, req.FilterDBType, projectName, model.OP_WORKFLOW_SAVE) + operationType = v1.OpPermissionTypeCreateWorkflow default: - instances, err = s.GetInstanceTipsByUser(user, req.FilterDBType, projectName) } + + instances, err := GetCanOperationInstances(c.Request().Context(), user, req.FilterDBType, projectUid, operationType) if err != nil { return controller.JSONBaseErrorReq(c, err) } - + s := model.GetStorage() + template, exist, err := s.GetWorkflowTemplateByProjectId(model.ProjectUID(projectUid)) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if !exist { + return controller.JSONBaseErrorReq(c, fmt.Errorf("current project doesn't has workflow template")) + } instanceTipsResV1 := make([]InstanceTipResV1, 0, len(instances)) for _, inst := range instances { instanceTipRes := InstanceTipResV1{ + ID: inst.GetIDStr(), Name: inst.Name, Type: inst.DbType, Host: inst.Host, Port: inst.Port, - WorkflowTemplateId: uint32(inst.WorkflowTemplateId), + WorkflowTemplateId: uint32(template.ID), } instanceTipsResV1 = append(instanceTipsResV1, instanceTipRes) } @@ -954,23 +431,20 @@ func GetInstanceRules(c echo.Context) error { s := model.GetStorage() instanceName := c.Param("instance_name") - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - instance, exist, err := s.GetInstanceByNameAndProjectName(instanceName, projectName) + instance, exist, err := dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, instanceName) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("instance is not exist"))) } - can, err := checkCurrentUserCanAccessInstance(c, instance) + + can, err := CheckCurrentUserCanAccessInstances(c.Request().Context(), projectUid, controller.GetUserID(c), []*model.Instance{instance}) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -978,7 +452,7 @@ func GetInstanceRules(c echo.Context) error { return controller.JSONBaseErrorReq(c, ErrInstanceNoAccess) } - rules, _, err := s.GetAllRulesByInstanceId(fmt.Sprintf("%d", instance.ID)) + rules, _, err := s.GetAllRulesByInstance(instance) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1079,31 +553,3 @@ type GetTableMetadataResV1 struct { func GetTableMetadata(c echo.Context) error { return getTableMetadata(c) } - -type GetInstanceTypeLogoReqV1 struct { - InstanceType string `json:"instance_type" query:"instance_type"` -} - -// GetInstanceTypeLogo -// @Summary 获取实例类型logo -// @Description get instance type logo -// @Id getInstanceTypeLogo -// @Tags instance -// @Param instance_type query string true "instance type" -// @Security ApiKeyAuth -// @Success 200 {file} file "get instance type logo" -// @router /v1/static/instance_logo [get] -func GetInstanceTypeLogo(c echo.Context) error { - req := new(GetInstanceTypeLogoReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - instanceTypeLogoMap := driver.GetPluginManager().AllLogo() - - if logo, ok := instanceTypeLogoMap[req.InstanceType]; ok { - return c.Blob(http.StatusOK, "image/png", logo) - } - - return c.Blob(http.StatusOK, "image/png", defaultInstanceLogo) -} diff --git a/sqle/api/controller/v1/management_permission.go b/sqle/api/controller/v1/management_permission.go deleted file mode 100644 index f0144fefc1..0000000000 --- a/sqle/api/controller/v1/management_permission.go +++ /dev/null @@ -1,60 +0,0 @@ -package v1 - -import ( - "net/http" - - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/model" - - "github.com/labstack/echo/v4" -) - -type GetManagementPermissionsResV1 struct { - controller.BaseRes - Data []*ManagementPermissionResV1 `json:"data"` -} - -type ManagementPermissionResV1 struct { - Code uint `json:"code"` - Desc string `json:"desc"` -} - -func generateManagementPermissionResV1(code uint) ManagementPermissionResV1 { - return ManagementPermissionResV1{ - Code: code, - Desc: model.GetManagementPermissionDesc(code), - } -} - -func generateManagementPermissionResV1s(code []uint) []*ManagementPermissionResV1 { - m := []*ManagementPermissionResV1{} - for _, u := range code { - p := generateManagementPermissionResV1(u) - m = append(m, &p) - } - return m -} - -// GetManagementPermissions -// @Summary 获取平台管理权限列表 -// @Description get platform management permissions -// @Id GetManagementPermissionsV1 -// @Tags management_permission -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetManagementPermissionsResV1 -// @Router /v1/management_permissions [get] -func GetManagementPermissions(c echo.Context) error { - p := model.GetManagementPermission() - data := []*ManagementPermissionResV1{} - for u, s := range p { - data = append(data, &ManagementPermissionResV1{ - Code: u, - Desc: s, - }) - } - - return c.JSON(http.StatusOK, GetManagementPermissionsResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: data, - }) -} diff --git a/sqle/api/controller/v1/oauth2.go b/sqle/api/controller/v1/oauth2.go deleted file mode 100644 index 8525290ed7..0000000000 --- a/sqle/api/controller/v1/oauth2.go +++ /dev/null @@ -1,46 +0,0 @@ -package v1 - -import ( - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/labstack/echo/v4" -) - -// @Summary oauth2通过此链接跳转到第三方登录网址 -// @Description oauth2 link -// @Id Oauth2Link -// @Tags oauth2 -// @router /v1/oauth2/link [get] -func Oauth2Link(c echo.Context) error { - return oauth2Link(c) -} - -// Oauth2Callback is a hidden interface for third-party platform callbacks for oauth2 verification -func Oauth2Callback(c echo.Context) error { - return oauth2Callback(c) -} - -type BindOauth2UserReqV1 struct { - UserName string `json:"user_name" from:"user_name" valid:"required"` - Pwd string `json:"pwd" from:"pwd" valid:"required"` - Oauth2Token string `json:"oauth2_token" from:"oauth2_token" valid:"required"` -} - -type BindOauth2UserResV1 struct { - controller.BaseRes - Data BindOauth2UserResDataV1 `json:"data"` -} - -type BindOauth2UserResDataV1 struct { - Token string `json:"token"` -} - -// @Summary 绑定 Oauth2 和 sqle用户 -// @Description bind Oauth2 user to sqle -// @Id bindOauth2User -// @Tags oauth2 -// @Param conf body v1.BindOauth2UserReqV1 true "bind oauth2 user req" -// @Success 200 {object} v1.BindOauth2UserResV1 -// @router /v1/oauth2/user/bind [post] -func BindOauth2User(c echo.Context) error { - return bindOauth2User(c) -} diff --git a/sqle/api/controller/v1/oauth2_ce.go b/sqle/api/controller/v1/oauth2_ce.go deleted file mode 100644 index 0b1ade4e11..0000000000 --- a/sqle/api/controller/v1/oauth2_ce.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build !enterprise -// +build !enterprise - -package v1 - -import ( - "fmt" - - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/errors" - - "github.com/labstack/echo/v4" -) - -var errNotSupportOauth2 = errors.New(errors.EnterpriseEditionFeatures, fmt.Errorf("oauth2 related functions are enterprise version functions")) - -func oauth2Link(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errNotSupportOauth2) -} - -func oauth2Callback(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errNotSupportOauth2) -} - -func bindOauth2User(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errNotSupportOauth2) -} diff --git a/sqle/api/controller/v1/project.go b/sqle/api/controller/v1/project.go deleted file mode 100644 index 2a7f617103..0000000000 --- a/sqle/api/controller/v1/project.go +++ /dev/null @@ -1,322 +0,0 @@ -package v1 - -import ( - "fmt" - "net/http" - "time" - - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/model" - - "github.com/labstack/echo/v4" -) - -var ( - ErrProjectNotExist = func(projectName string) error { - return errors.New(errors.DataNotExist, fmt.Errorf("project [%v] is not exist", projectName)) - } - ErrProjectArchived = errors.New(errors.ErrAccessDeniedError, fmt.Errorf("project is archived")) -) - -type GetProjectReqV1 struct { - PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` - PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` -} - -type GetProjectResV1 struct { - controller.BaseRes - Data []*ProjectListItem `json:"data"` - TotalNums uint64 `json:"total_nums"` -} - -type ProjectListItem struct { - Name string `json:"name"` - Desc string `json:"desc"` - CreateUserName string `json:"create_user_name"` - CreateTime *time.Time `json:"create_time"` - Archived bool `json:"archived"` -} - -// GetProjectListV1 -// @Summary 获取项目列表 -// @Description get project list -// @Tags project -// @Id getProjectListV1 -// @Security ApiKeyAuth -// @Param page_index query uint32 true "page index" -// @Param page_size query uint32 true "size of per page" default(50) -// @Success 200 {object} v1.GetProjectResV1 -// @router /v1/projects [get] -func GetProjectListV1(c echo.Context) error { - req := new(GetProjectReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - limit, offset := controller.GetLimitAndOffset(req.PageIndex, req.PageSize) - - user := controller.GetUserName(c) - - mp := map[string]interface{}{ - "limit": limit, - "offset": offset, - "filter_user_name": user, - } - - s := model.GetStorage() - projects, total, err := s.GetProjectsByReq(mp) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - resp := []*ProjectListItem{} - for _, project := range projects { - resp = append(resp, &ProjectListItem{ - Name: project.Name, - Desc: project.Desc, - CreateUserName: project.CreateUserName, - CreateTime: &project.CreateTime, - Archived: project.Status == model.ProjectStatusArchived, - }) - } - - return c.JSON(http.StatusOK, &GetProjectResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: resp, - TotalNums: total, - }) -} - -type GetProjectDetailResV1 struct { - controller.BaseRes - Data ProjectDetailItem `json:"data"` -} - -type ProjectDetailItem struct { - Name string `json:"name"` - Desc string `json:"desc"` - CreateUserName string `json:"create_user_name"` - CreateTime *time.Time `json:"create_time"` - Archived bool `json:"archived"` -} - -// GetProjectDetailV1 -// @Summary 获取项目详情 -// @Description get project detail -// @Tags project -// @Id getProjectDetailV1 -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Success 200 {object} v1.GetProjectDetailResV1 -// @router /v1/projects/{project_name}/ [get] -func GetProjectDetailV1(c echo.Context) error { - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - s := model.GetStorage() - err := CheckIsProjectMember(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - - return c.JSON(http.StatusOK, GetProjectDetailResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: ProjectDetailItem{ - Name: project.Name, - Desc: project.Desc, - CreateUserName: project.CreateUser.Name, - CreateTime: &project.CreatedAt, - Archived: project.Status == model.ProjectStatusArchived, - }, - }) -} - -type CreateProjectReqV1 struct { - Name string `json:"name" valid:"required"` - Desc string `json:"desc"` -} - -// CreateProjectV1 -// @Summary 创建项目 -// @Description create project -// @Accept json -// @Produce json -// @Tags project -// @Id createProjectV1 -// @Security ApiKeyAuth -// @Param project body v1.CreateProjectReqV1 true "create project request" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects [post] -func CreateProjectV1(c echo.Context) error { - return createProjectV1(c) -} - -type UpdateProjectReqV1 struct { - Desc *string `json:"desc"` -} - -// UpdateProjectV1 -// @Summary 更新项目 -// @Description update project -// @Accept json -// @Produce json -// @Tags project -// @Id updateProjectV1 -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param project body v1.UpdateProjectReqV1 true "create project request" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/ [patch] -func UpdateProjectV1(c echo.Context) error { - req := new(UpdateProjectReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - user, err := controller.GetCurrentUser(c) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - projectName := c.Param("project_name") - err = CheckIsProjectManager(user.Name, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - sure, err := s.CheckUserCanUpdateProject(projectName, user.ID) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !sure { - return controller.JSONBaseErrorReq(c, fmt.Errorf("you can not modify this project")) - } - - attr := map[string]interface{}{} - if req.Desc != nil { - attr["desc"] = *req.Desc - } - - return controller.JSONBaseErrorReq(c, s.UpdateProjectInfoByID(projectName, attr)) -} - -// DeleteProjectV1 -// @Summary 删除项目 -// @Description delete project -// @Id deleteProjectV1 -// @Tags project -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/ [delete] -func DeleteProjectV1(c echo.Context) error { - return deleteProjectV1(c) -} - -type GetProjectTipsReqV1 struct { - FunctionalModule string `json:"functional_module" query:"functional_module"` -} - -type GetProjectTipsResV1 struct { - controller.BaseRes - Data []ProjectTipResV1 `json:"data"` -} - -type ProjectTipResV1 struct { - Name string `json:"project_name"` -} - -// GetProjectTipsV1 -// @Summary 获取项目提示列表 -// @Description get project tip list -// @Tags project -// @Id getProjectTipsV1 -// @Security ApiKeyAuth -// @Param functional_module query string false "functional module" Enums(operation_record) -// @Success 200 {object} v1.GetProjectTipsResV1 -// @router /v1/project_tips [get] -func GetProjectTipsV1(c echo.Context) error { - req := new(GetProjectTipsReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - - data := []ProjectTipResV1{} - - switch req.FunctionalModule { - case "operation_record": - projectNameList, err := s.GetOperationRecordProjectNameList() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - for _, projectName := range projectNameList { - data = append(data, ProjectTipResV1{ - Name: projectName, - }) - } - default: - projects, err := s.GetProjectTips(controller.GetUserName(c)) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - for _, project := range projects { - data = append(data, ProjectTipResV1{ - Name: project.Name, - }) - } - } - - return c.JSON(http.StatusOK, GetProjectTipsResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: data, - }) -} - -// ArchiveProjectV1 -// @Summary 归档项目 -// @Description archive project -// @Accept json -// @Produce json -// @Tags project -// @Id archiveProjectV1 -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/archive [post] -func ArchiveProjectV1(c echo.Context) error { - return archiveProjectV1(c) -} - -// UnarchiveProjectV1 -// @Summary 取消归档项目 -// @Description archive project -// @Accept json -// @Produce json -// @Tags project -// @Id unarchiveProjectV1 -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/unarchive [post] -func UnarchiveProjectV1(c echo.Context) error { - return unarchiveProjectV1(c) -} diff --git a/sqle/api/controller/v1/project_ce.go b/sqle/api/controller/v1/project_ce.go deleted file mode 100644 index de6ddb216d..0000000000 --- a/sqle/api/controller/v1/project_ce.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:build !enterprise -// +build !enterprise - -package v1 - -import ( - e "errors" - - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/errors" - - "github.com/labstack/echo/v4" -) - -var errCommunityEditionDoesNotSupportCreateProject = errors.New(errors.EnterpriseEditionFeatures, e.New("community edition does not support create project")) -var errCommunityEditionDoesNotSupportDeleteProject = errors.New(errors.EnterpriseEditionFeatures, e.New("community edition does not support delete project")) -var errCommunityEditionDoesNotSupportArchiveProject = errors.New(errors.EnterpriseEditionFeatures, e.New("community edition does not support suspend project")) -var errCommunityEditionDoesNotSupportUnarchiveProject = errors.New(errors.EnterpriseEditionFeatures, e.New("community edition does not support unarchive project")) - -func createProjectV1(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportCreateProject) -} - -func deleteProjectV1(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportDeleteProject) -} - -func archiveProjectV1(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportArchiveProject) -} - -func unarchiveProjectV1(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportUnarchiveProject) -} diff --git a/sqle/api/controller/v1/project_permission.go b/sqle/api/controller/v1/project_permission.go index eac50c1e22..815b7fb06a 100644 --- a/sqle/api/controller/v1/project_permission.go +++ b/sqle/api/controller/v1/project_permission.go @@ -1,70 +1,33 @@ package v1 import ( + "context" "fmt" + "strconv" + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/model" + "github.com/labstack/echo/v4" ) -/* - -project permission. - -*/ - -func CheckIsProjectMember(userName, projectName string) error { - if userName == model.DefaultAdminUser { - return nil - } - s := model.GetStorage() - isMember, err := s.IsUserInProject(userName, projectName) +func CheckCurrentUserCanOperateWorkflow(c echo.Context, projectUid string, workflow *model.Workflow, ops []dmsV1.OpPermissionType) error { + userId := controller.GetUserID(c) + up, err := dms.NewUserPermission(userId, projectUid) if err != nil { return err } - if !isMember { - return errors.New(errors.UserNotPermission, fmt.Errorf("the project does not exist or user %v is not in project %v", userName, projectName)) - } - return nil -} - -func CheckIsProjectManager(userName, projectName string) error { - if userName == model.DefaultAdminUser { + if up.IsAdmin() { return nil } - s := model.GetStorage() - isManager, err := s.IsProjectManager(userName, projectName) - if err != nil { - return err - } - if !isManager { - return errors.New(errors.UserNotPermission, fmt.Errorf("the project does not exist or the user does not have permission to operate")) - } - return nil -} - -func CheckCurrentUserCanOperateTasks(c echo.Context, project *model.Project, workflow *model.Workflow, ops []uint, taskIdList []uint) error { - if controller.GetUserName(c) == model.DefaultAdminUser { - return nil - } - user, err := controller.GetCurrentUser(c) - if err != nil { - return err - } s := model.GetStorage() - - isManager, err := s.IsProjectManager(user.Name, project.Name) - if err != nil { - return err - } - if isManager { - return nil - } - - access, err := s.UserCanAccessWorkflow(user, workflow) + access, err := s.UserCanAccessWorkflow(userId, workflow) if err != nil { return err } @@ -73,92 +36,79 @@ func CheckCurrentUserCanOperateTasks(c echo.Context, project *model.Project, wor } if len(ops) > 0 { - instances, err := s.GetInstanceByTaskIDList(taskIdList) - if err != nil { - return err - } - - ok, err := s.CheckUserHasOpToInstances(user, instances, ops) - if err != nil { - return err - } - if ok { - return nil + for _, item := range workflow.Record.InstanceRecords { + if !up.CanOpInstanceNoAdmin(item.Instance.GetIDStr(), ops...) { + return ErrWorkflowNoAccess + } } + return nil } - return ErrWorkflowNoAccess } -/* - -workflow permission. - -*/ - -func CheckCurrentUserCanOperateWorkflow(c echo.Context, project *model.Project, workflow *model.Workflow, ops []uint) error { - if controller.GetUserName(c) == model.DefaultAdminUser { - return nil - } - user, err := controller.GetCurrentUser(c) - if err != nil { - return err - } - - s := model.GetStorage() - - isManager, err := s.IsProjectManager(user.Name, project.Name) +func CheckCurrentUserCanOperateTasks(c echo.Context, projectUid string, workflow *model.Workflow, ops []dmsV1.OpPermissionType, taskIdList []uint) error { + userId := controller.GetUserID(c) + up, err := dms.NewUserPermission(userId, projectUid) if err != nil { return err } - if isManager { + if up.IsAdmin() { return nil } - access, err := s.UserCanAccessWorkflow(user, workflow) + s := model.GetStorage() + + access, err := s.UserCanAccessWorkflow(userId, workflow) if err != nil { return err } if access { return nil } + if len(ops) > 0 { - instances, err := s.GetInstancesByWorkflowID(workflow.ID) + workflowInstances, err := s.GetWorkInstanceRecordByTaskIds(taskIdList) if err != nil { return err } - ok, err := s.CheckUserHasOpToInstances(user, instances, ops) + + instanceIds := make([]uint64, 0, len(workflowInstances)) + for _, item := range workflowInstances { + instanceIds = append(instanceIds, item.InstanceId) + } + + instances, err := dms.GetInstancesInProjectByIds(c.Request().Context(), projectUid, instanceIds) if err != nil { return err } - if ok { - return nil + for _, instance := range instances { + if up.CanOpInstanceNoAdmin(instance.GetIDStr(), ops...) { + return nil + } } } + return ErrWorkflowNoAccess } -func checkCurrentUserCanAccessTask(c echo.Context, task *model.Task, ops []uint) error { - user, err := controller.GetCurrentUser(c) - if err != nil { - return err - } - - if controller.GetUserName(c) == model.DefaultAdminUser { +func checkCurrentUserCanAccessTask(c echo.Context, task *model.Task, ops []dmsV1.OpPermissionType) error { + userId := controller.GetUserID(c) + // todo issues-2005 + if task.Instance == nil || task.Instance.ProjectId == "" { return nil } - if user.ID == task.CreateUserId { - return nil - } - s := model.GetStorage() - isManager, err := s.IsProjectManagerByID(user.ID, task.Instance.ProjectId) + up, err := dms.NewUserPermission(userId, task.Instance.ProjectId) if err != nil { return err } - if isManager { + if up.IsAdmin() { + return nil + } + if userId == fmt.Sprintf("%d", task.CreateUserId) { return nil } + s := model.GetStorage() workflow, exist, err := s.GetWorkflowByTaskId(task.ID) if err != nil { return err @@ -166,191 +116,186 @@ func checkCurrentUserCanAccessTask(c echo.Context, task *model.Task, ops []uint) if !exist { return errors.NewTaskNoExistOrNoAccessErr() } - access, err := s.UserCanAccessWorkflow(user, workflow) + access, err := s.UserCanAccessWorkflow(userId, workflow) if err != nil { return err } if access { return nil } - if len(ops) > 0 { - ok, err := s.CheckUserHasOpToInstances(user, []*model.Instance{task.Instance}, ops) - if err != nil { - return err - } - if ok { - return nil - } + + if up.CanOpInstanceNoAdmin(task.Instance.GetIDStr(), ops...) { + return nil } return errors.NewTaskNoExistOrNoAccessErr() } -func CheckCurrentUserCanViewWorkflow(c echo.Context, workflowName, projectName string) error { - userName := controller.GetUserName(c) - s := model.GetStorage() - isManager, err := s.IsProjectManager(userName, projectName) - if err != nil { - return err - } - if userName == model.DefaultAdminUser || isManager { - return nil +func GetAuditPlanIfCurrentUserCanAccess(c echo.Context, projectId, auditPlanName string, opType v1.OpPermissionType) (*model.AuditPlan, bool, error) { + storage := model.GetStorage() + + ap, exist, err := dms.GetAuditPlanWithInstanceFromProjectByName(projectId, auditPlanName, storage.GetAuditPlanFromProjectByName) + if err != nil || !exist { + return nil, exist, err } - user, err := controller.GetCurrentUser(c) + + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { - return err + return nil, false, err } - workflow, _, err := s.GetWorkflowByProjectAndWorkflowName(projectName, workflowName) - if err != nil { - return err + + if ap.CreateUserID == user.GetIDStr() { + return ap, true, nil } - access, err := s.UserCanAccessWorkflow(user, workflow) + _, isAdmin, err := dmsobject.GetUserOpPermission(c.Request().Context(), projectId, user.GetIDStr(), controller.GetDMSServerAddress()) if err != nil { - return err + return nil, false, err } - if access { - return nil + if isAdmin { + return ap, true, nil } - instances, err := s.GetInstancesByWorkflowID(workflow.ID) - if err != nil { - return err + + if opType != "" { + instances, err := GetCanOperationInstances(c.Request().Context(), user, "", projectId, opType) + if err != nil { + return nil, false, errors.NewUserNotPermissionError(string(opType)) + } + for _, instance := range instances { + if ap.InstanceName == instance.Name { + return ap, true, nil + } + } } - ok, err := s.CheckUserHasOpToAnyInstance(user, instances, []uint{model.OP_WORKFLOW_VIEW_OTHERS}) + return ap, false, errors.NewUserNotPermissionError(v1.GetOperationTypeDesc(opType)) +} + +func CheckCurrentUserCanAccessInstances(ctx context.Context, projectUID string, userId string, instances []*model.Instance) (bool, error) { + up, err := dms.NewUserPermission(userId, projectUID) if err != nil { - return err + return false, fmt.Errorf("get user op permission from dms error: %v", err) } - if ok { - return nil + if up.IsAdmin() { + return true, nil } - return ErrWorkflowNoAccess -} - -func CheckCurrentUserCanCreateWorkflow(user *model.User, tasks []*model.Task, projectName string) error { - if model.IsDefaultAdminUser(user.Name) { - return nil + for _, instance := range instances { + if !up.CanOpInstanceNoAdmin(instance.GetIDStr(), dms.GetAllOpPermissions()...) { + return false, nil + } } + return true, nil +} - s := model.GetStorage() - - isManager, err := s.IsProjectManager(user.Name, projectName) +func CheckCurrentUserCanCreateWorkflow(ctx context.Context, projectUID string, user *model.User, tasks []*model.Task) (bool, error) { + up, err := dms.NewUserPermission(user.GetIDStr(), projectUID) if err != nil { - return err + return false, err } - - if isManager { - return nil + if up.IsAdmin() { + return true, nil } instances := make([]*model.Instance, len(tasks)) for i, task := range tasks { instances[i] = task.Instance } - - ok, err := s.CheckUserHasOpToInstances(user, instances, []uint{model.OP_WORKFLOW_SAVE}) - if err != nil { - return err - } - if !ok { - return errors.NewAccessDeniedErr("user has no access to create workflow for instance") + for _, instance := range instances { + if !up.CanOpInstanceNoAdmin(instance.GetIDStr(), dmsV1.OpPermissionTypeCreateWorkflow) { + return false, nil + } } - - return nil + return true, nil } -/* - -instance permission. - -*/ - -// 1. admin user have all access to all instance -// 2. non-admin user have access to instance which is bound to one of his roles -func checkCurrentUserCanAccessInstance(c echo.Context, instance *model.Instance) (bool, error) { - if controller.GetUserName(c) == model.DefaultAdminUser { - return true, nil - } - user, err := controller.GetCurrentUser(c) - if err != nil { - return false, err - } - s := model.GetStorage() - access, err := s.UserCanAccessInstance(user, instance) +func CheckUserCanCreateAuditPlan(ctx context.Context, projectUID string, user *model.User, instances []*model.Instance) (bool, error) { + up, err := dms.NewUserPermission(user.GetIDStr(), projectUID) if err != nil { return false, err } - if !access { - return false, nil - } - return true, nil -} - -func checkCurrentUserCanAccessInstances(c echo.Context, instances []*model.Instance) (bool, error) { - if len(instances) == 0 { - return false, nil + if up.IsAdmin() { + return true, nil } - for _, instance := range instances { - can, err := checkCurrentUserCanAccessInstance(c, instance) - if err != nil { - return false, err - } - if !can { + if !up.CanOpInstanceNoAdmin(instance.GetIDStr(), dmsV1.OpPermissionTypeSaveAuditPlan) { return false, nil } } - return true, nil } -/* - -audit plan permission. - -*/ - -func GetAuditPlanIfCurrentUserCanAccess(c echo.Context, projectName, auditPlanName string, opCode int) (*model.AuditPlan, bool, error) { - storage := model.GetStorage() - - userName := controller.GetUserName(c) - err := CheckIsProjectMember(userName, projectName) +// 根据用户权限获取能访问/操作的实例列表 +func GetCanOperationInstances(ctx context.Context, user *model.User, dbType, projectUid string, operationType v1.OpPermissionType) ([]*model.Instance, error) { + // 获取当前项目下指定数据库类型的全部实例 + instances, err := dms.GetInstancesInProjectByType(ctx, projectUid, dbType) if err != nil { - return nil, false, err + return nil, err } - ap, exist, err := storage.GetAuditPlanFromProjectByName(projectName, auditPlanName) - if err != nil || !exist { - return nil, exist, err + userOpPermissions, isAdmin, err := dmsobject.GetUserOpPermission(ctx, projectUid, user.GetIDStr(), controller.GetDMSServerAddress()) + if err != nil { + return nil, err } - if controller.GetUserName(c) == model.DefaultAdminUser { - return ap, true, nil + if isAdmin || operationType == "" { + return instances, nil } - - user, err := controller.GetCurrentUser(c) - if err != nil { - return nil, false, err + canOperationInstance := make([]*model.Instance, 0) + for _, instance := range instances { + if CanOperationInstance(userOpPermissions, []v1.OpPermissionType{operationType}, instance) { + canOperationInstance = append(canOperationInstance, instance) + } } + return canOperationInstance, nil +} - if ap.CreateUserID == user.ID { - return ap, true, nil +func GetCanOpInstanceUsers(memberWithPermissions []*dmsV1.ListMembersForInternalItem, instance *model.Instance, opPermissioins []dmsV1.OpPermissionType) (opUsers []*model.User, err error) { + opMapUsers := make(map[uint]struct{}, 0) + for _, memberWithPermission := range memberWithPermissions { + for _, memberOpPermission := range memberWithPermission.MemberOpPermissionList { + if CanOperationInstance([]dmsV1.OpPermissionItem{memberOpPermission}, opPermissioins, instance) { + opUser := new(model.User) + userId, err := strconv.Atoi(memberWithPermission.User.Uid) + if err != nil { + return nil, err + } + opUser.ID = uint(userId) + opUser.Name = memberWithPermission.User.Name + if _, ok := opMapUsers[opUser.ID]; !ok { + opMapUsers[opUser.ID] = struct{}{} + opUsers = append(opUsers, opUser) + } + } + } } + return opUsers, nil +} - err = CheckIsProjectManager(userName, projectName) - if err == nil { - return ap, true, nil - } +func CanOperationInstance(userOpPermissions []dmsV1.OpPermissionItem, needOpPermissionTypes []dmsV1.OpPermissionType, instance *model.Instance) bool { + for _, userOpPermission := range userOpPermissions { + // 对象权限(当前空间内所有对象) + if userOpPermission.RangeType == dmsV1.OpRangeTypeProject { + return true + } - if opCode > 0 { - instances, err := storage.GetUserCanOpInstancesFromProject(user, projectName, []uint{uint(opCode)}) - if err != nil { - return nil, false, errors.NewUserNotPermissionError(model.GetOperationCodeDesc(uint(opCode))) + // 动作权限(创建、审核、上线工单等) + hasPrivilege := false + for _, needOpPermissionType := range needOpPermissionTypes { + if needOpPermissionType == userOpPermission.OpPermissionType { + hasPrivilege = true + break + } } - for _, instance := range instances { - if ap.InstanceName == instance.Name { - return ap, true, nil + if !hasPrivilege { + continue + } + // 对象权限(指定数据源) + if userOpPermission.RangeType == dmsV1.OpRangeTypeDBService { + for _, id := range userOpPermission.RangeUids { + if id == instance.GetIDStr() { + return true + } } } } - return nil, false, errors.NewUserNotPermissionError(model.GetOperationCodeDesc(uint(opCode))) + return false } diff --git a/sqle/api/controller/v1/role.go b/sqle/api/controller/v1/role.go deleted file mode 100644 index e78e8e9d5a..0000000000 --- a/sqle/api/controller/v1/role.go +++ /dev/null @@ -1,311 +0,0 @@ -package v1 - -import ( - "fmt" - "net/http" - - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/model" - - "github.com/labstack/echo/v4" -) - -// @Summary 删除角色 -// @Description delete role -// @Id deleteRoleV1 -// @Tags role -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param role_name path string true "role name" -// @Success 200 {object} controller.BaseRes -// @router /v1/roles/{role_name}/ [delete] -func DeleteRole(c echo.Context) error { - roleName := c.Param("role_name") - s := model.GetStorage() - role, exist, err := s.GetRoleByName(roleName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("role is not exist"))) - } - - return controller.JSONBaseErrorReq(c, - s.DeleteRoleAndAssociations(role)) -} - -type RoleTipResV1 struct { - Name string `json:"role_name"` - Operations []*Operation `json:"operations,omitempty"` -} - -type GetRoleTipsResV1 struct { - controller.BaseRes - Data []RoleTipResV1 `json:"data"` -} - -// @Summary 获取角色提示列表 -// @Description get role tip list -// @Tags role -// @Id getRoleTipListV1 -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetRoleTipsResV1 -// @router /v1/role_tips [get] -func GetRoleTips(c echo.Context) error { - s := model.GetStorage() - roles, err := s.GetAllRoleTip() - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - roleTipsRes := make([]RoleTipResV1, 0, len(roles)) - - for i, role := range roles { - ops := make([]*Operation, len(roles[i].OperationsCodes)) - opCodes := roles[i].OperationsCodes.ForceConvertIntSlice() - for i := range opCodes { - ops[i] = &Operation{ - Code: opCodes[i], - Desc: model.GetOperationCodeDesc(opCodes[i]), - } - } - roleTipRes := RoleTipResV1{ - Name: role.Name, - Operations: ops, - } - roleTipsRes = append(roleTipsRes, roleTipRes) - } - return c.JSON(http.StatusOK, &GetRoleTipsResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: roleTipsRes, - }) -} - -type CreateRoleReqV1 struct { - Name string `json:"role_name" form:"role_name" valid:"required,name"` - Desc string `json:"role_desc" form:"role_desc"` - OperationCodes []uint `json:"operation_code_list" form:"operation_code_list"` -} - -// @Summary 创建角色 -// @Description create role -// @Id createRoleV1 -// @Tags role -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param instance body v1.CreateRoleReqV1 true "create role" -// @Success 200 {object} controller.BaseRes -// @router /v1/roles [post] -func CreateRole(c echo.Context) (err error) { - - req := new(CreateRoleReqV1) - { - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - } - - s := model.GetStorage() - - // check if role name already exists - { - _, exist, err := s.GetRoleByName(req.Name) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if exist { - return controller.JSONNewDataExistErr(c, "role<%s> is exist", req.Name) - } - } - - // check operation codes - { - if len(req.OperationCodes) > 0 { - if err := model.CheckIfOperationCodeValid(req.OperationCodes); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - } - - newRole := &model.Role{ - Name: req.Name, - Desc: req.Desc, - } - - return controller.JSONBaseErrorReq(c, - s.SaveRoleAndAssociations(newRole, req.OperationCodes), - ) -} - -type GetRolesReqV1 struct { - FilterRoleName string `json:"filter_role_name" query:"filter_role_name"` - PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` - PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` -} - -type GetRolesResV1 struct { - controller.BaseRes - Data []*RoleResV1 `json:"data"` - TotalNums uint64 `json:"total_nums"` -} - -type Operation struct { - Code uint `json:"op_code"` - Desc string `json:"op_desc"` -} - -type RoleResV1 struct { - Name string `json:"role_name"` - Desc string `json:"role_desc"` - Operations []*Operation `json:"operation_list,omitempty"` - IsDisabled bool `json:"is_disabled,omitempty"` -} - -// @Summary 获取角色列表 -// @Description get role list -// @Id getRoleListV1 -// @Tags role -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param filter_role_name query string false "filter role name" -// @Param page_index query uint32 true "page index" -// @Param page_size query uint32 true "size of per page" -// @Success 200 {object} v1.GetRolesResV1 -// @router /v1/roles [get] -func GetRoles(c echo.Context) error { - req := new(GetRolesReqV1) - { - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - } - - s := model.GetStorage() - - var queryCondition map[string]interface{} - { - limit, offset := controller.GetLimitAndOffset(req.PageIndex, req.PageSize) - queryCondition = map[string]interface{}{ - "filter_role_name": req.FilterRoleName, - "limit": limit, - "offset": offset, - } - } - - roles, count, err := s.GetRolesByReq(queryCondition) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - roleRes := make([]*RoleResV1, len(roles)) - for i := range roles { - ops := make([]*Operation, len(roles[i].OperationsCodes)) - opCodes := roles[i].OperationsCodes.ForceConvertIntSlice() - for i := range opCodes { - ops[i] = &Operation{ - Code: opCodes[i], - Desc: model.GetOperationCodeDesc(opCodes[i]), - } - } - roleRes[i] = &RoleResV1{ - Name: roles[i].Name, - Desc: roles[i].Desc, - IsDisabled: roles[i].IsDisabled(), - Operations: ops, - } - - } - - return c.JSON(http.StatusOK, &GetRolesResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: roleRes, - TotalNums: count, - }) -} - -type UpdateRoleReqV1 struct { - Desc *string `json:"role_desc" form:"role_desc"` - OperationCodes *[]uint `json:"operation_code_list,omitempty" form:"operation_code_list"` - IsDisabled *bool `json:"is_disabled,omitempty"` -} - -// @Summary 更新角色信息 -// @Description update role -// @Id updateRoleV1 -// @Tags role -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param role_name path string true "role name" -// @Param instance body v1.UpdateRoleReqV1 true "update role request" -// @Success 200 {object} controller.BaseRes -// @router /v1/roles/{role_name}/ [patch] -func UpdateRole(c echo.Context) (err error) { - - req := new(UpdateRoleReqV1) - { - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - } - - s := model.GetStorage() - roleName := c.Param("role_name") - - // check if role name exists - var role *model.Role - { - var isExist bool - role, isExist, err = s.GetRoleByName(roleName) - if err != nil { - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - if !isExist { - return controller.JSONNewDataNotExistErr(c, - `role is not exist`) - } - } - - // update stat - { - if req.IsDisabled != nil { - if *req.IsDisabled { - role.Stat = model.Disabled - } else { - role.Stat = model.Enabled - } - - } - } - - // update desc - if req.Desc != nil { - role.Desc = *req.Desc - } - - // check operation codes - var opCodes []uint - { - if req.OperationCodes != nil { - if len(*req.OperationCodes) > 0 { - if err := model.CheckIfOperationCodeValid(*req.OperationCodes); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - opCodes = *req.OperationCodes - } else { - opCodes = make([]uint, 0) - } - } - } - - return controller.JSONBaseErrorReq(c, - s.SaveRoleAndAssociations(role, opCodes), - ) - -} diff --git a/sqle/api/controller/v1/rule.go b/sqle/api/controller/v1/rule.go index 5b34dadcc3..a59f9c45ac 100644 --- a/sqle/api/controller/v1/rule.go +++ b/sqle/api/controller/v1/rule.go @@ -2,16 +2,16 @@ package v1 import ( "bytes" + "context" "encoding/json" "fmt" "mime" "net/http" - "strconv" "strings" "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" "github.com/labstack/echo/v4" @@ -157,7 +157,7 @@ func CreateRuleTemplate(c echo.Context) error { return err } s := model.GetStorage() - exist, err := s.IsRuleTemplateExistFromAnyProject(req.Name) + exist, err := s.IsRuleTemplateExistFromAnyProject(model.ProjectIdForGlobalRuleTemplate, req.Name) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -166,9 +166,10 @@ func CreateRuleTemplate(c echo.Context) error { } ruleTemplate := &model.RuleTemplate{ - Name: req.Name, - Desc: req.Desc, - DBType: req.DBType, + ProjectId: model.ProjectIdForGlobalRuleTemplate, + Name: req.Name, + Desc: req.Desc, + DBType: req.DBType, } templateRules := []model.RuleTemplateRule{} templateCustomRules := []model.RuleTemplateCustomRule{} @@ -255,40 +256,42 @@ func UpdateRuleTemplate(c echo.Context) error { return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) } +type GetRuleTemplateReqV1 struct { + FuzzyKeywordRule string `json:"fuzzy_keyword_rule" query:"fuzzy_keyword_rule"` +} + type GetRuleTemplateResV1 struct { controller.BaseRes Data *RuleTemplateDetailResV1 `json:"data"` } type RuleTemplateDetailResV1 struct { - Name string `json:"rule_template_name"` - Desc string `json:"desc"` - DBType string `json:"db_type"` - Instances []*GlobalRuleTemplateInstance `json:"instance_list,omitempty"` - RuleList []RuleResV1 `json:"rule_list,omitempty"` + Name string `json:"rule_template_name"` + Desc string `json:"desc"` + DBType string `json:"db_type"` + RuleList []RuleResV1 `json:"rule_list,omitempty"` } -func convertRuleTemplateToRes(template *model.RuleTemplate, instNameToProjectName map[uint]model.ProjectAndInstance) *RuleTemplateDetailResV1 { - instances := make([]*GlobalRuleTemplateInstance, 0, len(template.Instances)) - for _, instance := range template.Instances { - instances = append(instances, &GlobalRuleTemplateInstance{ - ProjectName: instNameToProjectName[instance.ID].ProjectName, - InstanceName: instance.Name, - }) - } +func convertRuleTemplateToRes(template *model.RuleTemplate) *RuleTemplateDetailResV1 { + ruleList := make([]RuleResV1, 0, len(template.RuleList)) for _, r := range template.RuleList { + if r.Rule == nil { + continue + } ruleList = append(ruleList, convertRuleToRes(r.GetRule())) } for _, r := range template.CustomRuleList { + if r.CustomRule == nil { + continue + } ruleList = append(ruleList, convertCustomRuleToRuleResV1(r.GetRule())) } return &RuleTemplateDetailResV1{ - Name: template.Name, - Desc: template.Desc, - DBType: template.DBType, - Instances: instances, - RuleList: ruleList, + Name: template.Name, + Desc: template.Desc, + DBType: template.DBType, + RuleList: ruleList, } } @@ -298,12 +301,17 @@ func convertRuleTemplateToRes(template *model.RuleTemplate, instNameToProjectNam // @Tags rule_template // @Security ApiKeyAuth // @Param rule_template_name path string true "rule template name" +// @Param fuzzy_keyword_rule query string false "fuzzy rule,keyword for desc and annotation" // @Success 200 {object} v1.GetRuleTemplateResV1 // @router /v1/rule_templates/{rule_template_name}/ [get] func GetRuleTemplate(c echo.Context) error { s := model.GetStorage() templateName := c.Param("rule_template_name") - template, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]uint{model.ProjectIdForGlobalRuleTemplate}, templateName) + req := new(GetRuleTemplateReqV1) + if err := controller.BindAndValidateReq(c, req); err != nil { + return err + } + template, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]string{model.ProjectIdForGlobalRuleTemplate}, templateName, req.FuzzyKeywordRule) if err != nil { return c.JSON(200, controller.NewBaseReq(err)) } @@ -312,18 +320,9 @@ func GetRuleTemplate(c echo.Context) error { fmt.Errorf("rule template is not exist")))) } - instanceIds := make([]uint, len(template.Instances)) - for i, inst := range template.Instances { - instanceIds[i] = inst.ID - } - instanceNameToProjectName, err := s.GetProjectNamesByInstanceIds(instanceIds) - if err != nil { - return c.JSON(200, controller.NewBaseReq(err)) - } - return c.JSON(http.StatusOK, &GetRuleTemplateResV1{ BaseRes: controller.NewBaseReq(nil), - Data: convertRuleTemplateToRes(template, instanceNameToProjectName), + Data: convertRuleTemplateToRes(template), }) } @@ -362,7 +361,7 @@ func DeleteRuleTemplate(c echo.Context) error { // check instance { - instanceNames, err := s.GetInstancesNamesByRuleTemplate(templateName) + instanceNames, err := dms.GetInstancesNameByRuleTemplateName(c.Request().Context(), templateName) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -392,15 +391,9 @@ type GetRuleTemplatesResV1 struct { } type RuleTemplateResV1 struct { - Name string `json:"rule_template_name"` - Desc string `json:"desc"` - DBType string `json:"db_type"` - Instances []*GlobalRuleTemplateInstance `json:"instance_list"` -} - -type GlobalRuleTemplateInstance struct { - ProjectName string `json:"project_name"` - InstanceName string `json:"instance_name"` + Name string `json:"rule_template_name"` + Desc string `json:"desc"` + DBType string `json:"db_type"` } // @Summary 全局规则模板列表 @@ -425,37 +418,14 @@ func GetRuleTemplates(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - // get project name and instance name - var instanceIds []uint - templateNameToInstanceIds := make(map[string][]uint) - for _, template := range ruleTemplates { - for _, instIdStr := range template.InstanceIds { - if instIdStr == "" { - continue - } - instId, err := strconv.Atoi(instIdStr) - if err != nil { - log.Logger().Errorf("unexpected instance id. id=%v", instIdStr) - continue - } - instanceIds = append(instanceIds, uint(instId)) - templateNameToInstanceIds[template.Name] = append(templateNameToInstanceIds[template.Name], uint(instId)) - } - } - - instanceIdToProjectName, err := s.GetProjectNamesByInstanceIds(instanceIds) - if err != nil { - return c.JSON(200, controller.NewBaseReq(err)) - } - return c.JSON(http.StatusOK, &GetRuleTemplatesResV1{ BaseRes: controller.NewBaseReq(nil), - Data: convertRuleTemplatesToRes(templateNameToInstanceIds, instanceIdToProjectName, ruleTemplates), + Data: convertRuleTemplatesToRes(ruleTemplates), TotalNums: count, }) } -func getRuleTemplatesByReq(s *model.Storage, limit, offset uint32, projectId uint) (ruleTemplates []*model.RuleTemplateDetail, count uint64, err error) { +func getRuleTemplatesByReq(s *model.Storage, limit, offset uint32, projectId string) (ruleTemplates []*model.RuleTemplateDetail, count uint64, err error) { data := map[string]interface{}{ "limit": limit, "offset": offset, @@ -468,24 +438,14 @@ func getRuleTemplatesByReq(s *model.Storage, limit, offset uint32, projectId uin return } -func convertRuleTemplatesToRes(templateNameToInstanceIds map[string][]uint, - instanceIdToProjectName map[uint] /*instance id*/ model.ProjectAndInstance, - ruleTemplates []*model.RuleTemplateDetail) []RuleTemplateResV1 { +func convertRuleTemplatesToRes(ruleTemplates []*model.RuleTemplateDetail) []RuleTemplateResV1 { ruleTemplatesReq := make([]RuleTemplateResV1, 0, len(ruleTemplates)) for _, ruleTemplate := range ruleTemplates { - instances := make([]*GlobalRuleTemplateInstance, len(templateNameToInstanceIds[ruleTemplate.Name])) - for i, instId := range templateNameToInstanceIds[ruleTemplate.Name] { - instances[i] = &GlobalRuleTemplateInstance{ - ProjectName: instanceIdToProjectName[instId].ProjectName, - InstanceName: instanceIdToProjectName[instId].InstanceName, - } - } ruleTemplateReq := RuleTemplateResV1{ - Name: ruleTemplate.Name, - Desc: ruleTemplate.Desc, - DBType: ruleTemplate.DBType, - Instances: instances, + Name: ruleTemplate.Name, + Desc: ruleTemplate.Desc, + DBType: ruleTemplate.DBType, } ruleTemplatesReq = append(ruleTemplatesReq, ruleTemplateReq) } @@ -496,6 +456,7 @@ type GetRulesReqV1 struct { FilterDBType string `json:"filter_db_type" query:"filter_db_type"` FilterGlobalRuleTemplateName string `json:"filter_global_rule_template_name" query:"filter_global_rule_template_name"` FilterRuleNames string `json:"filter_rule_names" query:"filter_rule_names"` + FuzzyKeywordRule string `json:"fuzzy_keyword_rule" query:"fuzzy_keyword_rule"` } type GetRulesResV1 struct { @@ -580,6 +541,7 @@ func convertRulesToRes(rules interface{}) []RuleResV1 { // @Tags rule_template // @Security ApiKeyAuth // @Param filter_db_type query string false "filter db type" +// @Param fuzzy_keyword_rule query string false "fuzzy rule,keyword for desc and annotation" // @Param filter_global_rule_template_name query string false "filter global rule template name" // @Param filter_rule_names query string false "filter rule name list" // @Success 200 {object} v1.GetRulesResV1 @@ -597,6 +559,7 @@ func GetRules(c echo.Context) error { "filter_global_rule_template_name": req.FilterGlobalRuleTemplateName, "filter_db_type": req.FilterDBType, "filter_rule_names": req.FilterRuleNames, + "fuzzy_keyword_rule": req.FuzzyKeywordRule, }) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -605,6 +568,7 @@ func GetRules(c echo.Context) error { "filter_global_rule_template_name": req.FilterGlobalRuleTemplateName, "filter_db_type": req.FilterDBType, "filter_rule_names": req.FilterRuleNames, + "fuzzy_keyword_rule": req.FuzzyKeywordRule, }) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -624,6 +588,7 @@ type RuleTemplateTipReqV1 struct { } type RuleTemplateTipResV1 struct { + ID string `json:"rule_template_id"` Name string `json:"rule_template_name"` DBType string `json:"db_type"` } @@ -650,7 +615,7 @@ func GetRuleTemplateTips(c echo.Context) error { return getRuleTemplateTips(c, model.ProjectIdForGlobalRuleTemplate, req.FilterDBType) } -func getRuleTemplateTips(c echo.Context, projectId uint, filterDBType string) error { +func getRuleTemplateTips(c echo.Context, projectId string, filterDBType string) error { s := model.GetStorage() ruleTemplates, err := s.GetRuleTemplateTips(projectId, filterDBType) if err != nil { @@ -660,6 +625,7 @@ func getRuleTemplateTips(c echo.Context, projectId uint, filterDBType string) er ruleTemplateTipsRes := make([]RuleTemplateTipResV1, 0, len(ruleTemplates)) for _, roleTemplate := range ruleTemplates { ruleTemplateTipRes := RuleTemplateTipResV1{ + ID: roleTemplate.GetIDStr(), Name: roleTemplate.Name, DBType: roleTemplate.DBType, } @@ -692,7 +658,7 @@ func CloneRuleTemplate(c echo.Context) error { return err } s := model.GetStorage() - exist, err := s.IsRuleTemplateExistFromAnyProject(req.Name) + exist, err := s.IsRuleTemplateExistFromAnyProject(model.ProjectIdForGlobalRuleTemplate, req.Name) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -701,7 +667,7 @@ func CloneRuleTemplate(c echo.Context) error { } sourceTplName := c.Param("rule_template_name") - sourceTpl, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]uint{model.ProjectIdForGlobalRuleTemplate}, sourceTplName) + sourceTpl, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]string{model.ProjectIdForGlobalRuleTemplate}, sourceTplName, "") if err != nil { return c.JSON(200, controller.NewBaseReq(err)) } @@ -711,9 +677,10 @@ func CloneRuleTemplate(c echo.Context) error { } ruleTemplate := &model.RuleTemplate{ - Name: req.Name, - Desc: req.Desc, - DBType: sourceTpl.DBType, + ProjectId: model.ProjectIdForGlobalRuleTemplate, + Name: req.Name, + Desc: req.Desc, + DBType: sourceTpl.DBType, } err = s.Save(ruleTemplate) if err != nil { @@ -748,11 +715,10 @@ func CheckRuleTemplateCanBeBindEachInstance(s *model.Storage, tplName string, in } type CreateProjectRuleTemplateReqV1 struct { - Name string `json:"rule_template_name" valid:"required,name"` - Desc string `json:"desc"` - DBType string `json:"db_type" valid:"required"` - Instances []string `json:"instance_name_list"` - RuleList []RuleReqV1 `json:"rule_list" form:"rule_list" valid:"required,dive,required"` + Name string `json:"rule_template_name" valid:"required,name"` + Desc string `json:"desc"` + DBType string `json:"db_type" valid:"required"` + RuleList []RuleReqV1 `json:"rule_list" form:"rule_list" valid:"required,dive,required"` } // CreateProjectRuleTemplate @@ -771,24 +737,13 @@ func CreateProjectRuleTemplate(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectManager(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - - _, exist, err = s.GetGlobalAndProjectRuleTemplateByNameAndProjectId(req.Name, project.ID) + _, exist, err := s.GetGlobalAndProjectRuleTemplateByNameAndProjectId(req.Name, projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -797,7 +752,7 @@ func CreateProjectRuleTemplate(c echo.Context) error { } ruleTemplate := &model.RuleTemplate{ - ProjectId: project.ID, + ProjectId: model.ProjectUID(projectUid), Name: req.Name, Desc: req.Desc, DBType: req.DBType, @@ -811,23 +766,23 @@ func CreateProjectRuleTemplate(c echo.Context) error { } } - var instances []*model.Instance - if len(req.Instances) > 0 { - instances, err = s.GetAndCheckInstanceExist(req.Instances, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } + // var instances []*model.Instance + // if len(req.Instances) > 0 { + // instances, err = s.GetAndCheckInstanceExist(req.Instances, projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + // } - err = CheckRuleTemplateCanBeBindEachInstance(s, req.Name, instances) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } + // err = CheckRuleTemplateCanBeBindEachInstance(s, req.Name, instances) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } - err = CheckInstanceAndRuleTemplateDbType([]*model.RuleTemplate{ruleTemplate}, instances...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } + // err = CheckInstanceAndRuleTemplateDbType([]*model.RuleTemplate{ruleTemplate}, instances...) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } err = s.Save(ruleTemplate) if err != nil { @@ -843,17 +798,17 @@ func CreateProjectRuleTemplate(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - err = s.UpdateRuleTemplateInstances(ruleTemplate, instances...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } + // TODO SQLE会移除instance参数 + // err = s.UpdateRuleTemplateInstances(ruleTemplate, instances...) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) } type UpdateProjectRuleTemplateReqV1 struct { - Desc *string `json:"desc"` - Instances []string `json:"instance_name_list" example:"mysql-xxx"` - RuleList []RuleReqV1 `json:"rule_list" form:"rule_list" valid:"dive,required"` + Desc *string `json:"desc"` + RuleList []RuleReqV1 `json:"rule_list" form:"rule_list" valid:"dive,required"` } // UpdateProjectRuleTemplate @@ -873,23 +828,12 @@ func UpdateProjectRuleTemplate(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectManager(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - template, exist, err := s.GetGlobalAndProjectRuleTemplateByNameAndProjectId(templateName, project.ID) + template, exist, err := s.GetGlobalAndProjectRuleTemplateByNameAndProjectId(templateName, projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -910,24 +854,6 @@ func UpdateProjectRuleTemplate(c echo.Context) error { } } - var instances []*model.Instance - if len(req.Instances) > 0 { - instances, err = s.GetAndCheckInstanceExist(req.Instances, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - - err = CheckRuleTemplateCanBeBindEachInstance(s, templateName, instances) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - err = CheckInstanceAndRuleTemplateDbType([]*model.RuleTemplate{template}, instances...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if req.Desc != nil { template.Desc = *req.Desc err = s.Save(&template) @@ -946,12 +872,6 @@ func UpdateProjectRuleTemplate(c echo.Context) error { } } - if req.Instances != nil { - err = s.UpdateRuleTemplateInstances(template, instances...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) } @@ -961,11 +881,10 @@ type GetProjectRuleTemplateResV1 struct { } type RuleProjectTemplateDetailResV1 struct { - Name string `json:"rule_template_name"` - Desc string `json:"desc"` - DBType string `json:"db_type"` - Instances []*ProjectRuleTemplateInstance `json:"instance_list,omitempty"` - RuleList []RuleResV1 `json:"rule_list,omitempty"` + Name string `json:"rule_template_name"` + Desc string `json:"desc"` + DBType string `json:"db_type"` + RuleList []RuleResV1 `json:"rule_list,omitempty"` } type ProjectRuleTemplateInstance struct { @@ -980,32 +899,26 @@ type ProjectRuleTemplateInstance struct { // @Security ApiKeyAuth // @Param project_name path string true "project name" // @Param rule_template_name path string true "rule template name" +// @Param fuzzy_keyword_rule query string false "fuzzy rule,keyword for desc and annotation" // @Success 200 {object} v1.GetProjectRuleTemplateResV1 // @router /v1/projects/{project_name}/rule_templates/{rule_template_name}/ [get] func GetProjectRuleTemplate(c echo.Context) error { - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } templateName := c.Param("rule_template_name") - template, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]uint{project.ID}, templateName) + req := new(GetRuleTemplateReqV1) + if err := controller.BindAndValidateReq(c, req); err != nil { + return err + } + template, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]string{projectUid}, templateName, req.FuzzyKeywordRule) if err != nil { - return c.JSON(200, controller.NewBaseReq(err)) + return c.JSON(http.StatusOK, controller.NewBaseReq(err)) } if !exist { - return c.JSON(200, controller.NewBaseReq(errors.New(errors.DataNotExist, + return c.JSON(http.StatusOK, controller.NewBaseReq(errors.New(errors.DataNotExist, fmt.Errorf("rule template is not exist")))) } @@ -1016,25 +929,24 @@ func GetProjectRuleTemplate(c echo.Context) error { } func convertProjectRuleTemplateToRes(template *model.RuleTemplate) *RuleProjectTemplateDetailResV1 { - instances := make([]*ProjectRuleTemplateInstance, 0, len(template.Instances)) - for _, instance := range template.Instances { - instances = append(instances, &ProjectRuleTemplateInstance{ - Name: instance.Name, - }) - } ruleList := make([]RuleResV1, 0, len(template.RuleList)) for _, r := range template.RuleList { + if r.Rule == nil { + continue + } ruleList = append(ruleList, convertRuleToRes(r.GetRule())) } for _, r := range template.CustomRuleList { + if r.CustomRule == nil { + continue + } ruleList = append(ruleList, convertCustomRuleToRuleResV1(r.GetRule())) } return &RuleProjectTemplateDetailResV1{ - Name: template.Name, - Desc: template.Desc, - DBType: template.DBType, - Instances: instances, - RuleList: ruleList, + Name: template.Name, + Desc: template.Desc, + DBType: template.DBType, + RuleList: ruleList, } } @@ -1049,25 +961,15 @@ func convertProjectRuleTemplateToRes(template *model.RuleTemplate) *RuleProjectT // @Success 200 {object} controller.BaseRes // @router /v1/projects/{project_name}/rule_templates/{rule_template_name}/ [delete] func DeleteProjectRuleTemplate(c echo.Context) error { - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectManager(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } templateName := c.Param("rule_template_name") - template, exist, err := s.GetGlobalAndProjectRuleTemplateByNameAndProjectId(templateName, project.ID) + template, exist, err := s.GetGlobalAndProjectRuleTemplateByNameAndProjectId(templateName, projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1081,7 +983,7 @@ func DeleteProjectRuleTemplate(c echo.Context) error { // check audit plans { - auditPlanNames, err := s.GetAuditPlanNamesByRuleTemplateAndProject(templateName, project.ID) + auditPlanNames, err := s.GetAuditPlanNamesByRuleTemplateAndProject(templateName, projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1095,7 +997,7 @@ func DeleteProjectRuleTemplate(c echo.Context) error { // check instance { - instanceNames, err := s.GetInstancesNamesByRuleTemplateAndProject(templateName, project.ID) + instanceNames, err := dms.GetInstancesNameInProjectByRuleTemplateName(c.Request().Context(), projectUid, templateName) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1120,10 +1022,9 @@ type GetProjectRuleTemplatesResV1 struct { } type ProjectRuleTemplateResV1 struct { - Name string `json:"rule_template_name"` - Desc string `json:"desc"` - DBType string `json:"db_type"` - Instances []*ProjectRuleTemplateInstance `json:"instance_list"` + Name string `json:"rule_template_name"` + Desc string `json:"desc"` + DBType string `json:"db_type"` } // GetProjectRuleTemplates @@ -1142,25 +1043,13 @@ func GetProjectRuleTemplates(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - limit, offset := controller.GetLimitAndOffset(req.PageIndex, req.PageSize) - ruleTemplates, count, err := getRuleTemplatesByReq(s, limit, offset, project.ID) + ruleTemplates, count, err := getRuleTemplatesByReq(s, limit, offset, projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1175,24 +1064,23 @@ func GetProjectRuleTemplates(c echo.Context) error { func convertProjectRuleTemplatesToRes(ruleTemplates []*model.RuleTemplateDetail) []ProjectRuleTemplateResV1 { ruleTemplatesRes := make([]ProjectRuleTemplateResV1, len(ruleTemplates)) for i, t := range ruleTemplates { - instances := make([]*ProjectRuleTemplateInstance, len(t.InstanceNames)) - for j, instName := range t.InstanceNames { - instances[j] = &ProjectRuleTemplateInstance{Name: instName} - } + // instances := make([]*ProjectRuleTemplateInstance, len(t.InstanceNames)) + // for j, instName := range t.InstanceNames { + // instances[j] = &ProjectRuleTemplateInstance{Name: instName} + // } ruleTemplatesRes[i] = ProjectRuleTemplateResV1{ - Name: t.Name, - Desc: t.Desc, - DBType: t.DBType, - Instances: instances, + Name: t.Name, + Desc: t.Desc, + DBType: t.DBType, + // Instances: instances, } } return ruleTemplatesRes } type CloneProjectRuleTemplateReqV1 struct { - Name string `json:"new_rule_template_name" valid:"required"` - Desc string `json:"desc"` - Instances []string `json:"instance_name_list"` + Name string `json:"new_rule_template_name" valid:"required"` + Desc string `json:"desc"` } // CloneProjectRuleTemplate @@ -1212,23 +1100,13 @@ func CloneProjectRuleTemplate(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectManager(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - exist, err = s.IsRuleTemplateExistFromAnyProject(req.Name) + exist, err := s.IsRuleTemplateExistFromAnyProject(model.ProjectUID(projectUid), req.Name) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1237,7 +1115,7 @@ func CloneProjectRuleTemplate(c echo.Context) error { } sourceTplName := c.Param("rule_template_name") - sourceTpl, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]uint{project.ID}, sourceTplName) + sourceTpl, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]string{projectUid}, sourceTplName, "") if err != nil { return c.JSON(200, controller.NewBaseReq(err)) } @@ -1246,26 +1124,26 @@ func CloneProjectRuleTemplate(c echo.Context) error { fmt.Errorf("source rule template %s is not exist", sourceTplName)))) } - var instances []*model.Instance - if len(req.Instances) > 0 { - instances, err = s.GetAndCheckInstanceExist(req.Instances, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } + // var instances []*model.Instance + // if len(req.Instances) > 0 { + // instances, err = s.GetAndCheckInstanceExist(req.Instances, projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + // } - err = CheckRuleTemplateCanBeBindEachInstance(s, req.Name, instances) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } + // err = CheckRuleTemplateCanBeBindEachInstance(s, req.Name, instances) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } - err = CheckInstanceAndRuleTemplateDbType([]*model.RuleTemplate{sourceTpl}, instances...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } + // err = CheckInstanceAndRuleTemplateDbType([]*model.RuleTemplate{sourceTpl}, instances...) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } ruleTemplate := &model.RuleTemplate{ - ProjectId: project.ID, + ProjectId: model.ProjectUID(projectUid), Name: req.Name, Desc: req.Desc, DBType: sourceTpl.DBType, @@ -1283,10 +1161,6 @@ func CloneProjectRuleTemplate(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - err = s.UpdateRuleTemplateInstances(ruleTemplate, instances...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) } @@ -1305,24 +1179,12 @@ func GetProjectRuleTemplateTips(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectMember(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - return getRuleTemplateTips(c, project.ID, req.FilterDBType) + return getRuleTemplateTips(c, projectUid, req.FilterDBType) } type ParseProjectRuleTemplateFileResV1 struct { @@ -1395,32 +1257,20 @@ func ExportRuleTemplateFile(c echo.Context) error { // @router /v1/projects/{project_name}/rule_templates/{rule_template_name}/export [get] func ExportProjectRuleTemplateFile(c echo.Context) error { // 权限检查 - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } // 获取模板内容 templateName := c.Param("rule_template_name") - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - - return exportRuleTemplateFile(c, project.ID, templateName) + return exportRuleTemplateFile(c, projectUid, templateName) } -func exportRuleTemplateFile(c echo.Context, projectID uint, ruleTemplateName string) error { +func exportRuleTemplateFile(c echo.Context, projectID string, ruleTemplateName string) error { // 获取规则模板详情 s := model.GetStorage() - template, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]uint{projectID}, ruleTemplateName) + template, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds([]string{projectID}, ruleTemplateName, "") if err != nil { return c.JSON(200, controller.NewBaseReq(err)) } diff --git a/sqle/api/controller/v1/sql_audit.go b/sqle/api/controller/v1/sql_audit.go index f51bc39ec8..de6fceb0c1 100644 --- a/sqle/api/controller/v1/sql_audit.go +++ b/sqle/api/controller/v1/sql_audit.go @@ -2,6 +2,7 @@ package v1 import ( "bytes" + "context" e "errors" "fmt" "net/http" @@ -9,6 +10,7 @@ import ( parser "github.com/actiontech/mybatis-mapper-2-sql" "github.com/actiontech/sqle/sqle/api/controller" + dms "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" @@ -70,11 +72,16 @@ func DirectAudit(c echo.Context) error { } if req.ProjectName != nil { - user := controller.GetUserName(c) - s := model.GetStorage() - if yes, err := s.IsProjectMember(user, *req.ProjectName); err != nil { - return controller.JSONBaseErrorReq(c, fmt.Errorf("check privilege failed: %v", err)) - } else if !yes { + userUid := controller.GetUserID(c) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), *req.ProjectName) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + up, err := dms.NewUserPermission(userUid, projectUid) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + if up.IsProjectMember() { return controller.JSONBaseErrorReq(c, errors.New(errors.ErrAccessDeniedError, e.New("you are not the project member"))) } } @@ -86,14 +93,16 @@ func DirectAudit(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } } - + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), *req.ProjectName) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } l := log.NewEntry().WithField("/v1/sql_audit", "direct audit failed") - s := model.GetStorage() var instance *model.Instance var exist bool if req.ProjectName != nil && req.InstanceName != nil { - instance, exist, err = s.GetInstanceByNameAndProjectName(*req.InstanceName, *req.ProjectName) + instance, exist, err = dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, *req.InstanceName) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -111,7 +120,7 @@ func DirectAudit(c echo.Context) error { if instance != nil && schemaName != "" { task, err = server.DirectAuditByInstance(l, sql, schemaName, instance) } else { - task, err = server.AuditSQLByDBType(l, sql, req.InstanceType, nil, "") + task, err = server.AuditSQLByDBType(l, sql, req.InstanceType) } if err != nil { l.Errorf("audit sqls failed: %v", err) @@ -167,12 +176,16 @@ func DirectAuditFiles(c echo.Context) error { if err != nil { return err } - - user := controller.GetUserName(c) - s := model.GetStorage() - if yes, err := s.IsProjectMember(user, req.ProjectName); err != nil { - return controller.JSONBaseErrorReq(c, fmt.Errorf("check privilege failed: %v", err)) - } else if !yes { + userUid := controller.GetUserID(c) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), req.ProjectName) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + up, err := dms.NewUserPermission(userUid, projectUid) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + if up.IsProjectMember() { return controller.JSONBaseErrorReq(c, errors.New(errors.ErrAccessDeniedError, e.New("you are not the project member"))) } @@ -196,7 +209,7 @@ func DirectAuditFiles(c echo.Context) error { var instance *model.Instance var exist bool if req.InstanceName != nil { - instance, exist, err = s.GetInstanceByNameAndProjectName(*req.InstanceName, req.ProjectName) + instance, exist, err = dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, *req.InstanceName) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -214,7 +227,7 @@ func DirectAuditFiles(c echo.Context) error { if instance != nil && schemaName != "" { task, err = server.DirectAuditByInstance(l, sqls, schemaName, instance) } else { - task, err = server.AuditSQLByDBType(l, sqls, req.InstanceType, nil, "") + task, err = server.AuditSQLByDBType(l, sqls, req.InstanceType) } if err != nil { l.Errorf("audit sqls failed: %v", err) diff --git a/sqle/api/controller/v1/sql_audit_record.go b/sqle/api/controller/v1/sql_audit_record.go index 5ff1e01b9b..929d86b5f4 100644 --- a/sqle/api/controller/v1/sql_audit_record.go +++ b/sqle/api/controller/v1/sql_audit_record.go @@ -20,6 +20,7 @@ import ( xmlAst "github.com/actiontech/mybatis-mapper-2-sql/ast" "github.com/actiontech/sqle/sqle/api/controller" "github.com/actiontech/sqle/sqle/common" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/driver" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" @@ -88,29 +89,17 @@ func CreateSQLAuditRecord(c echo.Context) error { if req.DbType == "" && req.InstanceName == "" { return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, e.New("db_type and instance_name can't both be empty"))) } - projectName := c.Param("project_name") - - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - if project.IsArchived() { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - user, err := controller.GetCurrentUser(c) + s := model.GetStorage() + sqls := getSQLFromFileResp{} + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if err := CheckIsProjectMember(user.Name, project.Name); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - var sqls getSQLFromFileResp if req.Sqls != "" { sqls = getSQLFromFileResp{model.TaskSQLSourceFromFormData, []SQLsFromFile{{SQLs: req.Sqls}}} } else { @@ -122,24 +111,26 @@ func CreateSQLAuditRecord(c echo.Context) error { var task *model.Task if req.InstanceName != "" { - task, err = buildOnlineTaskForAudit(c, s, user.ID, req.InstanceName, req.InstanceSchema, projectName, sqls) + task, err = buildOnlineTaskForAudit(c, s, uint64(user.ID), req.InstanceName, req.InstanceSchema, projectUid, sqls) if err != nil { return controller.JSONBaseErrorReq(c, err) } } else { - task, err = buildOfflineTaskForAudit(user.ID, req.DbType, sqls) + task, err = buildOfflineTaskForAudit(uint64(user.ID), req.DbType, sqls) if err != nil { return controller.JSONBaseErrorReq(c, err) } } + // if task instance is not nil, gorm will update instance when save task. + task.Instance = nil recordId, err := utils.GenUid() if err != nil { return controller.JSONBaseErrorReq(c, fmt.Errorf("generate audit record id failed: %v", err)) } record := model.SQLAuditRecord{ - ProjectId: project.ID, - CreatorId: user.ID, + ProjectId: projectUid, + CreatorId: user.GetIDStr(), AuditRecordId: recordId, TaskId: task.ID, Task: task, @@ -213,7 +204,7 @@ func buildOnlineTaskForAudit(c echo.Context, s *model.Storage, userId uint, inst if !exist { return nil, ErrInstanceNoAccess } - can, err := checkCurrentUserCanAccessInstance(c, instance) + can, err := CheckCurrentUserCanAccessInstances(c.Request().Context(), projectUid, controller.GetUserID(c), []*model.Instance{instance}) if err != nil { return nil, err } @@ -250,7 +241,7 @@ func buildOnlineTaskForAudit(c echo.Context, s *model.Storage, userId uint, inst return task, nil } -func buildOfflineTaskForAudit(userId uint, dbType string, sqls getSQLFromFileResp) (*model.Task, error) { +func buildOfflineTaskForAudit(userId uint64, dbType string, sqls getSQLFromFileResp) (*model.Task, error) { task := &model.Task{ CreateUserId: userId, ExecuteSQLs: []*model.ExecuteSQL{}, @@ -509,36 +500,49 @@ func UpdateSQLAuditRecordV1(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return controller.JSONBaseErrorReq(c, err) } - projectName := c.Param("project_name") - auditRecordId := c.Param("sql_audit_record_id") - - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - user, err := controller.GetCurrentUser(c) + auditRecordId := c.Param("sql_audit_record_id") + + s := model.GetStorage() + + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - record, exist, err := s.GetSQLAuditRecordById(project.ID, auditRecordId) + record, exist, err := s.GetSQLAuditRecordById(projectUid, auditRecordId) if err != nil { return controller.JSONBaseErrorReq(c, err) } if !exist { return controller.JSONBaseErrorReq(c, errors.New(errors.ErrAccessDeniedError, fmt.Errorf("sql audit record id %v not exist", auditRecordId))) } + instance, exist, err := dms.GetInstanceInProjectById(c.Request().Context(), projectUid, record.Task.InstanceId) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if exist { + record.Task.Instance = instance + } if req.Tags != nil { - if yes, err := s.IsSQLAuditRecordBelongToCurrentUser(user.ID, project.ID, auditRecordId); err != nil { - return controller.JSONBaseErrorReq(c, fmt.Errorf("check privilege failed: %v", err)) - } else if !yes { - return controller.JSONBaseErrorReq(c, errors.New(errors.ErrAccessDeniedError, errors.NewAccessDeniedErr("you can't update SQL audit record that created by others"))) + up, err := dms.NewUserPermission(user.GetIDStr(), projectUid) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + if err != nil { + return errors.New(errors.ConnectStorageError, fmt.Errorf("check project manager failed: %v", err)) + } + if !up.IsProjectAdmin() { + if yes, err := s.IsSQLAuditRecordBelongToCurrentUser(user.GetIDStr(), projectUid, auditRecordId); err != nil { + return controller.JSONBaseErrorReq(c, fmt.Errorf("check privilege failed: %v", err)) + } else if !yes { + return controller.JSONBaseErrorReq(c, errors.New(errors.ErrAccessDeniedError, errors.NewAccessDeniedErr("you can't update SQL audit record that created by others"))) + } } data := model.SQLAuditRecordUpdateData{Tags: req.Tags} @@ -560,7 +564,7 @@ func UpdateSQLAuditRecordV1(c echo.Context) error { type GetSQLAuditRecordsReqV1 struct { FuzzySearchTags string `json:"fuzzy_search_tags" query:"fuzzy_search_tags"` // todo issue1811 FilterSQLAuditStatus string `json:"filter_sql_audit_status" query:"filter_sql_audit_status" enums:"auditing,successfully,"` - FilterInstanceName string `json:"filter_instance_name" query:"filter_instance_name"` + FilterInstanceId uint64 `json:"filter_instance_id" query:"filter_instance_id"` FilterCreateTimeFrom string `json:"filter_create_time_from" query:"filter_create_time_from"` FilterCreateTimeTo string `json:"filter_create_time_to" query:"filter_create_time_to"` FilterSqlAuditRecordIDs string `json:"filter_sql_audit_record_ids" query:"filter_sql_audit_record_ids" example:"1711247438821462016,1711246967037759488"` @@ -602,7 +606,7 @@ const ( // @Security ApiKeyAuth // @Param fuzzy_search_tags query string false "fuzzy search tags" // @Param filter_sql_audit_status query string false "filter sql audit status" Enums(auditing,successfully) -// @Param filter_instance_name query string false "filter instance name" +// @Param filter_instance_id query uint64 false "filter instance id" // @Param filter_create_time_from query string false "filter create time from" // @Param filter_create_time_to query string false "filter create time to" // @Param filter_sql_audit_record_ids query string false "filter sql audit record ids" @@ -616,24 +620,22 @@ func GetSQLAuditRecordsV1(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return controller.JSONBaseErrorReq(c, err) } - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), false) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } s := model.GetStorage() - _, exist, err := s.GetProjectByName(projectName) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - - user, err := controller.GetCurrentUser(c) + up, err := dms.NewUserPermission(user.GetIDStr(), projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } - isManager, err := s.IsProjectManager(user.Name, projectName) if err != nil { - return err + return controller.JSONBaseErrorReq(c, fmt.Errorf("check project manager failed: %v", err)) } var offset uint32 @@ -642,13 +644,13 @@ func GetSQLAuditRecordsV1(c echo.Context) error { } data := map[string]interface{}{ - "filter_project_name": projectName, + "filter_project_id": projectUid, "filter_creator_id": user.ID, "fuzzy_search_tags": req.FuzzySearchTags, - "filter_instance_name": req.FilterInstanceName, + "filter_instance_id": req.FilterInstanceId, "filter_create_time_from": req.FilterCreateTimeFrom, "filter_create_time_to": req.FilterCreateTimeTo, - "check_user_can_access": !isManager, + "check_user_can_access": !up.IsProjectAdmin(), "filter_audit_record_ids": req.FilterSqlAuditRecordIDs, "limit": req.PageSize, "offset": offset, @@ -664,6 +666,20 @@ func GetSQLAuditRecordsV1(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } + // batch get instance info + instanceIds := make([]uint64, 0) + for _, record := range records { + instanceIds = append(instanceIds, record.InstanceId) + } + instances, err := dms.GetInstancesByIds(c.Request().Context(), instanceIds) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + idInstMap := make(map[uint64] /*instance id*/ *model.Instance /*instance */, 0) + for _, instance := range instances { + idInstMap[instance.ID] = instance + } + resData := make([]SQLAuditRecord, len(records)) for i := range records { record := records[i] @@ -677,19 +693,15 @@ func GetSQLAuditRecordsV1(c echo.Context) error { log.NewEntry().Errorf("parse tags failed,tags:%v , err: %v", record.Tags, err) } } + resData[i] = SQLAuditRecord{ - Creator: record.CreatorName, + Creator: dms.GetUserNameWithDelTag(record.CreatorId), SQLAuditRecordId: record.AuditRecordId, SQLAuditStatus: status, Tags: tags, CreatedAt: record.RecordCreatedAt, - Instance: &SQLAuditRecordInstance{ - Host: record.InstanceHost.String, - Port: record.InstancePort.String, - }, Task: &AuditTaskResV1{ Id: record.TaskId, - InstanceName: record.InstanceName.String, InstanceDbType: record.DbType, InstanceSchema: record.InstanceSchema, AuditLevel: record.AuditLevel.String, @@ -699,6 +711,13 @@ func GetSQLAuditRecordsV1(c echo.Context) error { SQLSource: record.SQLSource, }, } + if inst, ok := idInstMap[record.InstanceId]; ok { + resData[i].Instance = &SQLAuditRecordInstance{ + Host: inst.Host, + Port: inst.Port, + } + resData[i].Task.InstanceName = idInstMap[record.InstanceId].Name + } } return c.JSON(http.StatusOK, &GetSQLAuditRecordsResV1{ BaseRes: controller.NewBaseReq(nil), @@ -723,54 +742,78 @@ type GetSQLAuditRecordResV1 struct { // @Success 200 {object} v1.GetSQLAuditRecordResV1 // @router /v1/projects/{project_name}/sql_audit_records/{sql_audit_record_id}/ [get] func GetSQLAuditRecordV1(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), false) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } auditRecordId := c.Param("sql_audit_record_id") - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - user, err := controller.GetCurrentUser(c) + up, err := dms.NewUserPermission(user.GetIDStr(), projectUid) if err != nil { - return controller.JSONBaseErrorReq(c, err) + return echo.NewHTTPError(http.StatusForbidden) + } + if err != nil { + return errors.New(errors.ConnectStorageError, fmt.Errorf("check project manager failed: %v", err)) } - if yes, err := s.IsSQLAuditRecordBelongToCurrentUser(user.ID, project.ID, auditRecordId); err != nil { - return controller.JSONBaseErrorReq(c, fmt.Errorf("check privilege failed: %v", err)) - } else if !yes { - return controller.JSONBaseErrorReq(c, errors.New(errors.ErrAccessDeniedError, errors.NewAccessDeniedErr("you can't see the SQL audit record because it isn't created by you"))) + s := model.GetStorage() + + if !up.IsProjectAdmin() { + if yes, err := s.IsSQLAuditRecordBelongToCurrentUser(user.GetIDStr(), projectUid, auditRecordId); err != nil { + return controller.JSONBaseErrorReq(c, fmt.Errorf("check privilege failed: %v", err)) + } else if !yes { + return controller.JSONBaseErrorReq(c, errors.New(errors.ErrAccessDeniedError, errors.NewAccessDeniedErr("you can't see the SQL audit record because it isn't created by you"))) + } } - record, exist, err := s.GetSQLAuditRecordById(project.ID, auditRecordId) + record, exist, err := s.GetSQLAuditRecordById(projectUid, auditRecordId) if err != nil { return controller.JSONBaseErrorReq(c, err) } if !exist { return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, e.New("can not find record"))) } + // build ret info + status := SQLAuditRecordStatusAuditing + if record.Task.Status == model.TaskStatusAudited { + status = SQLAuditRecordStatusSuccessfully + } + var tags []string + if err := json.Unmarshal([]byte(record.Tags), &tags); err != nil { + log.NewEntry().Errorf("parse tags failed,tags:%v , err: %v", record.Tags, err) + } + task := &AuditTaskResV1{ + Id: record.Task.ID, + InstanceDbType: record.Task.DBType, + InstanceSchema: record.Task.Schema, + AuditLevel: record.Task.AuditLevel, + Score: record.Task.Score, + PassRate: record.Task.PassRate, + Status: record.Task.Status, + SQLSource: record.Task.SQLSource, + ExecStartTime: record.Task.ExecStartAt, + ExecEndTime: record.Task.ExecEndAt, + } + instance, exist, err := dms.GetInstancesById(c.Request().Context(), record.Task.InstanceId) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if exist { + task.InstanceName = instance.Name + } return c.JSON(http.StatusOK, &GetSQLAuditRecordResV1{ BaseRes: controller.NewBaseReq(nil), Data: SQLAuditRecord{ + SQLAuditStatus: status, + Tags: tags, SQLAuditRecordId: auditRecordId, - Task: &AuditTaskResV1{ - Id: record.Task.ID, - InstanceName: record.Task.InstanceName(), - InstanceDbType: record.Task.DBType, - InstanceSchema: record.Task.Schema, - AuditLevel: record.Task.AuditLevel, - Score: record.Task.Score, - PassRate: record.Task.PassRate, - Status: record.Task.Status, - SQLSource: record.Task.SQLSource, - ExecStartTime: record.Task.ExecStartAt, - ExecEndTime: record.Task.ExecEndAt, - }, + Task: task, }, }) } diff --git a/sqle/api/controller/v1/sql_manage.go b/sqle/api/controller/v1/sql_manage.go index fab200feca..8347c721b4 100644 --- a/sqle/api/controller/v1/sql_manage.go +++ b/sqle/api/controller/v1/sql_manage.go @@ -96,7 +96,7 @@ func GetSqlManageList(c echo.Context) error { type BatchUpdateSqlManageReq struct { SqlManageIdList []*uint64 `json:"sql_manage_id_list"` Status *string `json:"status" enums:"solved,ignored,manual_audited"` - Assignees []*string `json:"assignees"` + Assignees []string `json:"assignees"` Remark *string `json:"remark"` } diff --git a/sqle/api/controller/v1/sql_whitelist.go b/sqle/api/controller/v1/sql_whitelist.go index 7c224264d4..6f529e26f1 100644 --- a/sqle/api/controller/v1/sql_whitelist.go +++ b/sqle/api/controller/v1/sql_whitelist.go @@ -1,11 +1,13 @@ package v1 import ( + "context" "fmt" "net/http" "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/model" @@ -33,28 +35,14 @@ func CreateAuditWhitelist(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := CheckIsProjectManager(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"),true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - if project.IsArchived() { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } sqlWhitelist := &model.SqlWhitelist{ - ProjectId: project.ID, + ProjectId: model.ProjectUID(projectUid), Value: req.Value, Desc: req.Desc, MatchType: req.MatchType, @@ -90,24 +78,15 @@ func UpdateAuditWhitelistById(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - err := CheckIsProjectManager(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } whitelistId := c.Param("audit_whitelist_id") - sqlWhitelist, exist, err := s.GetSqlWhitelistByIdAndProjectName(whitelistId, projectName) + sqlWhitelist, exist, err := s.GetSqlWhitelistByIdAndProjectUID(whitelistId, model.ProjectUID(projectUid)) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -151,22 +130,14 @@ func UpdateAuditWhitelistById(c echo.Context) error { func DeleteAuditWhitelistById(c echo.Context) error { s := model.GetStorage() whitelistId := c.Param("audit_whitelist_id") - projectName := c.Param("project_name") - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } + // projectName := c.Param("project_name") - userName := controller.GetUserName(c) - err = CheckIsProjectManager(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - sqlWhitelist, exist, err := s.GetSqlWhitelistByIdAndProjectName(whitelistId, projectName) + sqlWhitelist, exist, err := s.GetSqlWhitelistByIdAndProjectUID(whitelistId, model.ProjectUID(projectUid)) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -214,15 +185,13 @@ func GetSqlWhitelist(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - err := CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - sqlWhitelist, count, err := s.GetSqlWhitelistByProjectName(req.PageIndex, req.PageSize, projectName) + sqlWhitelist, count, err := s.GetSqlWhitelistByProjectUID(req.PageIndex, req.PageSize, model.ProjectUID(projectUid)) if err != nil { return controller.JSONBaseErrorReq(c, err) } diff --git a/sqle/api/controller/v1/statistic.go b/sqle/api/controller/v1/statistic.go index 4b56b584cc..1eb734f4b0 100644 --- a/sqle/api/controller/v1/statistic.go +++ b/sqle/api/controller/v1/statistic.go @@ -1,9 +1,11 @@ package v1 import ( + "context" "net/http" "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/model" "github.com/actiontech/sqle/sqle/server/auditplan" @@ -348,7 +350,21 @@ type GetLicenseUsageResV1 struct { // @Success 200 {object} v1.GetLicenseUsageResV1 // @router /v1/statistic/license/usage [get] func GetLicenseUsageV1(c echo.Context) error { - return getLicenseUsageV1(c) + // dms-todo: 移除 license + return c.JSON(http.StatusOK, &GetLicenseUsageResV1{ + BaseRes: controller.NewBaseReq(nil), + Data: &LicenseUsageV1{ + UsersUsage: LicenseUsageItem{ + ResourceType: "user", + ResourceTypeDesc: "用户", + Used: 0, + Limit: 0, + IsLimited: false, + }, + InstancesUsage: []LicenseUsageItem{}, + }, + }) + // return getLicenseUsageV1(c) } type GetSqlExecutionFailPercentReqV1 struct { @@ -402,44 +418,45 @@ type GetProjectStatisticsResDataV1 struct { // @Success 200 {object} v1.GetProjectStatisticsResV1 // @router /v1/projects/{project_name}/statistics [get] func GetProjectStatisticsV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } + // TODO 暂时不处理,解决页面报错 + // projectName := c.Param("project_name") + // err := CheckIsProjectMember(controller.GetUserName(c), projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } resp := GetProjectStatisticsResDataV1{} - s := model.GetStorage() - - resp.MemberTotal, err = s.GetUserTotalInProjectByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - resp.WhitelistTotal, err = s.GetSqlWhitelistTotalByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - resp.RuleTemplateTotal, err = s.GetRuleTemplateTotalByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - resp.InstanceTotal, err = s.GetInstanceTotalByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - resp.AuditPlanTotal, err = s.GetAuditPlanTotalByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - resp.WorkflowTotal, err = s.GetWorkflowTotalByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } + // s := model.GetStorage() + + // resp.MemberTotal, err = s.GetUserTotalInProjectByProjectName(projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + + // resp.WhitelistTotal, err = s.GetSqlWhitelistTotalByProjectName(projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + + // resp.RuleTemplateTotal, err = s.GetRuleTemplateTotalByProjectName(projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + + // resp.InstanceTotal, err = s.GetInstanceTotalByProjectName(projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + + // resp.AuditPlanTotal, err = s.GetAuditPlanTotalByProjectName(projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + + // resp.WorkflowTotal, err = s.GetWorkflowTotalByProjectName(projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } return c.JSON(http.StatusOK, GetProjectStatisticsResV1{ BaseRes: controller.NewBaseReq(nil), @@ -468,18 +485,16 @@ type StatisticsAuditedSQLResV1 struct { // @Success 200 {object} v1.StatisticsAuditedSQLResV1 // @router /v1/projects/{project_name}/statistic/audited_sqls [get] func StatisticsAuditedSQLV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() - workflowSqlCount, err := s.GetSqlCountAndTriggerRuleCountFromWorkflowByProject(projectName) + workflowSqlCount, err := s.GetSqlCountAndTriggerRuleCountFromWorkflowByProject(projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } - auditPlanSqlCount, err := s.GetAuditPlanSQLCountAndTriggerRuleCountByProject(projectName) + auditPlanSqlCount, err := s.GetAuditPlanSQLCountAndTriggerRuleCountByProject(projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -506,12 +521,12 @@ type dbErr struct { err error } -func (d *dbErr) getWorkFlowStatusCountByProject(status string, projectName string) (count int) { +func (d *dbErr) getWorkFlowStatusCountByProject(status string, projectUid string) (count int) { if d.err != nil { return 0 } - count, d.err = d.s.GetWorkflowCountByStatusAndProject(status, projectName) + count, d.err = d.s.GetWorkflowCountByStatusAndProject(status, projectUid) return count } @@ -526,20 +541,19 @@ func (d *dbErr) getWorkFlowStatusCountByProject(status string, projectName strin // @Success 200 {object} v1.GetWorkflowStatusCountResV1 // @router /v1/projects/{project_name}/statistic/workflow_status [get] func StatisticWorkflowStatusV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } d := &dbErr{s: model.GetStorage()} - waitingForAuditCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusWaitForAudit, projectName) - waitingForExecutionCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusWaitForExecution, projectName) - executingCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusExecuting, projectName) - executionSuccessCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusFinish, projectName) - executingFailedCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusExecFailed, projectName) - rejectedCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusReject, projectName) - closedCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusCancel, projectName) + waitingForAuditCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusWaitForAudit, projectUid) + waitingForExecutionCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusWaitForExecution, projectUid) + executingCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusExecuting, projectUid) + executionSuccessCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusFinish, projectUid) + executingFailedCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusExecFailed, projectUid) + rejectedCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusReject, projectUid) + closedCount := d.getWorkFlowStatusCountByProject(model.WorkflowStatusCancel, projectUid) return c.JSON(http.StatusOK, &GetWorkflowStatusCountResV1{ BaseRes: controller.NewBaseReq(nil), @@ -578,25 +592,33 @@ type StatisticRiskWorkflowResV1 struct { // @Success 200 {object} v1.StatisticRiskWorkflowResV1 // @router /v1/projects/{project_name}/statistic/risk_workflow [get] func StatisticRiskWorkflowV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() - projectWorkflowStatusDetails, err := s.GetProjectWorkflowStatusDetail(projectName, []string{model.WorkflowStatusReject, model.WorkflowStatusExecFailed}) + projectWorkflowStatusDetails, err := s.GetProjectWorkflowStatusDetail(projectUid, []string{model.WorkflowStatusReject, model.WorkflowStatusExecFailed}) if err != nil { return controller.JSONBaseErrorReq(c, err) } riskWorkflows := make([]*RiskWorkflow, len(projectWorkflowStatusDetails)) for i, info := range projectWorkflowStatusDetails { + user, err := func() (*model.User, error) { + ctx, cancel := context.WithTimeout(c.Request().Context(), 5*time.Second) + defer cancel() + + return dms.GetUser(ctx, info.CreateUserId, controller.GetDMSServerAddress()) + }() + + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } riskWorkflows[i] = &RiskWorkflow{ Name: info.Subject, WorkflowID: info.WorkflowId, Status: info.Status, - CreateUser: info.LoginName, + CreateUser: user.Name, UpdateTime: info.UpdatedAt, } } @@ -633,14 +655,13 @@ type StatisticAuditPlanResV1 struct { // @Success 200 {object} v1.StatisticAuditPlanResV1 // @router /v1/projects/{project_name}/statistic/audit_plans [get] func StatisticAuditPlanV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - dBTypeAuditPlanCounts, err := s.GetDBTypeAuditPlanCountByProject(projectName) + dBTypeAuditPlanCounts, err := s.GetDBTypeAuditPlanCountByProject(projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -700,14 +721,13 @@ type GetRiskAuditPlanResV1 struct { // @Success 200 {object} v1.GetRiskAuditPlanResV1 // @router /v1/projects/{project_name}/statistic/risk_audit_plans [get] func GetRiskAuditPlanV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - riskAuditPlanInfos, err := s.GetRiskAuditPlan(projectName) + riskAuditPlanInfos, err := s.GetRiskAuditPlan(projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -749,51 +769,47 @@ type GetRoleUserCountResV1 struct { // @Success 200 {object} v1.GetRoleUserCountResV1 // @router /v1/projects/{project_name}/statistic/role_user [get] func GetRoleUserCountV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - userRoles, err := s.GetUserRoleByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - userRoleFromUserGroup, err := s.GetUserRoleFromUserGroupByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - // 若成员和成员组重复绑定相同角色,需要去重 - userRoleMap := make(map[string]map[string]struct{}) // key 1: role_name, key 2: username - for i := range userRoles { - userRole := userRoles[i] - subMap, exist := userRoleMap[userRole.RoleName] - if !exist { - subMap = make(map[string]struct{}) - userRoleMap[userRole.RoleName] = subMap - } - subMap[userRole.UserName] = struct{}{} - } - for i := range userRoleFromUserGroup { - userRole := userRoleFromUserGroup[i] - subMap, exist := userRoleMap[userRole.RoleName] - if !exist { - subMap = make(map[string]struct{}) - userRoleMap[userRole.RoleName] = subMap - } - subMap[userRole.UserName] = struct{}{} - } - - roleUserCountSlice := []*RoleUserCount{} - for k, v := range userRoleMap { - roleUserCountSlice = append(roleUserCountSlice, &RoleUserCount{Role: k, Count: uint(len(v))}) - } + // projectName := c.Param("project_name") + + // s := model.GetStorage() + // userRoles, err := s.GetUserRoleByProjectName(projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + // userRoleFromUserGroup, err := s.GetUserRoleFromUserGroupByProjectName(projectName) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + + // // 若成员和成员组重复绑定相同角色,需要去重 + // userRoleMap := make(map[string]map[string]struct{}) // key 1: role_name, key 2: username + // for i := range userRoles { + // userRole := userRoles[i] + // subMap, exist := userRoleMap[userRole.RoleName] + // if !exist { + // subMap = make(map[string]struct{}) + // userRoleMap[userRole.RoleName] = subMap + // } + // subMap[userRole.UserName] = struct{}{} + // } + // for i := range userRoleFromUserGroup { + // userRole := userRoleFromUserGroup[i] + // subMap, exist := userRoleMap[userRole.RoleName] + // if !exist { + // subMap = make(map[string]struct{}) + // userRoleMap[userRole.RoleName] = subMap + // } + // subMap[userRole.UserName] = struct{}{} + // } + + // roleUserCountSlice := []*RoleUserCount{} + // for k, v := range userRoleMap { + // roleUserCountSlice = append(roleUserCountSlice, &RoleUserCount{Role: k, Count: uint(len(v))}) + // } return c.JSON(http.StatusOK, GetRoleUserCountResV1{ BaseRes: controller.NewBaseReq(nil), - Data: roleUserCountSlice, + Data: nil, }) } @@ -816,19 +832,17 @@ type GetProjectScoreResV1 struct { // @Success 200 {object} v1.GetProjectScoreResV1 // @router /v1/projects/{project_name}/statistic/project_score [get] func GetProjectScoreV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() execFailedStatus := []string{model.WorkflowStatusExecFailed, model.WorkflowStatusFinish, model.WorkflowStatusExecuting} - workflowsStatuses, err := s.GetProjectWorkflowStatusDetail(projectName, execFailedStatus) + workflowsStatuses, err := s.GetProjectWorkflowStatusDetail(projectUid, execFailedStatus) if err != nil { return controller.JSONBaseErrorReq(c, err) } - auditReports, err := s.GetAuditPlanReportByProjectName(projectName) + auditReports, err := s.GetAuditPlanReportByProjectName(projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -946,18 +960,26 @@ func generateMaps(instanceWorkFlowFailedStatus []*model.InstanceWorkFlowStatusCo // @Success 200 {object} v1.GetInstanceHealthResV1 // @router /v1/projects/{project_name}/statistic/instance_health [get] func GetInstanceHealthV1(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - instanceWorkFlowFailedStatus, err := s.GetInstanceWorkFlowStatusCountByProject(projectName, []string{model.WorkflowStatusReject, model.WorkflowStatusExecFailed}) + instances, err := dms.GetInstancesInProject(c.Request().Context(), projectUid) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + instanceWorkFlowFailedStatus, err := s.GetInstanceWorkFlowStatusCountByProject(instances, []string{model.WorkflowStatusReject, model.WorkflowStatusExecFailed}) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + + instanceNames, err := dms.GetInstanceNamesInProject(c.Request().Context(), projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } - latestAuditPlanReportScores, err := s.GetLatestAuditPlanReportScoreFromInstanceByProject(projectName) + latestAuditPlanReportScores, err := s.GetLatestAuditPlanReportScoreFromInstanceByProject(projectUid, instanceNames) if err != nil { return controller.JSONBaseErrorReq(c, err) } diff --git a/sqle/api/controller/v1/statistic_ce.go b/sqle/api/controller/v1/statistic_ce.go index 736a85784c..37e082287c 100644 --- a/sqle/api/controller/v1/statistic_ce.go +++ b/sqle/api/controller/v1/statistic_ce.go @@ -17,10 +17,6 @@ func getInstancesTypePercentV1(c echo.Context) error { return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportStatistic) } -func getLicenseUsageV1(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportStatistic) -} - func getWorkflowRejectedPercentGroupByCreatorV1(c echo.Context) error { return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportStatistic) } diff --git a/sqle/api/controller/v1/sync_instance.go b/sqle/api/controller/v1/sync_instance.go deleted file mode 100644 index 7f3f7c2e07..0000000000 --- a/sqle/api/controller/v1/sync_instance.go +++ /dev/null @@ -1,165 +0,0 @@ -package v1 - -import ( - "time" - - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/labstack/echo/v4" -) - -type CreateSyncInstanceTaskReqV1 struct { - Source string `json:"source" form:"source" validate:"required" example:"actiontech-dmp"` - Version string `json:"version" form:"version" validate:"required" example:"5.23.01.0"` - URL string `json:"url" form:"url" validate:"required" example:"http://10.186.62.56:10000"` - DbType string `json:"db_type" form:"db_type" validate:"required" example:"mysql"` - GlobalRuleTemplate string `json:"global_rule_template" form:"global_rule_template" validate:"required" example:"default_mysql"` - SyncInstanceInterval string `json:"sync_instance_interval" form:"sync_instance_interval" validate:"required" example:"0 0 * * *"` -} - -// CreateSyncInstanceTask create sync instance task -// @Summary 创建同步实例任务 -// @Description create sync instance task -// @Id createSyncInstanceTaskV1 -// @Tags sync_instance -// @Security ApiKeyAuth -// @Accept json -// @Param sync_task body v1.CreateSyncInstanceTaskReqV1 true "create sync instance task request" -// @Success 200 {object} controller.BaseRes -// @router /v1/sync_instances [post] -func CreateSyncInstanceTask(c echo.Context) error { - return createSyncInstanceTask(c) -} - -type UpdateSyncInstanceTaskReqV1 struct { - Version *string `json:"version" form:"version" example:"5.23.01.0"` - URL *string `json:"url" form:"url" example:"http://10.186.62.56:10000"` - GlobalRuleTemplate *string `json:"global_rule_template" form:"global_rule_template" example:"default_mysql"` - SyncInstanceInterval *string `json:"sync_instance_interval" form:"sync_instance_interval" example:"0 0 * * *"` -} - -// UpdateSyncInstanceTask update sync instance task -// @Summary 更新同步实例任务 -// @Description update sync instance task -// @Id updateSyncInstanceTaskV1 -// @Tags sync_instance -// @Security ApiKeyAuth -// @Param task_id path string true "sync task id" -// @param sync_task body v1.UpdateSyncInstanceTaskReqV1 true "update sync instance request" -// @Success 200 {object} controller.BaseRes -// @router /v1/sync_instances/{task_id}/ [patch] -func UpdateSyncInstanceTask(c echo.Context) error { - return updateSyncInstanceTask(c) -} - -// DeleteSyncInstanceTask delete sync instance task -// @Summary 删除同步实例任务 -// @Description delete sync instance task -// @Id deleteSyncInstanceTaskV1 -// @Tags sync_instance -// @Security ApiKeyAuth -// @param task_id path string true "sync task id" -// @Success 200 {object} controller.BaseRes -// @router /v1/sync_instances/{task_id}/ [delete] -func DeleteSyncInstanceTask(c echo.Context) error { - return deleteSyncInstanceTask(c) -} - -type SyncInstanceResV1 struct { - IsSyncInstanceSuccess bool `json:"is_sync_instance_success" example:"true"` - SyncErrorMessage string `json:"sync_error_message"` -} - -type TriggerSyncInstanceResV1 struct { - controller.BaseRes - Data SyncInstanceResV1 `json:"data"` -} - -// TriggerSyncInstance trigger sync instance -// @Summary 触发同步实例 -// @Description trigger sync instance -// @Id triggerSyncInstanceV1 -// @Tags sync_instance -// @Security ApiKeyAuth -// @param task_id path string true "sync task id" -// @Success 200 {object} v1.TriggerSyncInstanceResV1 -// @router /v1/sync_instances/{task_id}/trigger [post] -func TriggerSyncInstance(c echo.Context) error { - return triggerSyncInstance(c) -} - -type GetSyncInstanceTaskListResV1 struct { - controller.BaseRes - Data []InstanceTaskResV1 `json:"data"` -} - -type InstanceTaskResV1 struct { - ID int `json:"id" example:"1"` - Source string `json:"source" example:"actiontech-dmp"` - Version string `json:"version" example:"1.23.1"` - URL string `json:"url" example:"http://10.186.62.56:10000"` - DbType string `json:"db_type" example:"mysql"` - LastSyncStatus string `json:"last_sync_status" enums:"succeeded,failed" example:"succeeded"` - LastSyncSuccessTime *time.Time `json:"last_sync_success_time" example:"2021-08-12 12:00:00"` -} - -// GetSyncInstanceTaskList get sync instance task list -// @Summary 获取同步实例任务列表 -// @Description get sync instance task list -// @Id GetSyncInstanceTaskList -// @Tags sync_instance -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetSyncInstanceTaskListResV1 -// @router /v1/sync_instances [get] -func GetSyncInstanceTaskList(c echo.Context) error { - return getSyncInstanceTaskList(c) -} - -type SyncTaskTipsResV1 struct { - Source string `json:"source" example:"actiontech-dmp"` - DbTypes []string `json:"db_types"` -} - -type GetSyncTaskSourceTipsResV1 struct { - controller.BaseRes - Data []SyncTaskTipsResV1 `json:"data"` -} - -// GetSyncTaskSourceTips get sync instance tips -// @Summary 获取同步任务提示 -// @Description get sync task tips -// @Id GetSyncTaskSourceTips -// @Tags sync_instance -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetSyncTaskSourceTipsResV1 -// @router /v1/sync_instances/source_tips [get] -func GetSyncTaskSourceTips(c echo.Context) error { - return getSyncTaskSourceTips(c) -} - -type InstanceTaskDetailResV1 struct { - ID int `json:"id" example:"1"` - Source string `json:"source" example:"actiontech-dmp"` - Version string `json:"version" example:"1.23.1"` - URL string `json:"url" example:"http://10.186.62.56:10000"` - DbType string `json:"db_type" example:"mysql"` - RuleTemplate string `json:"rule_template" example:"default_mysql"` - SyncInstanceInterval string `json:"sync_instance_interval" example:"0 0 * * *"` -} - -type GetSyncInstanceTaskResV1 struct { - controller.BaseRes - Data InstanceTaskDetailResV1 `json:"data"` -} - -// GetSyncInstanceTask get sync task detail -// @Summary 获取同步任务详情 -// @Description get sync task detail -// @Id GetSyncInstanceTask -// @Tags sync_instance -// @Security ApiKeyAuth -// @param task_id path string true "sync task id" -// @Success 200 {object} v1.GetSyncInstanceTaskResV1 -// @router /v1/sync_instances/{task_id}/ [get] -func GetSyncInstanceTask(c echo.Context) error { - return getSyncInstanceTask(c) -} diff --git a/sqle/api/controller/v1/sync_instance_ce.go b/sqle/api/controller/v1/sync_instance_ce.go deleted file mode 100644 index 2a38ba7b7c..0000000000 --- a/sqle/api/controller/v1/sync_instance_ce.go +++ /dev/null @@ -1,41 +0,0 @@ -//go:build !enterprise -// +build !enterprise - -package v1 - -import ( - e "errors" - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/errors" - "github.com/labstack/echo/v4" -) - -var errCommunityEditionDoesNotSupportSyncInstance = errors.New(errors.EnterpriseEditionFeatures, e.New("community edition does not support sync instance")) - -func createSyncInstanceTask(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportSyncInstance) -} - -func updateSyncInstanceTask(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportSyncInstance) -} - -func deleteSyncInstanceTask(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportSyncInstance) -} - -func triggerSyncInstance(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportSyncInstance) -} - -func getSyncInstanceTaskList(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportSyncInstance) -} - -func getSyncTaskSourceTips(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportSyncInstance) -} - -func getSyncInstanceTask(c echo.Context) error { - return controller.JSONBaseErrorReq(c, errCommunityEditionDoesNotSupportSyncInstance) -} diff --git a/sqle/api/controller/v1/task.go b/sqle/api/controller/v1/task.go index ff3eeace26..124e78ace2 100644 --- a/sqle/api/controller/v1/task.go +++ b/sqle/api/controller/v1/task.go @@ -10,9 +10,11 @@ import ( "strconv" "time" + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" mybatis_parser "github.com/actiontech/mybatis-mapper-2-sql" "github.com/actiontech/sqle/sqle/api/controller" "github.com/actiontech/sqle/sqle/common" + "github.com/actiontech/sqle/sqle/dms" driverV2 "github.com/actiontech/sqle/sqle/driver/v2" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" @@ -174,19 +176,19 @@ func CreateAndAuditTask(c echo.Context) error { } } - projectName := c.Param("project_name") - - user, err := controller.GetCurrentUser(c) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - err = CheckIsProjectMember(user.Name, projectName) + s := model.GetStorage() + + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() - task, err := buildOnlineTaskForAudit(c, s, user.ID, req.InstanceName, req.InstanceSchema, projectName, sqls) + + task, err := buildOnlineTaskForAudit(c, s, uint64(user.ID), req.InstanceName, req.InstanceSchema, projectUid, sqls) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -220,15 +222,12 @@ func CreateAndAuditTask(c echo.Context) error { // @Success 200 {object} v1.GetAuditTaskResV1 // @router /v1/tasks/audits/{task_id}/ [get] func GetTask(c echo.Context) error { - s := model.GetStorage() taskId := c.Param("task_id") - task, exist, err := s.GetTaskById(taskId) + task, err := getTaskById(c.Request().Context(), taskId) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) - } + err = CheckCurrentUserCanViewTask(c, task) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -239,6 +238,28 @@ func GetTask(c echo.Context) error { Data: convertTaskToRes(task), }) } +func GetTaskById(ctx context.Context, taskId string) (*model.Task, error) { + return getTaskById(ctx, taskId) +} + +func getTaskById(ctx context.Context, taskId string) (*model.Task, error) { + s := model.GetStorage() + task, exist, err := s.GetTaskById(taskId) + if err != nil { + return nil, err + } + if !exist { + return nil, errors.NewTaskNoExistOrNoAccessErr() + } + + instance, exist, err := dms.GetInstancesById(ctx, task.InstanceId) + if err != nil { + return nil, err + } + task.Instance = instance + + return task, nil +} type GetAuditTaskSQLsReqV1 struct { FilterExecStatus string `json:"filter_exec_status" query:"filter_exec_status"` @@ -288,14 +309,12 @@ func GetTaskSQLs(c echo.Context) error { } s := model.GetStorage() taskId := c.Param("task_id") - task, exist, err := s.GetTaskById(taskId) + task, err := getTaskById(c.Request().Context(), taskId) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) - } - err = CheckCurrentUserCanViewTask(c, task) + + err = CheckCurrentUserCanViewTaskDMS(c, task) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -362,13 +381,11 @@ func DownloadTaskSQLReportFile(c echo.Context) error { } s := model.GetStorage() taskId := c.Param("task_id") - task, exist, err := s.GetTaskById(taskId) + task, err := getTaskById(c.Request().Context(), taskId) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) - } + err = CheckCurrentUserCanViewTask(c, task) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -428,13 +445,11 @@ func DownloadTaskSQLReportFile(c echo.Context) error { func DownloadTaskSQLFile(c echo.Context) error { taskId := c.Param("task_id") s := model.GetStorage() - task, exist, err := s.GetTaskById(taskId) + task, err := getTaskById(c.Request().Context(), taskId) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) - } + err = CheckCurrentUserCanViewTask(c, task) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -471,13 +486,12 @@ type AuditTaskSQLContentResV1 struct { func GetAuditTaskSQLContent(c echo.Context) error { taskId := c.Param("task_id") s := model.GetStorage() - task, exist, err := s.GetTaskById(taskId) + + task, err := getTaskById(c.Request().Context(), taskId) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) - } + err = CheckCurrentUserCanViewTask(c, task) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -519,13 +533,11 @@ func UpdateAuditTaskSQLs(c echo.Context) error { number := c.Param("number") s := model.GetStorage() - task, exist, err := s.GetTaskById(taskId) + task, err := getTaskById(c.Request().Context(), taskId) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) - } + err = CheckCurrentUserCanViewTask(c, task) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -544,7 +556,16 @@ func UpdateAuditTaskSQLs(c echo.Context) error { } func CheckCurrentUserCanViewTask(c echo.Context, task *model.Task) (err error) { - return checkCurrentUserCanAccessTask(c, task, []uint{model.OP_WORKFLOW_VIEW_OTHERS}) + return checkCurrentUserCanAccessTask(c, task, []dmsV1.OpPermissionType{dmsV1.OpPermissionTypeViewOthersWorkflow}) +} + +// TODO 使用DMS的权限校验 +func CheckCurrentUserCanViewTaskDMS(c echo.Context, task *model.Task) error { + _, err := controller.GetCurrentUser(c, dms.GetUser) + if err != nil { + return err + } + return nil } type SQLExplain struct { @@ -620,26 +641,38 @@ func CreateAuditTasksGroupV1(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } // 数据源个数最大为10 if len(req.Instances) > MaximumDataSourceNum { return controller.JSONBaseErrorReq(c, ErrTooManyDataSource) } - projectName := c.Param("project_name") - userName := controller.GetUserName(c) + instNames := make([]string, len(req.Instances)) + for i, instance := range req.Instances { + instNames[i] = instance.InstanceName + } + + distinctInstNames := utils.RemoveDuplicate(instNames) - err := CheckIsProjectMember(userName, projectName) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } s := model.GetStorage() - distinctInstNameList := getDistinctInstNameList(req.Instances) + + instances, err := dms.GetInstancesInProjectByNames(c.Request().Context(), projectUid, distinctInstNames) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + nameInstanceMap := make(map[string]*model.Instance, len(req.Instances)) - for _, instName := range distinctInstNameList { + for _, inst := range instances { // https://github.com/actiontech/sqle/issues/1673 - inst, exist, err := s.GetInstanceByNameAndProjectName(instName, projectName) + inst, exist, err := dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, inst.Name) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -647,7 +680,7 @@ func CreateAuditTasksGroupV1(c echo.Context) error { return controller.JSONBaseErrorReq(c, ErrInstanceNoAccess) } - can, err := checkCurrentUserCanAccessInstance(c, inst) + can, err := CheckCurrentUserCanAccessInstances(c.Request().Context(), projectUid, user.GetIDStr(), instances) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -659,12 +692,7 @@ func CreateAuditTasksGroupV1(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - nameInstanceMap[instName] = inst - } - - user, err := controller.GetCurrentUser(c) - if err != nil { - return controller.JSONBaseErrorReq(c, err) + nameInstanceMap[inst.Name] = inst } tasks := make([]*model.Task, len(req.Instances)) @@ -672,7 +700,7 @@ func CreateAuditTasksGroupV1(c echo.Context) error { tasks[i] = &model.Task{ Schema: reqInstance.InstanceSchema, InstanceId: nameInstanceMap[reqInstance.InstanceName].ID, - CreateUserId: user.ID, + CreateUserId: uint64(user.ID), DBType: nameInstanceMap[reqInstance.InstanceName].DbType, } tasks[i].CreatedAt = time.Now() @@ -691,15 +719,6 @@ func CreateAuditTasksGroupV1(c echo.Context) error { }) } -func getDistinctInstNameList(instList []*InstanceForCreatingTask) []string { - instNames := make([]string, len(instList)) - for i, inst := range instList { - instNames[i] = inst.InstanceName - } - - return utils.RemoveDuplicate(instNames) -} - type AuditTaskGroupReqV1 struct { TaskGroupId uint `json:"task_group_id" form:"task_group_id" valid:"required"` Sql string `json:"sql" form:"sql" example:"alter table tb1 drop columns c1"` @@ -768,12 +787,19 @@ func AuditTaskGroupV1(c echo.Context) error { tasks := taskGroup.Tasks { - instances := make([]*model.Instance, 0) + instanceIds := make([]uint64, 0, len(tasks)) for _, task := range tasks { - instances = append(instances, task.Instance) + instanceIds = append(instanceIds, task.InstanceId) + } + + instances, err := dms.GetInstancesByIds(c.Request().Context(), instanceIds) + if err != nil { + return controller.JSONBaseErrorReq(c, err) } - can, err := checkCurrentUserCanAccessInstances(c, instances) + // 因为这个接口数据源属于同一个项目,取第一个DB所属项目 + projectId := instances[0].ProjectId + can, err := CheckCurrentUserCanAccessInstances(c.Request().Context(), projectId, controller.GetUserID(c), instances) if err != nil { return controller.JSONBaseErrorReq(c, err) } diff --git a/sqle/api/controller/v1/user.go b/sqle/api/controller/v1/user.go index fbd7f34bdc..78690b478d 100644 --- a/sqle/api/controller/v1/user.go +++ b/sqle/api/controller/v1/user.go @@ -1,564 +1,21 @@ package v1 import ( - _errors "errors" - "fmt" "net/http" "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/utils" + "github.com/actiontech/sqle/sqle/dms" "github.com/labstack/echo/v4" ) -type CreateUserReqV1 struct { - Name string `json:"user_name" form:"user_name" example:"test" valid:"required,name"` - Password string `json:"user_password" form:"user_name" example:"123456" valid:"required"` - Email string `json:"email" form:"email" example:"test@email.com" valid:"omitempty,email"` - Phone string `json:"phone" form:"phone" example:"18962136666" valid:"omitempty"` - WeChatID string `json:"wechat_id" example:"UserID"` - UserGroups []string `json:"user_group_name_list" form:"user_group_name_list"` - ManagementPermissionCodes []uint `json:"management_permission_code_list" form:"management_permission_code_list"` -} - -// @Summary 创建用户 -// @Description create user -// @Id createUserV1 -// @Tags user -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param instance body v1.CreateUserReqV1 true "create user" -// @Success 200 {object} controller.BaseRes -// @router /v1/users [post] -func CreateUser(c echo.Context) error { - req := new(CreateUserReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - s := model.GetStorage() - _, exist, err := s.GetUserByName(req.Name) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataExist, fmt.Errorf("user is exist"))) - } - - var userGroups []*model.UserGroup - { - if req.UserGroups != nil || len(req.UserGroups) > 0 { - userGroups, err = s.GetAndCheckUserGroupExist(req.UserGroups) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - } - - user := &model.User{ - Name: req.Name, - Password: req.Password, - Email: req.Email, - Phone: req.Phone, - WeChatID: req.WeChatID, - } - - return controller.JSONBaseErrorReq(c, - s.SaveUserAndAssociations(user, userGroups, &req.ManagementPermissionCodes)) -} - -type UpdateUserReqV1 struct { - Email *string `json:"email" valid:"omitempty,len=0|email" form:"email"` - Phone *string `json:"phone" valid:"omitempty" form:"phone"` - WeChatID *string `json:"wechat_id" example:"UserID"` - IsDisabled *bool `json:"is_disabled,omitempty" form:"is_disabled"` - UserGroups *[]string `json:"user_group_name_list" form:"user_group_name_list"` - ManagementPermissionCodes *[]uint `json:"management_permission_code_list,omitempty" form:"management_permission_code_list"` -} - -// @Summary 更新用户信息 -// @Description update user -// @Id updateUserV1 -// @Tags user -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param user_name path string true "user name" -// @Param instance body v1.UpdateUserReqV1 true "update user" -// @Success 200 {object} controller.BaseRes -// @router /v1/users/{user_name}/ [patch] -func UpdateUser(c echo.Context) error { - req := new(UpdateUserReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - userName := c.Param("user_name") - s := model.GetStorage() - user, exist, err := s.GetUserByName(userName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("user is not exist"))) - } - - // Email - if req.Email != nil { - user.Email = *req.Email - } - - // Phone - if req.Phone != nil { - user.Phone = *req.Phone - } - - // WeChatID - if req.WeChatID != nil { - user.WeChatID = *req.WeChatID - } - - // IsDisabled - if req.IsDisabled != nil { - if err := controller.CanThisUserBeDisabled( - controller.GetUserName(c), userName); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if *req.IsDisabled { - user.SetStat(model.Disabled) - } else { - user.SetStat(model.Enabled) - } - } - - // user_groups - var userGroups []*model.UserGroup - { - if req.UserGroups != nil { - if len(*req.UserGroups) > 0 { - userGroups, err = s.GetAndCheckUserGroupExist(*req.UserGroups) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } else { - userGroups = make([]*model.UserGroup, 0) - } - } - - } - - return controller.JSONBaseErrorReq(c, s.SaveUserAndAssociations(user, userGroups, req.ManagementPermissionCodes)) -} - -// @Summary 删除用户 -// @Description delete user -// @Id deleteUserV1 -// @Tags user -// @Security ApiKeyAuth -// @Param user_name path string true "user name" -// @Success 200 {object} controller.BaseRes -// @router /v1/users/{user_name}/ [delete] -func DeleteUser(c echo.Context) error { - userName := c.Param("user_name") - if userName == model.DefaultAdminUser { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataConflict, - fmt.Errorf("admin user cannot be deleted"))) - } - s := model.GetStorage() - user, exist, err := s.GetUserByName(userName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("user is not exist"))) - } - exist, err = s.UserHasRunningWorkflow(user.ID) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataExist, - fmt.Errorf("%s can't be deleted,cause wait_for_audit or wait_for_execution workflow exist", userName))) - } - hasBind, err := s.UserHasBindWorkflowTemplate(user) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if hasBind { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataExist, - fmt.Errorf("%s can't be deleted,cause the user binds the workflow template", userName))) - } - - isLastMgr, err := s.IsLastProjectManagerOfAnyProjectByUserID(user.ID) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if isLastMgr { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataExist, fmt.Errorf("%s can't be deleted,cause the user is project last manager", userName))) - } - - err = s.RemoveMemberFromAllProjectByUserID(user.ID) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - err = s.Delete(user) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return controller.JSONBaseErrorReq(c, nil) -} - -type UpdateOtherUserPasswordReqV1 struct { - Password string `json:"password" valid:"required"` -} - -// @Summary admin修改其他用户密码 -// @Description admin modifies the passwords of other users -// @Id UpdateOtherUserPasswordV1 -// @Tags user -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param user_name path string true "user name" -// @Param instance body v1.UpdateOtherUserPasswordReqV1 true "change user's password" -// @Success 200 {object} controller.BaseRes -// @router /v1/users/{user_name}/password [patch] -func UpdateOtherUserPassword(c echo.Context) error { - req := new(UpdateOtherUserPasswordReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - userName := c.Param("user_name") - if userName == model.DefaultAdminUser { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataConflict, - fmt.Errorf("admin user's password cannot be changed in this page"))) - } - - s := model.GetStorage() - user, exist, err := s.GetUserByName(userName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("user is not exist"))) - } - if user.UserAuthenticationType == model.UserAuthenticationTypeLDAP { - return controller.JSONBaseErrorReq(c, errLdapUserCanNotChangePassword) - } - err = s.UpdatePassword(user, req.Password) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return controller.JSONBaseErrorReq(c, nil) -} - -type GetUserDetailResV1 struct { - controller.BaseRes - Data UserDetailResV1 `json:"data"` -} - -type UserDetailResV1 struct { - Name string `json:"user_name"` - Email string `json:"email"` - Phone string `json:"phone"` - IsAdmin bool `json:"is_admin"` - WeChatID string `json:"wechat_id"` - LoginType string `json:"login_type"` - IsDisabled bool `json:"is_disabled,omitempty"` - UserGroups []string `json:"user_group_name_list,omitempty"` - ManagementPermissionList []*ManagementPermissionResV1 `json:"management_permission_list,omitempty"` - BindProjects []*UserBindProjectResV1 `json:"bind_projects,omitempty"` -} - -type UserBindProjectResV1 struct { - ProjectName string `json:"project_name"` - IsManager bool `json:"is_manager"` -} - -func convertUserToRes(user *model.User, managementPermissionCodes []uint, projects []*model.Project, projectManagerCache map[uint] /*project id*/ bool /*is manager*/) UserDetailResV1 { - if user.UserAuthenticationType == "" { - user.UserAuthenticationType = model.UserAuthenticationTypeSQLE - } - userResp := UserDetailResV1{ - Name: user.Name, - Phone: user.Phone, - Email: user.Email, - WeChatID: user.WeChatID, - LoginType: string(user.UserAuthenticationType), - IsAdmin: user.Name == model.DefaultAdminUser, - IsDisabled: user.IsDisabled(), - } - - userGroupNames := make([]string, len(user.UserGroups)) - for i := range user.UserGroups { - userGroupNames[i] = user.UserGroups[i].Name - } - userResp.UserGroups = userGroupNames - - bindProjects := []*UserBindProjectResV1{} - for _, project := range projects { - bindProjects = append(bindProjects, &UserBindProjectResV1{ - ProjectName: project.Name, - IsManager: projectManagerCache[project.ID], - }) - } - userResp.BindProjects = bindProjects - - userResp.ManagementPermissionList = generateManagementPermissionResV1s(managementPermissionCodes) - - return userResp -} - -// @Summary 获取用户信息 -// @Description get user info -// @Id getUserV1 -// @Tags user -// @Security ApiKeyAuth -// @Param user_name path string true "user name" -// @Success 200 {object} v1.GetUserDetailResV1 -// @router /v1/users/{user_name}/ [get] -func GetUser(c echo.Context) error { - userName := c.Param("user_name") - return getUserDetail(c, userName) -} - -func getUserDetail(c echo.Context, userName string) error { - s := model.GetStorage() - user, exist, err := s.GetUserDetailByName(userName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("user is not exist"))) - } - - codes, err := s.GetManagementPermissionByUserID(user.ID) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - projects, err := s.GetProjectTips(user.Name) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - managed, err := s.GetManagedProjects(user.ID) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - managerCache := map[uint]bool{} - for _, project := range projects { - isManager := false - for _, p := range managed { - if p.ID == project.ID { - isManager = true - break - } - } - managerCache[project.ID] = isManager - } - - return c.JSON(http.StatusOK, &GetUserDetailResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: convertUserToRes(user, codes, projects, managerCache), - }) -} - -// @Summary 获取当前用户信息 -// @Description get current user info -// @Id getCurrentUserV1 -// @Tags user -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetUserDetailResV1 -// @router /v1/user [get] -func GetCurrentUser(c echo.Context) error { - userName := controller.GetUserName(c) - return getUserDetail(c, userName) -} - -type UpdateCurrentUserReqV1 struct { - Email *string `json:"email"` - WeChatID *string `json:"wechat_id" example:"UserID"` - Phone *string `json:"phone" form:"phone"` -} - -// @Summary 更新个人信息 -// @Description update current user -// @Id updateCurrentUserV1 -// @Tags user -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param instance body v1.UpdateCurrentUserReqV1 true "update user" -// @Success 200 {object} controller.BaseRes -// @router /v1/user [patch] -func UpdateCurrentUser(c echo.Context) error { - req := new(UpdateCurrentUserReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - user, err := controller.GetCurrentUser(c) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - s := model.GetStorage() - if req.Email != nil { - user.Email = *req.Email - } - if req.WeChatID != nil { - user.WeChatID = *req.WeChatID - } - if req.Phone != nil { - user.Phone = *req.Phone - } - err = s.Save(user) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return controller.JSONBaseErrorReq(c, nil) -} - -type UpdateCurrentUserPasswordReqV1 struct { - Password string `json:"password" valid:"required"` - NewPassword string `json:"new_password" valid:"required"` -} - -var errLdapUserCanNotChangePassword = errors.New(errors.DataConflict, _errors.New("the password of the ldap user cannot be changed or reset, because this password is meaningless")) - -// @Summary 用户修改密码 -// @Description update current user's password -// @Id UpdateCurrentUserPasswordV1 -// @Tags user -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param instance body v1.UpdateCurrentUserPasswordReqV1 true "update user's password" -// @Success 200 {object} controller.BaseRes -// @router /v1/user/password [put] -func UpdateCurrentUserPassword(c echo.Context) error { - req := new(UpdateCurrentUserPasswordReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - user, err := controller.GetCurrentUser(c) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if user.UserAuthenticationType == model.UserAuthenticationTypeLDAP { - return controller.JSONBaseErrorReq(c, errLdapUserCanNotChangePassword) - } - if user.Password != req.Password { - return controller.JSONBaseErrorReq(c, - errors.New(errors.LoginAuthFail, fmt.Errorf("password is wrong"))) - } - - s := model.GetStorage() - err = s.UpdatePassword(user, req.NewPassword) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return controller.JSONBaseErrorReq(c, logout(c)) -} - -type GetUsersReqV1 struct { - FilterUserName string `json:"filter_user_name" query:"filter_user_name"` - PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` - PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` -} - -type GetUsersResV1 struct { - controller.BaseRes - Data []UserResV1 `json:"data"` - TotalNums uint64 `json:"total_nums"` -} - -type UserResV1 struct { - Name string `json:"user_name"` - Phone string `json:"phone"` - Email string `json:"email"` - WeChatID string `json:"wechat_id"` - LoginType string `json:"login_type"` - IsDisabled bool `json:"is_disabled,omitempty"` - UserGroups []string `json:"user_group_name_list,omitempty"` - ManagementPermissionList []*ManagementPermissionResV1 `json:"management_permission_list,omitempty"` -} - -// @Summary 获取用户信息列表 -// @Description get user info list -// @Tags user -// @Id getUserListV1 -// @Security ApiKeyAuth -// @Param filter_user_name query string false "filter user name" -// @Param page_index query uint32 true "page index" -// @Param page_size query uint32 true "size of per page" -// @Success 200 {object} v1.GetUsersResV1 -// @router /v1/users [get] -func GetUsers(c echo.Context) error { - req := new(GetUsersReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - - var offset uint32 - if req.PageIndex >= 1 { - offset = req.PageSize * (req.PageIndex - 1) - } - data := map[string]interface{}{ - "filter_user_name": req.FilterUserName, - "limit": req.PageSize, - "offset": offset, - } - - users, count, err := s.GetUsersByReq(data) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - userIDs := []uint{} - for _, user := range users { - userIDs = append(userIDs, uint(user.Id)) - } - permission, err := s.GetManagementPermissionByUserIDs(userIDs) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - usersRes := []UserResV1{} - for _, user := range users { - if user.LoginType == "" { - user.LoginType = string(model.UserAuthenticationTypeSQLE) - } - userReq := UserResV1{ - Name: user.Name, - Email: user.Email, - Phone: user.Phone.String, - WeChatID: user.WeChatID.String, - LoginType: user.LoginType, - IsDisabled: user.IsDisabled(), - UserGroups: user.UserGroupNames, - ManagementPermissionList: generateManagementPermissionResV1s(permission[uint(user.Id)]), - } - usersRes = append(usersRes, userReq) - } - return c.JSON(http.StatusOK, &GetUsersResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: usersRes, - TotalNums: count, - }) -} - type UserTipsReqV1 struct { - FilterProject string `json:"filter_project" query:"filter_project"` + FilterProject string `json:"filter_project" query:"filter_project" valid:"required"` } type UserTipResV1 struct { - Name string `json:"user_name"` + UserID string `json:"user_id"` + Name string `json:"user_name"` } type GetUserTipsResV1 struct { @@ -571,7 +28,7 @@ type GetUserTipsResV1 struct { // @Tags user // @Id getUserTipListV1 // @Security ApiKeyAuth -// @Param filter_project query string false "project name" +// @Param filter_project query string true "project name" // @Success 200 {object} v1.GetUserTipsResV1 // @router /v1/user_tips [get] func GetUserTips(c echo.Context) error { @@ -579,474 +36,24 @@ func GetUserTips(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - s := model.GetStorage() - users, err := s.GetUserTipsByProject(req.FilterProject) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - userTipsRes := make([]UserTipResV1, 0, len(users)) - - for _, user := range users { - userTipRes := UserTipResV1{ - Name: user.Name, - } - userTipsRes = append(userTipsRes, userTipRes) - } - return c.JSON(http.StatusOK, &GetUserTipsResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: userTipsRes, - }) -} - -type CreateMemberReqV1 struct { - UserName string `json:"user_name" valid:"required"` - IsManager bool `json:"is_manager"` - Roles []BindRoleReqV1 `json:"roles" valid:"required"` -} - -type BindRoleReqV1 struct { - InstanceName string `json:"instance_name" valid:"required"` - RoleNames []string `json:"role_names" valid:"required"` -} - -// AddMember -// @Summary 添加成员 -// @Description add member -// @Id addMemberV1 -// @Tags user -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param project_name path string true "project name" -// @Param data body v1.CreateMemberReqV1 true "add member" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/members [post] -func AddMember(c echo.Context) error { - req := new(CreateMemberReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - - err := CheckIsProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - // 检查用户是否已添加过 - isMember, err := s.CheckUserIsMember(req.UserName, projectName) - if err != nil { - return err - } - if isMember { - return errors.New(errors.DataExist, fmt.Errorf("user %v is in project %v", req.UserName, projectName)) - } - - role := []model.BindRole{} - instNames := []string{} - roleNames := []string{} - for _, r := range req.Roles { - role = append(role, model.BindRole{ - RoleNames: r.RoleNames, - InstanceName: r.InstanceName, - }) - instNames = append(instNames, r.InstanceName) - roleNames = append(roleNames, r.RoleNames...) - } - - // 检查实例是否存在 - exist, err := s.CheckInstancesExist(projectName, utils.RemoveDuplicate(instNames)) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("prohibit binding non-existent instances"))) - } - - // 检查角色是否存在 - exist, err = s.CheckRolesExist(utils.RemoveDuplicate(roleNames)) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("prohibit binding non-existent roles"))) - } - - return controller.JSONBaseErrorReq(c, s.AddMember(req.UserName, projectName, req.IsManager, role)) -} - -type UpdateMemberReqV1 struct { - IsManager *bool `json:"is_manager"` - Roles *[]BindRoleReqV1 `json:"roles"` -} - -// UpdateMember -// @Summary 修改成员 -// @Description update member -// @Id updateMemberV1 -// @Tags user -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param project_name path string true "project name" -// @Param user_name path string true "user name" -// @Param data body v1.UpdateMemberReqV1 true "update member" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/members/{user_name}/ [patch] -func UpdateMember(c echo.Context) error { - req := new(UpdateMemberReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - projectName := c.Param("project_name") - userName := c.Param("user_name") - currentUser := controller.GetUserName(c) - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - err = CheckIsProjectManager(currentUser, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - isMember, err := s.CheckUserIsMember(userName, projectName) - if err != nil { - return err - } - if !isMember { - return errors.New(errors.DataNotExist, fmt.Errorf("user %v is not in project %v", userName, projectName)) - } - - // 更新成员 - if req.IsManager != nil { - if *req.IsManager { - isManager, err := s.IsProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !isManager { - err = s.AddProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - } else { - isLastManager, err := s.IsLastProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if isLastManager { - return controller.JSONBaseErrorReq(c, errors.New(errors.UserNotPermission, fmt.Errorf("you cannot delete the last administrator"))) - } - err = s.RemoveProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - - } - - // 更新角色 - role := []model.BindRole{} - if req.Roles != nil { - for _, r := range *req.Roles { - role = append(role, model.BindRole{ - RoleNames: r.RoleNames, - InstanceName: r.InstanceName, - }) - } - err = s.UpdateUserRoles(userName, projectName, role) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - - return controller.JSONBaseErrorReq(c, nil) -} - -// DeleteMember -// @Summary 删除成员 -// @Description delete member -// @Id deleteMemberV1 -// @Tags user -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param user_name path string true "user name" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/members/{user_name}/ [delete] -func DeleteMember(c echo.Context) error { - projectName := c.Param("project_name") - userName := c.Param("user_name") - currentUser := controller.GetUserName(c) - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - err = CheckIsProjectManager(currentUser, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - err = checkMemberCanDelete(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return controller.JSONBaseErrorReq(c, s.RemoveMember(userName, projectName)) - -} - -func checkMemberCanDelete(userName, projectName string) error { - - err := CheckIsProjectMember(userName, projectName) - if err != nil { - return err - } - - s := model.GetStorage() - user, exist, err := s.GetUserByName(userName) - if err != nil { - return err - } - if !exist { - return errors.New(errors.DataNotExist, fmt.Errorf("user not exist")) - } - - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return err - } - if !exist { - return ErrProjectNotExist(projectName) - } - - if len(project.Managers) == 1 && project.Managers[0].ID == user.ID { - return errors.New(errors.DataInvalid, fmt.Errorf("cannot delete the last administrator")) - } - - return nil - -} - -type GetMemberReqV1 struct { - FilterInstanceName string `json:"filter_instance_name" query:"filter_instance_name"` - FilterUserName string `json:"filter_user_name" query:"filter_user_name"` - PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` - PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` -} - -type GetMembersRespV1 struct { - controller.BaseRes - Data []GetMemberRespDataV1 `json:"data"` - TotalNums uint64 `json:"total_nums"` -} - -type GetMemberRespDataV1 struct { - UserName string `json:"user_name"` - IsManager bool `json:"is_manager"` - Roles []BindRoleReqV1 `json:"roles"` -} - -// GetMembers -// @Summary 获取成员列表 -// @Description get members -// @Id getMembersV1 -// @Tags user -// @Security ApiKeyAuth -// @Param filter_user_name query string false "filter user name" -// @Param filter_instance_name query string false "filter instance name" -// @Param page_index query uint32 true "page index" -// @Param page_size query uint32 true "size of per page" -// @Param project_name path string true "project name" -// @Success 200 {object} v1.GetMembersRespV1 -// @router /v1/projects/{project_name}/members [get] -func GetMembers(c echo.Context) error { - req := new(GetMemberReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - projectName := c.Param("project_name") - currentUser := controller.GetUserName(c) - - err := CheckIsProjectMember(currentUser, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - limit, offset := controller.GetLimitAndOffset(req.PageIndex, req.PageSize) - - // 获取成员信息 - mp := map[string]interface{}{ - "limit": limit, - "offset": offset, - "filter_project_name": projectName, - "filter_user_name": req.FilterUserName, - "filter_instance_name": req.FilterInstanceName, - } - - s := model.GetStorage() - members, total, err := s.GetMembersByReq(mp) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - // 获取角色信息 - memberNames := []string{} - for _, member := range members { - memberNames = append(memberNames, member.UserName) - } - - bindRole, err := s.GetBindRolesByMemberNames(memberNames, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - // 生成响应 - data := []GetMemberRespDataV1{} - for _, member := range members { - data = append(data, GetMemberRespDataV1{ - UserName: member.UserName, - IsManager: member.IsManager, - Roles: convertBindRoleToBindRoleReqV1(bindRole[member.UserName]), - }) - } - - return c.JSON(http.StatusOK, GetMembersRespV1{ - BaseRes: controller.NewBaseReq(nil), - Data: data, - TotalNums: total, - }) -} - -func convertBindRoleToBindRoleReqV1(role []model.BindRole) []BindRoleReqV1 { - req := []BindRoleReqV1{} - for _, r := range role { - req = append(req, BindRoleReqV1{ - InstanceName: r.InstanceName, - RoleNames: r.RoleNames, - }) - } - return req -} - -type GetMemberRespV1 struct { - controller.BaseRes - Data GetMemberRespDataV1 `json:"data"` -} - -// GetMember -// @Summary 获取成员信息 -// @Description get member -// @Id getMemberV1 -// @Tags user -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param user_name path string true "user name" -// @Success 200 {object} v1.GetMemberRespV1 -// @router /v1/projects/{project_name}/members/{user_name}/ [get] -func GetMember(c echo.Context) error { - projectName := c.Param("project_name") - userName := c.Param("user_name") - currentUser := controller.GetUserName(c) - - err := CheckIsProjectMember(currentUser, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - mp := map[string]interface{}{ - "limit": 1, - "offset": 1, - "filter_user_name": userName, - "filter_project_name": projectName, - } - - s := model.GetStorage() - members, _, err := s.GetMembersByReq(mp) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if len(members) != 1 { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("the number of members is not unique"))) - } - - bindRole, err := s.GetBindRolesByMemberNames([]string{members[0].UserName}, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return c.JSON(http.StatusOK, GetMemberRespV1{ - BaseRes: controller.NewBaseReq(nil), - Data: GetMemberRespDataV1{ - UserName: members[0].UserName, - IsManager: members[0].IsManager, - Roles: convertBindRoleToBindRoleReqV1(bindRole[members[0].UserName]), - }, - }) -} - -type MemberTipResV1 struct { - Name string `json:"user_name"` -} - -type GetMemberTipsResV1 struct { - controller.BaseRes - Data []MemberTipResV1 `json:"data"` -} - -// @Summary 获取成员提示列表 -// @Description get member tip list -// @Tags user -// @Id getMemberTipListV1 -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Success 200 {object} v1.GetMemberTipsResV1 -// @router /v1/projects/{project_name}/member_tips [get] -func GetMemberTips(c echo.Context) error { - projectName := c.Param("project_name") - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), req.FilterProject) if err != nil { return controller.JSONBaseErrorReq(c, err) } - - s := model.GetStorage() - users, err := s.GetMemberTips(projectName) + users, err := dms.ListProjectUserTips(c.Request().Context(), projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } - userTipsRes := make([]MemberTipResV1, 0, len(users)) + userTipsRes := make([]UserTipResV1, 0, len(users)) for _, user := range users { - userTipRes := MemberTipResV1{ - Name: user.Name, + userTipRes := UserTipResV1{ + Name: user.Name, + UserID: user.GetIDStr(), } userTipsRes = append(userTipsRes, userTipRes) } - return c.JSON(http.StatusOK, &GetMemberTipsResV1{ + return c.JSON(http.StatusOK, &GetUserTipsResV1{ BaseRes: controller.NewBaseReq(nil), Data: userTipsRes, }) diff --git a/sqle/api/controller/v1/user_group.go b/sqle/api/controller/v1/user_group.go deleted file mode 100644 index 7e9a017fd1..0000000000 --- a/sqle/api/controller/v1/user_group.go +++ /dev/null @@ -1,648 +0,0 @@ -package v1 - -import ( - "fmt" - "net/http" - - "github.com/actiontech/sqle/sqle/api/controller" - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/utils" - - "github.com/labstack/echo/v4" -) - -type CreateUserGroupReqV1 struct { - Name string `json:"user_group_name" form:"user_group_name" example:"test" valid:"required,name"` - Desc string `json:"user_group_desc" form:"user_group_desc" example:"this is a group"` - Users []string `json:"user_name_list" form:"user_name_list"` -} - -// @Summary 创建用户组 -// @Description create user group -// @Id CreateUserGroupV1 -// @Tags user_group -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param instance body v1.CreateUserGroupReqV1 true "create user group" -// @Success 200 {object} controller.BaseRes -// @router /v1/user_groups [post] -func CreateUserGroup(c echo.Context) (err error) { - - req := new(CreateUserGroupReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - s := model.GetStorage() - // check if user group already exist - { - _, isExist, err := s.GetUserGroupByName(req.Name) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if isExist { - return controller.JSONNewDataExistErr(c, "user group already exist") - } - } - - // check users - var users []*model.User - { - userNames := req.Users - users, err = s.GetAndCheckUserExist(userNames) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - - // user group - ug := &model.UserGroup{ - Name: req.Name, - Desc: req.Desc, - } - - if err := s.SaveUserGroupAndAssociations(ug, users); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return controller.JSONBaseErrorReq(c, nil) -} - -type GetUserGroupsReqV1 struct { - FilterUserGroupName string `json:"filter_user_group_name" query:"filter_user_group_name"` - PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` - PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` -} - -type GetUserGroupsResV1 struct { - controller.BaseRes - Data []*UserGroupListItemResV1 `json:"data"` - TotalNums uint64 `json:"total_nums"` -} - -type UserGroupListItemResV1 struct { - Name string `json:"user_group_name"` - Desc string `json:"user_group_desc"` - IsDisabled bool `json:"is_disabled,omitempty"` - Users []string `json:"user_name_list,omitempty"` -} - -// @Summary 获取用户组列表 -// @Description get user group info list -// @Id GetUserGroupsV1 -// @Tags user_group -// @Id getUserGroupListV1 -// @Security ApiKeyAuth -// @Param filter_user_group_name query string false "filter user group name" -// @Param page_index query uint32 true "page index" -// @Param page_size query uint32 true "size of per page" -// @Produce json -// @Success 200 {object} v1.GetUserGroupsResV1 -// @router /v1/user_groups [get] -func GetUserGroups(c echo.Context) (err error) { - req := new(GetUserGroupsReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - - var offset uint32 - if req.PageIndex >= 1 { - offset = req.PageSize * (req.PageIndex - 1) - } - - data := map[string]interface{}{ - "filter_user_group_name": req.FilterUserGroupName, - "limit": req.PageSize, - "offset": offset, - } - - userGroups, count, err := s.GetUserGroupsByReq(data) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - resData := make([]*UserGroupListItemResV1, len(userGroups)) - for i := range userGroups { - userGroupItem := &UserGroupListItemResV1{ - Name: userGroups[i].Name, - Desc: userGroups[i].Desc, - IsDisabled: userGroups[i].IsDisabled(), - Users: userGroups[i].UserNames, - } - resData[i] = userGroupItem - } - - return c.JSON(http.StatusOK, &GetUserGroupsResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: resData, - TotalNums: count, - }) -} - -// @Summary 删除用户组 -// @Description delete user group -// @Id deleteUserGroupV1 -// @Tags user_group -// @Security ApiKeyAuth -// @Param user_group_name path string true "user_group_name" -// @Success 200 {object} controller.BaseRes -// @router /v1/user_groups/{user_group_name}/ [delete] -func DeleteUserGroup(c echo.Context) (err error) { - - userGroupName := c.Param("user_group_name") - - s := model.GetStorage() - - // check if user group exist - var ug *model.UserGroup - { - var exist bool - ug, exist, err = s.GetUserGroupByName(userGroupName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq( - c, errors.NewDataNotExistErr("user group<%v> not exist", userGroupName)) - } - } - - err = s.RemoveMemberGroupFromAllProjectByUserGroupID(ug.ID) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - err = s.Delete(ug) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return controller.JSONBaseErrorReq(c, nil) -} - -type PatchUserGroupReqV1 struct { - Desc *string `json:"user_group_desc,omitempty" form:"user_group_desc" example:"this is a group"` - Users *[]string `json:"user_name_list,omitempty" form:"user_name_list"` - IsDisabled *bool `json:"is_disabled,omitempty" form:"is_disabled"` -} - -// @Summary 更新用户组 -// @Description update user group -// @Id updateUserGroupV1 -// @Tags user_group -// @Security ApiKeyAuth -// @Param user_group_name path string true "user_group_name" -// @Param instance body v1.PatchUserGroupReqV1 true "update user group" -// @Success 200 {object} controller.BaseRes -// @router /v1/user_groups/{user_group_name}/ [patch] -func UpdateUserGroup(c echo.Context) (err error) { - - userGroupName := c.Param("user_group_name") - - req := new(PatchUserGroupReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - s := model.GetStorage() - - // check if user group already exist - var ug *model.UserGroup - { - var isExist bool - ug, isExist, err = s.GetUserGroupByName(userGroupName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !isExist { - return controller.JSONNewDataNotExistErr(c, "user_group<%v> not exist", userGroupName) - } - } - - // update stat - if req.IsDisabled != nil { - if *req.IsDisabled { - ug.SetStat(model.Disabled) - } else { - ug.SetStat(model.Enabled) - } - } - - // update desc - if req.Desc != nil { - ug.Desc = *req.Desc - } - - // users - var users []*model.User - { - if req.Users != nil { - if len(*req.Users) > 0 { - users, err = s.GetAndCheckUserExist(*req.Users) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } else { - users = make([]*model.User, 0) - } - } - } - - if err := s.SaveUserGroupAndAssociations(ug, users); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return controller.JSONBaseErrorReq(c, nil) -} - -type UserGroupTipsReqV1 struct { - FilterProject string `json:"filter_project" query:"filter_project"` -} - -type UserGroupTipListItem struct { - Name string `json:"user_group_name"` - UserNames []string `json:"user_names"` -} - -type GetUserGroupTipsResV1 struct { - controller.BaseRes - Data []*UserGroupTipListItem `json:"data"` -} - -// @Summary 获取用户组提示列表 -// @Description get user group tip list -// @Tags user_group -// @Id getUserGroupTipListV1 -// @Param filter_project query string false "project name" -// @Security ApiKeyAuth -// @Success 200 {object} v1.GetUserGroupTipsResV1 -// @router /v1/user_group_tips [get] -func GetUserGroupTips(c echo.Context) error { - req := new(UserGroupTipsReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - s := model.GetStorage() - - data := map[string]interface{}{ - "project_name": req.FilterProject, - } - userGroups, err := s.GetUserGroupTipByProject(data) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - userGroupTipsRes := make([]*UserGroupTipListItem, len(userGroups)) - for i := range userGroups { - userGroupTipsRes[i] = &UserGroupTipListItem{ - Name: userGroups[i].Name, - UserNames: userGroups[i].UserNames, - } - } - - return c.JSON(http.StatusOK, &GetUserGroupTipsResV1{ - BaseRes: controller.NewBaseReq(nil), - Data: userGroupTipsRes, - }) -} - -type CreateMemberGroupReqV1 struct { - UserGroupName string `json:"user_group_name" valid:"required"` - Roles []BindRoleReqV1 `json:"roles" valid:"required"` -} - -// AddMemberGroup -// @Summary 添加成员组 -// @Description add member group -// @Id addMemberGroupV1 -// @Tags user_group -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param project_name path string true "project name" -// @Param data body v1.CreateMemberGroupReqV1 true "add member group" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/member_groups [post] -func AddMemberGroup(c echo.Context) error { - req := new(CreateMemberGroupReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - err = CheckIsProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - // 检查用户组是否已添加过 - isMember, err := s.CheckUserGroupIsMember(req.UserGroupName, projectName) - if err != nil { - return err - } - if isMember { - return errors.New(errors.DataExist, fmt.Errorf("user group %v is in project %v", req.UserGroupName, projectName)) - } - - role := []model.BindRole{} - instNames := []string{} - roleNames := []string{} - for _, r := range req.Roles { - role = append(role, model.BindRole{ - RoleNames: r.RoleNames, - InstanceName: r.InstanceName, - }) - instNames = append(instNames, r.InstanceName) - roleNames = append(roleNames, r.RoleNames...) - } - - // 检查实例是否存在 - exist, err := s.CheckInstancesExist(projectName, utils.RemoveDuplicate(instNames)) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("prohibit binding non-existent instances"))) - } - - // 检查角色是否存在 - exist, err = s.CheckRolesExist(utils.RemoveDuplicate(roleNames)) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("prohibit binding non-existent roles"))) - } - - return controller.JSONBaseErrorReq(c, s.AddMemberGroup(req.UserGroupName, projectName, role)) -} - -type UpdateMemberGroupReqV1 struct { - Roles *[]BindRoleReqV1 `json:"roles"` -} - -// UpdateMemberGroup -// @Summary 修改成员组 -// @Description update member group -// @Id updateMemberGroupV1 -// @Tags user_group -// @Security ApiKeyAuth -// @Accept json -// @Produce json -// @Param project_name path string true "project name" -// @Param user_group_name path string true "user group name" -// @Param data body v1.UpdateMemberGroupReqV1 true "update member_group" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/member_groups/{user_group_name}/ [patch] -func UpdateMemberGroup(c echo.Context) error { - req := new(UpdateMemberGroupReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - projectName := c.Param("project_name") - groupName := c.Param("user_group_name") - currentUser := controller.GetUserName(c) - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - err = CheckIsProjectManager(currentUser, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - isMember, err := s.CheckUserGroupIsMember(groupName, projectName) - if err != nil { - return err - } - if !isMember { - return errors.New(errors.DataNotExist, fmt.Errorf("user group %v is not in project %v", groupName, projectName)) - } - - // 更新角色 - role := []model.BindRole{} - if req.Roles != nil { - for _, r := range *req.Roles { - role = append(role, model.BindRole{ - RoleNames: r.RoleNames, - InstanceName: r.InstanceName, - }) - } - err = s.UpdateUserGroupRoles(groupName, projectName, role) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - - return controller.JSONBaseErrorReq(c, nil) -} - -// DeleteMemberGroup -// @Summary 删除成员组 -// @Description delete member group -// @Id deleteMemberGroupV1 -// @Tags user_group -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param user_group_name path string true "user group name" -// @Success 200 {object} controller.BaseRes -// @router /v1/projects/{project_name}/member_groups/{user_group_name}/ [delete] -func DeleteMemberGroup(c echo.Context) error { - projectName := c.Param("project_name") - groupName := c.Param("user_group_name") - currentUser := controller.GetUserName(c) - - s := model.GetStorage() - archived, err := s.IsProjectArchived(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if archived { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - - err = CheckIsProjectManager(currentUser, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return controller.JSONBaseErrorReq(c, s.RemoveMemberGroup(groupName, projectName)) - -} - -type GetMemberGroupReqV1 struct { - FilterInstanceName string `json:"filter_instance_name" query:"filter_instance_name"` - FilterUserGroupName string `json:"filter_user_group_name" query:"filter_user_group_name"` - PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` - PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` -} - -type GetMemberGroupsRespV1 struct { - controller.BaseRes - Data []GetMemberGroupRespDataV1 `json:"data"` - TotalNums uint64 `json:"total_nums"` -} - -type MemberGroupUserItem struct { - Name string `json:"name"` -} - -type GetMemberGroupRespDataV1 struct { - UserGroupName string `json:"user_group_name"` - Roles []BindRoleReqV1 `json:"roles"` - Users []MemberGroupUserItem `json:"users"` -} - -// GetMemberGroups -// @Summary 获取成员组列表 -// @Description get member groups -// @Id getMemberGroupsV1 -// @Tags user_group -// @Security ApiKeyAuth -// @Param filter_user_group_name query string false "filter user group name" -// @Param filter_instance_name query string false "filter instance name" -// @Param page_index query uint32 true "page index" -// @Param page_size query uint32 true "size of per page" -// @Param project_name path string true "project name" -// @Success 200 {object} v1.GetMemberGroupsRespV1 -// @router /v1/projects/{project_name}/member_groups [get] -func GetMemberGroups(c echo.Context) error { - req := new(GetMemberGroupReqV1) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - projectName := c.Param("project_name") - currentUser := controller.GetUserName(c) - - err := CheckIsProjectMember(currentUser, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - // 获取成员组列表 - limit, offset := controller.GetLimitAndOffset(req.PageIndex, req.PageSize) - filter := model.GetMemberGroupFilter{ - Limit: &limit, - Offset: &offset, - FilterProjectName: &projectName, - } - if req.FilterInstanceName != "" { - filter.FilterInstanceName = &req.FilterInstanceName - } - if req.FilterUserGroupName != "" { - filter.FilterUserGroupName = &req.FilterUserGroupName - } - - s := model.GetStorage() - groups, err := s.GetMemberGroups(filter) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - total, err := s.GetMemberGroupCount(filter) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - // 获取角色信息 - groupNames := []string{} - for _, group := range groups { - groupNames = append(groupNames, group.Name) - } - - bindRole, err := s.GetBindRolesByMemberGroupNames(groupNames, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - // 生成响应 - data := []GetMemberGroupRespDataV1{} - for _, group := range groups { - data = append(data, GetMemberGroupRespDataV1{ - UserGroupName: group.Name, - Roles: convertBindRoleToBindRoleReqV1(bindRole[group.Name]), - Users: convertMemberGroupUsers(group.Users), - }) - } - - return c.JSON(http.StatusOK, GetMemberGroupsRespV1{ - BaseRes: controller.NewBaseReq(nil), - Data: data, - TotalNums: total, - }) -} - -func convertMemberGroupUsers(users []*model.User) []MemberGroupUserItem { - usersRes := make([]MemberGroupUserItem, len(users)) - for i, user := range users { - usersRes[i] = MemberGroupUserItem{Name: user.Name} - } - return usersRes -} - -type GetMemberGroupRespV1 struct { - controller.BaseRes - Data GetMemberGroupRespDataV1 `json:"data"` -} - -// GetMemberGroup -// @Summary 获取成员组信息 -// @Description get member group -// @Id getMemberGroupV1 -// @Tags user_group -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param user_group_name path string true "user group name" -// @Success 200 {object} v1.GetMemberGroupRespV1 -// @router /v1/projects/{project_name}/member_groups/{user_group_name}/ [get] -func GetMemberGroup(c echo.Context) error { - projectName := c.Param("project_name") - groupName := c.Param("user_group_name") - currentUser := controller.GetUserName(c) - - err := CheckIsProjectMember(currentUser, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - s := model.GetStorage() - userGroup, err := s.GetMemberGroupByGroupName(projectName, groupName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - bindRole, err := s.GetBindRolesByMemberGroupNames([]string{userGroup.Name}, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return c.JSON(http.StatusOK, GetMemberGroupRespV1{ - BaseRes: controller.NewBaseReq(nil), - Data: GetMemberGroupRespDataV1{ - UserGroupName: userGroup.Name, - Roles: convertBindRoleToBindRoleReqV1(bindRole[userGroup.Name]), - }, - }) -} diff --git a/sqle/api/controller/v1/workflow.go b/sqle/api/controller/v1/workflow.go index 54f284dcf1..4e49e73439 100644 --- a/sqle/api/controller/v1/workflow.go +++ b/sqle/api/controller/v1/workflow.go @@ -1,18 +1,24 @@ package v1 import ( + "context" "database/sql" e "errors" "fmt" "net/http" "strconv" + "strings" "time" + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/dms" driverV2 "github.com/actiontech/sqle/sqle/driver/v2" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/model" + "github.com/actiontech/sqle/sqle/server" "github.com/actiontech/sqle/sqle/utils" + "github.com/labstack/echo/v4" ) @@ -41,7 +47,7 @@ type WorkflowTemplateDetailResV1 struct { Desc string `json:"desc,omitempty"` AllowSubmitWhenLessAuditLevel string `json:"allow_submit_when_less_audit_level" enums:"normal,notice,warn,error"` Steps []*WorkFlowStepTemplateResV1 `json:"workflow_step_template_list"` - Instances []string `json:"instance_name_list,omitempty"` + UpdateTime time.Time `json:"update_time"` } type WorkFlowStepTemplateResV1 struct { @@ -50,7 +56,7 @@ type WorkFlowStepTemplateResV1 struct { Desc string `json:"desc,omitempty"` ApprovedByAuthorized bool `json:"approved_by_authorized"` ExecuteByAuthorized bool `json:"execute_by_authorized"` - Users []string `json:"assignee_user_name_list"` + Users []string `json:"assignee_user_id_list"` } // @Summary 获取审批流程模板详情 @@ -64,55 +70,54 @@ type WorkFlowStepTemplateResV1 struct { func GetWorkflowTemplate(c echo.Context) error { s := model.GetStorage() - projectName := c.Param("project_name") - - err := CheckIsProjectMember(controller.GetUserName(c), projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } + var td *model.WorkflowTemplate - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - - template, exist, err := s.GetWorkflowTemplateById(project.WorkflowTemplateId) + template, exist, err := s.GetWorkflowTemplateByProjectId(model.ProjectUID(projectUid)) if err != nil { return controller.JSONBaseErrorReq(c, err) } if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, - fmt.Errorf("workflow template is not exist"))) - } - - res, err := getWorkflowTemplateDetailByTemplate(template) - if err != nil { - return controller.JSONBaseErrorReq(c, err) + td = model.DefaultWorkflowTemplate(projectUid) + err = s.SaveWorkflowTemplate(td) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + } else { + td, err = getWorkflowTemplateDetailByTemplate(template) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } } return c.JSON(http.StatusOK, &GetWorkflowTemplateResV1{ BaseRes: controller.NewBaseReq(nil), - Data: res, + Data: convertWorkflowTemplateToRes(td), }) } -func getWorkflowTemplateDetailByTemplate(template *model.WorkflowTemplate) (*WorkflowTemplateDetailResV1, error) { +func getWorkflowTemplateDetailByTemplate(template *model.WorkflowTemplate) (*model.WorkflowTemplate, error) { s := model.GetStorage() steps, err := s.GetWorkflowStepsDetailByTemplateId(template.ID) if err != nil { return nil, err } template.Steps = steps + return template, nil +} + +func convertWorkflowTemplateToRes(template *model.WorkflowTemplate) *WorkflowTemplateDetailResV1 { res := &WorkflowTemplateDetailResV1{ Name: template.Name, Desc: template.Desc, AllowSubmitWhenLessAuditLevel: template.AllowSubmitWhenLessAuditLevel, + UpdateTime: template.UpdatedAt, } - stepsRes := make([]*WorkFlowStepTemplateResV1, 0, len(steps)) - for _, step := range steps { + stepsRes := make([]*WorkFlowStepTemplateResV1, 0, len(template.Steps)) + for _, step := range template.Steps { stepRes := &WorkFlowStepTemplateResV1{ Number: int(step.Number), ApprovedByAuthorized: step.ApprovedByAuthorized.Bool, @@ -120,23 +125,20 @@ func getWorkflowTemplateDetailByTemplate(template *model.WorkflowTemplate) (*Wor Typ: step.Typ, Desc: step.Desc, } - users := []string{} - if step.Users != nil { - for _, user := range step.Users { - users = append(users, user.Name) - } + stepRes.Users = make([]string, 0) + if step.Users != "" { + stepRes.Users = strings.Split(step.Users, ",") } - stepRes.Users = users stepsRes = append(stepsRes, stepRes) } res.Steps = stepsRes - instanceNames, err := s.GetInstanceNamesByWorkflowTemplateId(template.ID) - if err != nil { - return nil, err - } - res.Instances = instanceNames - return res, nil + // instanceNames, err := s.GetInstanceNamesByWorkflowTemplateId(template.ID) + // if err != nil { + // return nil, err + // } + // res.Instances = instanceNames + return res } type WorkFlowStepTemplateReqV1 struct { @@ -144,7 +146,7 @@ type WorkFlowStepTemplateReqV1 struct { Desc string `json:"desc" form:"desc"` ApprovedByAuthorized bool `json:"approved_by_authorized"` ExecuteByAuthorized bool `json:"execute_by_authorized"` - Users []string `json:"assignee_user_name_list" form:"assignee_user_name_list"` + Users []string `json:"assignee_user_id_list" form:"assignee_user_id_list"` } func validWorkflowTemplateReq(steps []*WorkFlowStepTemplateReqV1) error { @@ -177,7 +179,6 @@ type UpdateWorkflowTemplateReqV1 struct { Desc *string `json:"desc" form:"desc"` AllowSubmitWhenLessAuditLevel *string `json:"allow_submit_when_less_audit_level" enums:"normal,notice,warn,error"` Steps []*WorkFlowStepTemplateReqV1 `json:"workflow_step_template_list" form:"workflow_step_template_list"` - Instances []string `json:"instance_name_list" form:"instance_name_list"` } // @Summary 更新Sql审批流程模板 @@ -197,27 +198,14 @@ func UpdateWorkflowTemplate(c echo.Context) error { return err } - projectName := c.Param("project_name") - - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - if project.IsArchived() { - return controller.JSONBaseErrorReq(c, ErrProjectArchived) - } - userName := controller.GetUserName(c) - err = CheckIsProjectManager(userName, project.Name) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } + s := model.GetStorage() - workflowTemplate, exist, err := s.GetWorkflowTemplateById(project.WorkflowTemplateId) + workflowTemplate, exist, err := s.GetWorkflowTemplateByProjectId(model.ProjectUID(projectUid)) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -226,32 +214,13 @@ func UpdateWorkflowTemplate(c echo.Context) error { fmt.Errorf("workflow template is not exist"))) } - var instances []*model.Instance - if req.Instances != nil && len(req.Instances) > 0 { - instances, err = s.GetAndCheckInstanceExist(req.Instances, project.Name) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - if req.Steps != nil { err = validWorkflowTemplateReq(req.Steps) if err != nil { return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, err)) } - userNames := []string{} - for _, step := range req.Steps { - userNames = append(userNames, step.Users...) - } - users, err := s.GetAndCheckUserExist(userNames) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - userMap := map[string]*model.User{} - for _, user := range users { - userMap[user.Name] = user - } + // dms-todo: 校验step.Users用户是否存在 steps := make([]*model.WorkflowStepTemplate, 0, len(req.Steps)) for i, step := range req.Steps { @@ -268,11 +237,7 @@ func UpdateWorkflowTemplate(c echo.Context) error { Typ: step.Type, Desc: step.Desc, } - stepUsers := make([]*model.User, 0, len(step.Users)) - for _, userName := range step.Users { - stepUsers = append(stepUsers, userMap[userName]) - } - s.Users = stepUsers + s.Users = strings.Join(step.Users, ",") steps = append(steps, s) } err = s.UpdateWorkflowTemplateSteps(workflowTemplate.ID, steps) @@ -294,13 +259,6 @@ func UpdateWorkflowTemplate(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - if req.Instances != nil { - err = s.UpdateWorkflowTemplateInstances(workflowTemplate, instances...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - } - return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) } @@ -445,13 +403,10 @@ func ExecuteOneTaskOnWorkflowV1(c echo.Context) error { } func IsTaskCanExecute(s *model.Storage, taskId string) (bool, error) { - task, exist, err := s.GetTaskById(taskId) + task, err := getTaskById(context.Background(), taskId) if err != nil { return false, fmt.Errorf("get task by id failed. taskId=%v err=%v", taskId, err) } - if !exist { - return false, fmt.Errorf("task not exist. taskId=%v", taskId) - } if task.Instance == nil { return false, fmt.Errorf("task instance is nil. taskId=%v", taskId) @@ -474,12 +429,64 @@ func IsTaskCanExecute(s *model.Storage, taskId string) (bool, error) { return true, nil } -func PrepareForTaskExecution(c echo.Context, projectName string, workflow *model.Workflow, user *model.User, TaskId int) error { +func GetNeedExecTaskIds(workflow *model.Workflow, user *model.User) (taskIds map[uint] /*task id*/ string /*user id*/, err error) { + instances := make([]*model.Instance, 0, len(workflow.Record.InstanceRecords)) + for _, item := range workflow.Record.InstanceRecords { + instances = append(instances, item.Instance) + } + + // 有不在运维时间内的instances报错 + var cannotExecuteInstanceNames []string + for _, inst := range instances { + if len(inst.MaintenancePeriod) != 0 && !inst.MaintenancePeriod.IsWithinScope(time.Now()) { + cannotExecuteInstanceNames = append(cannotExecuteInstanceNames, inst.Name) + } + } + if len(cannotExecuteInstanceNames) > 0 { + return nil, errors.New(errors.TaskActionInvalid, + fmt.Errorf("please go online during instance operation and maintenance time. these instances are not in maintenance time[%v]", strings.Join(cannotExecuteInstanceNames, ","))) + } + + // 定时的instances和已上线的跳过 + needExecTaskIds := make(map[uint]string) + for _, instRecord := range workflow.Record.InstanceRecords { + if instRecord.ScheduledAt != nil || instRecord.IsSQLExecuted { + continue + } + needExecTaskIds[instRecord.TaskId] = user.GetIDStr() + } + return needExecTaskIds, nil +} + +func PrepareForWorkflowExecution(c echo.Context, projectUid string, workflow *model.Workflow, user *model.User) error { + err := CheckCurrentUserCanOperateWorkflow(c, projectUid, workflow, []dmsV1.OpPermissionType{}) + if err != nil { + return err + } + + currentStep := workflow.CurrentStep() + if currentStep == nil { + return errors.New(errors.DataInvalid, fmt.Errorf("workflow current step not found")) + } + + if workflow.Record.Status != model.WorkflowStatusWaitForExecution { + return errors.New(errors.DataInvalid, + fmt.Errorf("workflow need to be approved first")) + } + + err = server.CheckUserCanOperateStep(user, workflow, int(currentStep.ID)) + if err != nil { + return errors.New(errors.DataInvalid, err) + } + return nil +} + +func PrepareForTaskExecution(c echo.Context, projectID string, workflow *model.Workflow, user *model.User, TaskId int) error { if workflow.Record.Status != model.WorkflowStatusWaitForExecution { return errors.New(errors.DataInvalid, e.New("workflow need to be approved first")) } - err := CheckCurrentUserCanOperateTasks(c, &model.Project{Name: projectName}, workflow, []uint{model.OP_WORKFLOW_EXECUTE}, []uint{uint(TaskId)}) + err := CheckCurrentUserCanOperateTasks(c, projectID, workflow, []dmsV1.OpPermissionType{dmsV1.OpPermissionTypeExecuteWorkflow}, []uint{uint(TaskId)}) if err != nil { return err } @@ -489,8 +496,8 @@ func PrepareForTaskExecution(c echo.Context, projectName string, workflow *model continue } - for _, u := range record.ExecutionAssignees { - if u.ID == user.ID { + for _, u := range strings.Split(record.ExecutionAssignees, ",") { + if u == user.GetIDStr() { return nil } } @@ -614,19 +621,19 @@ func CheckWorkflowCanCommit(template *model.WorkflowTemplate, tasks []*model.Tas } type GetWorkflowsReqV1 struct { - FilterSubject string `json:"filter_subject" query:"filter_subject"` - FilterWorkflowID string `json:"filter_workflow_id" query:"filter_workflow_id"` - FuzzySearchWorkflowDesc string `json:"fuzzy_search_workflow_desc" query:"fuzzy_search_workflow_desc"` - FilterCreateTimeFrom string `json:"filter_create_time_from" query:"filter_create_time_from"` - FilterCreateTimeTo string `json:"filter_create_time_to" query:"filter_create_time_to"` - FilterCreateUserName string `json:"filter_create_user_name" query:"filter_create_user_name"` - FilterStatus string `json:"filter_status" query:"filter_status" valid:"omitempty,oneof=wait_for_audit wait_for_execution rejected canceled executing exec_failed finished"` - FilterCurrentStepAssigneeUserName string `json:"filter_current_step_assignee_user_name" query:"filter_current_step_assignee_user_name"` - FilterTaskInstanceName string `json:"filter_task_instance_name" query:"filter_task_instance_name"` - FilterTaskExecuteStartTimeFrom string `json:"filter_task_execute_start_time_from" query:"filter_task_execute_start_time_from"` - FilterTaskExecuteStartTimeTo string `json:"filter_task_execute_start_time_to" query:"filter_task_execute_start_time_to"` - PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` - PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` + FilterSubject string `json:"filter_subject" query:"filter_subject"` + FilterWorkflowID string `json:"filter_workflow_id" query:"filter_workflow_id"` + FilterCreateTimeFrom string `json:"filter_create_time_from" query:"filter_create_time_from"` + FilterCreateTimeTo string `json:"filter_create_time_to" query:"filter_create_time_to"` + FilterCreateUserId string `json:"filter_create_user_id" query:"filter_create_user_id"` + FilterStatus string `json:"filter_status" query:"filter_status" valid:"omitempty,oneof=wait_for_audit wait_for_execution rejected canceled executing exec_failed finished"` + FilterCurrentStepAssigneeUserId string `json:"filter_current_step_assignee_user_id" query:"filter_current_step_assignee_user_id"` + FilterTaskInstanceName string `json:"filter_task_instance_name" query:"filter_task_instance_name"` + FilterTaskExecuteStartTimeFrom string `json:"filter_task_execute_start_time_from" query:"filter_task_execute_start_time_from"` + FilterTaskExecuteStartTimeTo string `json:"filter_task_execute_start_time_to" query:"filter_task_execute_start_time_to"` + PageIndex uint32 `json:"page_index" query:"page_index" valid:"required"` + PageSize uint32 `json:"page_size" query:"page_size" valid:"required"` + FuzzyKeyword string `json:"fuzzy_keyword" query:"fuzzy_keyword"` } type GetWorkflowsResV1 struct { @@ -658,10 +665,10 @@ type WorkflowDetailResV1 struct { // @Param filter_create_time_to query string false "filter create time to" // @Param filter_task_execute_start_time_from query string false "filter_task_execute_start_time_from" // @Param filter_task_execute_start_time_to query string false "filter_task_execute_start_time_to" -// @Param filter_create_user_name query string false "filter create user name" +// @Param filter_create_user_id query string false "filter create user id" // @Param filter_status query string false "filter workflow status" Enums(wait_for_audit,wait_for_execution,rejected,executing,canceled,exec_failed,finished) -// @Param filter_current_step_assignee_user_name query string false "filter current step assignee user name" -// @Param filter_task_instance_name query string false "filter instance name" +// @Param filter_current_step_assignee_user_id query string false "filter current step assignee user id" +// @Param filter_task_instance_name query string false "filter instance id" // @Param page_index query uint32 true "page index" // @Param page_size query uint32 true "size of per page" // @Success 200 {object} v1.GetWorkflowsResV1 @@ -672,7 +679,7 @@ func GetGlobalWorkflowsV1(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - user, err := controller.GetCurrentUser(c) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -683,38 +690,43 @@ func GetGlobalWorkflowsV1(c echo.Context) error { } data := map[string]interface{}{ - "filter_subject": req.FilterSubject, - "filter_create_time_from": req.FilterCreateTimeFrom, - "filter_create_time_to": req.FilterCreateTimeTo, - "filter_create_user_name": req.FilterCreateUserName, - "filter_task_execute_start_time_from": req.FilterTaskExecuteStartTimeFrom, - "filter_task_execute_start_time_to": req.FilterTaskExecuteStartTimeTo, - "filter_status": req.FilterStatus, - "filter_current_step_assignee_user_name": req.FilterCurrentStepAssigneeUserName, - "filter_task_instance_name": req.FilterTaskInstanceName, - "current_user_id": user.ID, - "check_user_can_access": user.Name != model.DefaultAdminUser, - "limit": req.PageSize, - "offset": offset, + "filter_subject": req.FilterSubject, + "filter_create_time_from": req.FilterCreateTimeFrom, + "filter_create_time_to": req.FilterCreateTimeTo, + "filter_create_user_id": req.FilterCreateUserId, + "filter_task_execute_start_time_from": req.FilterTaskExecuteStartTimeFrom, + "filter_task_execute_start_time_to": req.FilterTaskExecuteStartTimeTo, + "filter_status": req.FilterStatus, + "filter_current_step_assignee_user_id": req.FilterCurrentStepAssigneeUserId, + "filter_task_instance_name": req.FilterTaskInstanceName, + "current_user_id": user.GetIDStr(), + "check_user_can_access": user.Name != model.DefaultAdminUser, // dms-todo: 判断是否是超级管理员 + "limit": req.PageSize, + "offset": offset, } s := model.GetStorage() - workflows, count, err := s.GetWorkflowsByReq(data, user) + workflows, count, err := s.GetWorkflowsByReq(data) if err != nil { return controller.JSONBaseErrorReq(c, err) } + /* + TODO 全局工单暂时不使用 + 1. viewable_instance_ids,check_user_can_access 调用 AddFilterInstanceAndUserAdmin 添加筛选项 + 2. 用户相关代码需要从DMS获取 + */ workflowsResV1 := make([]*WorkflowDetailResV1, 0, len(workflows)) for _, workflow := range workflows { workflowRes := &WorkflowDetailResV1{ - ProjectName: workflow.ProjectName, + ProjectName: workflow.ProjectId, // dms-todo: 临时使用id代替name Name: workflow.Subject, WorkflowId: workflow.WorkflowId, Desc: workflow.Desc, CreateUser: utils.AddDelTag(workflow.CreateUserDeletedAt, workflow.CreateUser.String), CreateTime: workflow.CreateTime, CurrentStepType: workflow.CurrentStepType.String, - CurrentStepAssigneeUser: workflow.CurrentStepAssigneeUser, + CurrentStepAssigneeUser: strings.Split(workflow.CurrentStepAssigneeUserIds.String, ","), Status: workflow.Status, } workflowsResV1 = append(workflowsResV1, workflowRes) @@ -740,13 +752,14 @@ func GetGlobalWorkflowsV1(c echo.Context) error { // @Param filter_create_time_to query string false "filter create time to" // @Param filter_task_execute_start_time_from query string false "filter_task_execute_start_time_from" // @Param filter_task_execute_start_time_to query string false "filter_task_execute_start_time_to" -// @Param filter_create_user_name query string false "filter create user name" +// @Param filter_create_user_id query string false "filter create user id" // @Param filter_status query string false "filter workflow status" Enums(wait_for_audit,wait_for_execution,rejected,executing,canceled,exec_failed,finished) -// @Param filter_current_step_assignee_user_name query string false "filter current step assignee user name" +// @Param filter_current_step_assignee_user_id query string false "filter current step assignee user id" // @Param filter_task_instance_name query string false "filter instance name" // @Param page_index query uint32 true "page index" // @Param page_size query uint32 true "size of per page" // @Param project_name path string true "project name" +// @Param fuzzy_keyword query string false "fuzzy matching subject/workflow_id" // @Success 200 {object} v1.GetWorkflowsResV1 // @router /v1/projects/{project_name}/workflows [get] func GetWorkflowsV1(c echo.Context) error { @@ -754,68 +767,74 @@ func GetWorkflowsV1(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return controller.JSONBaseErrorReq(c, err) } - - projectName := c.Param("project_name") - - s := model.GetStorage() - - project, exist, err := s.GetProjectByName(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrProjectNotExist(projectName)) - } - user, err := controller.GetCurrentUser(c) + s := model.GetStorage() + + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - - if err := CheckIsProjectMember(user.Name, project.Name); err != nil { + up, err := dms.NewUserPermission(user.GetIDStr(), projectUid) + if err != nil { return controller.JSONBaseErrorReq(c, err) } - var offset uint32 if req.PageIndex > 0 { offset = (req.PageIndex - 1) * req.PageSize } - data := map[string]interface{}{ - "filter_workflow_id": req.FilterWorkflowID, - "fuzzy_search_workflow_desc": req.FuzzySearchWorkflowDesc, - "filter_subject": req.FilterSubject, - "filter_create_time_from": req.FilterCreateTimeFrom, - "filter_create_time_to": req.FilterCreateTimeTo, - "filter_create_user_name": req.FilterCreateUserName, - "filter_task_execute_start_time_from": req.FilterTaskExecuteStartTimeFrom, - "filter_task_execute_start_time_to": req.FilterTaskExecuteStartTimeTo, - "filter_status": req.FilterStatus, - "filter_current_step_assignee_user_name": req.FilterCurrentStepAssigneeUserName, - "filter_task_instance_name": req.FilterTaskInstanceName, - "filter_project_name": project.Name, - "current_user_id": user.ID, - "check_user_can_access": CheckIsProjectManager(user.Name, project.Name) != nil, - "limit": req.PageSize, - "offset": offset, - } - - workflows, count, err := s.GetWorkflowsByReq(data, user) + "filter_workflow_id": req.FilterWorkflowID, + "filter_subject": req.FilterSubject, + "filter_create_time_from": req.FilterCreateTimeFrom, + "filter_create_time_to": req.FilterCreateTimeTo, + "filter_create_user_id": req.FilterCreateUserId, + "filter_task_execute_start_time_from": req.FilterTaskExecuteStartTimeFrom, + "filter_task_execute_start_time_to": req.FilterTaskExecuteStartTimeTo, + "filter_status": req.FilterStatus, + "filter_current_step_assignee_user_id": req.FilterCurrentStepAssigneeUserId, + "filter_task_instance_name": req.FilterTaskInstanceName, + "filter_project_id": projectUid, + "current_user_id": user.ID, + "check_user_can_access": !up.IsAdmin(), + "limit": req.PageSize, + "offset": offset, + } + if req.FuzzyKeyword != "" { + data["fuzzy_keyword"] = fmt.Sprintf("%%%s%%", req.FuzzyKeyword) + } + + if !up.IsAdmin() { + data["viewable_instance_ids"] = strings.Join(up.GetInstancesByOP(dmsV1.OpPermissionTypeViewOthersWorkflow), ",") + } + + workflows, count, err := s.GetWorkflowsByReq(data) if err != nil { return controller.JSONBaseErrorReq(c, err) } workflowsResV1 := make([]*WorkflowDetailResV1, 0, len(workflows)) for _, workflow := range workflows { + // TODO DMS提供根据ID批量查询用户接口,demo阶段使用GetUser实现 + CurrentStepAssigneeUserNames := make([]string, 0) + for _, currentStepAssigneeUser := range strings.Split(workflow.CurrentStepAssigneeUserIds.String, ",") { + if currentStepAssigneeUser == "" { + continue + } + CurrentStepAssigneeUserNames = append(CurrentStepAssigneeUserNames, dms.GetUserNameWithDelTag(currentStepAssigneeUser)) + } workflowRes := &WorkflowDetailResV1{ - ProjectName: workflow.ProjectName, + ProjectName: workflow.ProjectId, // dms-todo: 暂时使用id代替name Name: workflow.Subject, WorkflowId: workflow.WorkflowId, Desc: workflow.Desc, - CreateUser: utils.AddDelTag(workflow.CreateUserDeletedAt, workflow.CreateUser.String), + CreateUser: dms.GetUserNameWithDelTag(workflow.CreateUser.String), CreateTime: workflow.CreateTime, CurrentStepType: workflow.CurrentStepType.String, - CurrentStepAssigneeUser: workflow.CurrentStepAssigneeUser, + CurrentStepAssigneeUser: CurrentStepAssigneeUserNames, Status: workflow.Status, } workflowsResV1 = append(workflowsResV1, workflowRes) @@ -930,16 +949,16 @@ func GetWorkflowV1(c echo.Context) error { } type ExportWorkflowReqV1 struct { - FilterSubject string `json:"filter_subject" query:"filter_subject"` - FuzzySearchWorkflowDesc string `json:"fuzzy_search_workflow_desc" query:"fuzzy_search_workflow_desc"` - FilterCreateTimeFrom string `json:"filter_create_time_from" query:"filter_create_time_from"` - FilterCreateTimeTo string `json:"filter_create_time_to" query:"filter_create_time_to"` - FilterCreateUserName string `json:"filter_create_user_name" query:"filter_create_user_name"` - FilterStatus string `json:"filter_status" query:"filter_status" valid:"omitempty,oneof=wait_for_audit wait_for_execution rejected canceled executing exec_failed finished"` - FilterCurrentStepAssigneeUserName string `json:"filter_current_step_assignee_user_name" query:"filter_current_step_assignee_user_name"` - FilterTaskInstanceName string `json:"filter_task_instance_name" query:"filter_task_instance_name"` - FilterTaskExecuteStartTimeFrom string `json:"filter_task_execute_start_time_from" query:"filter_task_execute_start_time_from"` - FilterTaskExecuteStartTimeTo string `json:"filter_task_execute_start_time_to" query:"filter_task_execute_start_time_to"` + FilterSubject string `json:"filter_subject" query:"filter_subject"` + FilterCreateTimeFrom string `json:"filter_create_time_from" query:"filter_create_time_from"` + FilterCreateTimeTo string `json:"filter_create_time_to" query:"filter_create_time_to"` + FilterCreateUserID string `json:"filter_create_user_id" query:"filter_create_user_id"` + FilterStatus string `json:"filter_status" query:"filter_status" valid:"omitempty,oneof=wait_for_audit wait_for_execution rejected canceled executing exec_failed finished"` + FilterCurrentStepAssigneeUserId string `json:"filter_current_step_assignee_user_id" query:"filter_current_step_assignee_user_id"` + FilterTaskInstanceName string `json:"filter_task_instance_name" query:"filter_task_instance_name"` + FilterTaskExecuteStartTimeFrom string `json:"filter_task_execute_start_time_from" query:"filter_task_execute_start_time_from"` + FilterTaskExecuteStartTimeTo string `json:"filter_task_execute_start_time_to" query:"filter_task_execute_start_time_to"` + FuzzyKeyword string `json:"fuzzy_keyword" query:"fuzzy_keyword"` } // ExportWorkflowV1 @@ -954,11 +973,12 @@ type ExportWorkflowReqV1 struct { // @Param filter_create_time_to query string false "filter create time to" // @Param filter_task_execute_start_time_from query string false "filter_task_execute_start_time_from" // @Param filter_task_execute_start_time_to query string false "filter_task_execute_start_time_to" -// @Param filter_create_user_name query string false "filter create user name" +// @Param filter_create_user_id query string false "filter create user id" // @Param filter_status query string false "filter workflow status" Enums(wait_for_audit,wait_for_execution,rejected,executing,canceled,exec_failed,finished) -// @Param filter_current_step_assignee_user_name query string false "filter current step assignee user name" +// @Param filter_current_step_assignee_user_id query string false "filter current step assignee user id" // @Param filter_task_instance_name query string false "filter instance name" // @Param project_name path string true "project name" +// @Param fuzzy_keyword query string false "fuzzy matching subject/workflow_id/desc" // @Success 200 {file} file "export workflow" // @Router /v1/projects/{project_name}/workflows/exports [get] func ExportWorkflowV1(c echo.Context) error { @@ -977,28 +997,31 @@ func ExportWorkflowV1(c echo.Context) error { // @Router /v1/projects/{project_name}/workflows/{workflow_id}/tasks/terminate [post] func TerminateMultipleTaskByWorkflowV1(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + workflowID := c.Param("workflow_id") + // user, err := controller.GetCurrentUser(c,dms.GetUser) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } s := model.GetStorage() var workflow *model.Workflow - var err error { - var exist bool - workflow, exist, err = s.GetWorkflowDetailByWorkflowID(projectName, workflowID) + workflow, err = dms.GetWorkflowDetailByWorkflowId(projectUid, workflowID, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrWorkflowNoAccess) - } } terminatingTaskIDs := getTerminatingTaskIDs(workflow) // check workflow permission { - err := checkBeforeTasksTermination(c, projectName, workflow, terminatingTaskIDs) + err := checkBeforeTasksTermination(c, projectUid, workflow, terminatingTaskIDs) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1022,30 +1045,35 @@ func TerminateMultipleTaskByWorkflowV1(c echo.Context) error { // @Success 200 {object} controller.BaseRes // @Router /v1/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/terminate [post] func TerminateSingleTaskByWorkflowV1(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + workflowID := c.Param("workflow_id") taskIDStr := c.Param("task_id") taskID, err := strconv.Atoi(taskIDStr) if err != nil { return controller.JSONBaseErrorReq(c, err) } + + // user, err := controller.GetCurrentUser(c,dms.GetUser) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } s := model.GetStorage() var workflow *model.Workflow { - var exist bool - workflow, exist, err = s.GetWorkflowDetailByWorkflowID(projectName, workflowID) + workflow, err = dms.GetWorkflowDetailByWorkflowId(projectUid, workflowID, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, ErrWorkflowNoAccess) - } } // check workflow permission { - err := checkBeforeTasksTermination(c, projectName, workflow, []uint{uint(taskID)}) + err := checkBeforeTasksTermination(c, projectUid, workflow, []uint{uint(taskID)}) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1069,7 +1097,7 @@ func TerminateSingleTaskByWorkflowV1(c echo.Context) error { return c.JSON(http.StatusOK, controller.NewBaseReq(err)) } -func checkBeforeTasksTermination(c echo.Context, projectName string, workflow *model.Workflow, needTerminatedTaskIdList []uint) error { +func checkBeforeTasksTermination(c echo.Context, projectId string, workflow *model.Workflow, needTerminatedTaskIdList []uint) error { needTerminatedTaskIdMap := make(map[uint]struct{}, len(needTerminatedTaskIdList)) for _, taskID := range needTerminatedTaskIdList { needTerminatedTaskIdMap[taskID] = struct{}{} @@ -1096,7 +1124,7 @@ func checkBeforeTasksTermination(c echo.Context, projectName string, workflow *m } err := CheckCurrentUserCanOperateTasks(c, - &model.Project{Name: projectName}, workflow, []uint{model.OP_WORKFLOW_EXECUTE}, needTerminatedTaskIdList) + projectId, workflow, []dmsV1.OpPermissionType{dmsV1.OpPermissionTypeViewOthersWorkflow}, needTerminatedTaskIdList) if err != nil { return err } @@ -1105,13 +1133,11 @@ func checkBeforeTasksTermination(c echo.Context, projectName string, workflow *m } func isTaskCanBeTerminate(s *model.Storage, taskID string) (bool, error) { - task, exist, err := s.GetTaskById(taskID) + task, err := getTaskById(context.Background(), taskID) if err != nil { return false, fmt.Errorf("get task by id failed. taskID=%v err=%v", taskID, err) } - if !exist { - return false, fmt.Errorf("task not exist. taskID=%v", taskID) - } + if task.Instance == nil { return false, fmt.Errorf("task instance is nil. taskID=%v", taskID) } diff --git a/sqle/api/controller/v2/audit_plan.go b/sqle/api/controller/v2/audit_plan.go index 82ee8a96f7..93e966954d 100644 --- a/sqle/api/controller/v2/audit_plan.go +++ b/sqle/api/controller/v2/audit_plan.go @@ -14,8 +14,10 @@ import ( "github.com/actiontech/sqle/sqle/server" "github.com/labstack/echo/v4" + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" "github.com/actiontech/sqle/sqle/api/controller" v1 "github.com/actiontech/sqle/sqle/api/controller/v1" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/model" "github.com/actiontech/sqle/sqle/server/auditplan" @@ -70,9 +72,7 @@ func GetAuditPlans(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") - userName := controller.GetUserName(c) - err := v1.CheckIsProjectMember(userName, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -82,22 +82,11 @@ func GetAuditPlans(c echo.Context) error { offset = req.PageSize * (req.PageIndex - 1) } - currentUser, err := controller.GetCurrentUser(c) - if err != nil { - return err - } - instances, err := s.GetUserCanOpInstancesFromProject(currentUser, projectName, []uint{model.OP_AUDIT_PLAN_VIEW_OTHERS}) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - names := []string{} - for _, instance := range instances { - names = append(names, instance.Name) - } + userId := controller.GetUserID(c) - isManager, err := s.IsProjectManager(currentUser.Name, projectName) + up, err := dms.NewUserPermission(userId, projectUid) if err != nil { - return controller.JSONBaseErrorReq(c, err) + return err } data := map[string]interface{}{ @@ -105,21 +94,26 @@ func GetAuditPlans(c echo.Context) error { "fuzzy_search_audit_plan_name": req.FuzzySearchAuditPlanName, "filter_audit_plan_type": req.FilterAuditPlanType, "filter_audit_plan_instance_name": req.FilterAuditPlanInstanceName, - "current_user_name": currentUser.Name, - "current_user_is_admin": model.DefaultAdminUser == currentUser.Name || isManager, - "filter_project_name": projectName, + "current_user_id": userId, + "current_user_is_admin": up.IsAdmin(), + "filter_project_id": projectUid, "limit": req.PageSize, "offset": offset, } - if len(names) > 0 { - data["accessible_instances_name"] = fmt.Sprintf("'%s'", strings.Join(names, "', '")) + if !up.IsAdmin() { + instanceNames, err := dms.GetInstanceNamesInProjectByIds(c.Request().Context(), projectUid, up.GetInstancesByOP(dmsV1.OpPermissionTypeViewOtherAuditPlan)) + if err != nil { + return err + } + data["accessible_instances_name"] = fmt.Sprintf("\"%s\"", strings.Join(instanceNames, "\",\"")) } + auditPlans, count, err := s.GetAuditPlansByReq(data) if err != nil { return controller.JSONBaseErrorReq(c, err) } - templateNamesInProject, err := s.GetRuleTemplateNamesByProjectName(projectName) + templateNamesInProject, err := s.GetRuleTemplateNamesByProjectId(projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -194,10 +188,13 @@ func GetAuditPlanReportSQLs(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } apName := c.Param("audit_plan_name") - ap, exist, err := v1.GetAuditPlanIfCurrentUserCanAccess(c, projectName, apName, model.OP_AUDIT_PLAN_VIEW_OTHERS) + ap, exist, err := v1.GetAuditPlanIfCurrentUserCanAccess(c, projectUid, apName, dmsV1.OpPermissionTypeViewOtherAuditPlan) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -393,15 +390,22 @@ func PartialSyncAuditPlanSQLs(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") apName := c.Param("audit_plan_name") s := model.GetStorage() - ap, err := v1.CheckProjectAndAuditPlan(s, projectName, apName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } + ap, exist, err := dms.GetAuditPlanWithInstanceFromProjectByName(projectUid, apName, s.GetAuditPlanFromProjectByName) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if !exist { + return controller.JSONBaseErrorReq(c, errors.NewAuditPlanNotExistErr()) + } + l := log.NewEntry() reqSQLs := req.SQLs blackList, err := s.GetBlackListAuditPlanSQLs() @@ -439,15 +443,23 @@ func FullSyncAuditPlanSQLs(c echo.Context) error { if err := controller.BindAndValidateReq(c, req); err != nil { return err } - projectName := c.Param("project_name") apName := c.Param("audit_plan_name") s := model.GetStorage() - ap, err := v1.CheckProjectAndAuditPlan(s, projectName, apName) + + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } + ap, exist, err := s.GetAuditPlanFromProjectByName(projectUid, apName) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if !exist { + return controller.JSONBaseErrorReq(c, errors.NewAuditPlanNotExistErr()) + } + l := log.NewEntry() reqSQLs := req.SQLs blackList, err := s.GetBlackListAuditPlanSQLs() diff --git a/sqle/api/controller/v2/auth.go b/sqle/api/controller/v2/auth.go deleted file mode 100644 index 24a348ac95..0000000000 --- a/sqle/api/controller/v2/auth.go +++ /dev/null @@ -1,35 +0,0 @@ -package v2 - -import ( - "net/http" - - "github.com/actiontech/sqle/sqle/api/controller" - v1 "github.com/actiontech/sqle/sqle/api/controller/v1" - "github.com/labstack/echo/v4" -) - -type UserLoginReqV2 struct { - UserName string `json:"username" form:"username" example:"test" valid:"required"` - Password string `json:"password" form:"password" example:"123456" valid:"required"` -} - -// @Summary 用户登录 -// @Description user login -// @Tags user -// @Id loginV2 -// @Param user body v1.UserLoginReqV1 true "user login request" -// @Success 200 {object} controller.BaseRes -// @router /v2/login [post] -func LoginV2(c echo.Context) error { - req := new(UserLoginReqV2) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - _, err := v1.Login(c, req.UserName, req.Password) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) -} diff --git a/sqle/api/controller/v2/instance.go b/sqle/api/controller/v2/instance.go index eb8fa350ef..2341537a6a 100644 --- a/sqle/api/controller/v2/instance.go +++ b/sqle/api/controller/v2/instance.go @@ -4,14 +4,11 @@ import ( "fmt" "net/http" - "github.com/actiontech/sqle/sqle/driver" - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/api/controller" v1 "github.com/actiontech/sqle/sqle/api/controller/v1" - driverV2 "github.com/actiontech/sqle/sqle/driver/v2" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/utils" + "github.com/labstack/echo/v4" ) @@ -45,253 +42,6 @@ type InstanceResV2 struct { Source string `json:"source" example:"SQLE"` } -type GetInstancesResV2 struct { - controller.BaseRes - Data []InstanceResV2 `json:"data"` - TotalNums uint64 `json:"total_nums"` -} - -// GetInstances get instances -// @Summary 获取实例信息列表 -// @Description get instance info list -// @Id getInstanceListV2 -// @Tags instance -// @Security ApiKeyAuth -// @Param project_name path string true "project name" -// @Param filter_instance_name query string false "filter instance name" -// @Param filter_db_type query string false "filter db type" -// @Param filter_db_host query string false "filter db host" -// @Param filter_db_port query string false "filter db port" -// @Param filter_db_user query string false "filter db user" -// @Param filter_rule_template_name query string false "filter rule template name" -// @Param page_index query uint32 true "page index" -// @Param page_size query uint32 true "size of per page" -// @Success 200 {object} GetInstancesResV2 -// @router /v2/projects/{project_name}/instances [get] -func GetInstances(c echo.Context) error { - req := new(GetInstancesReqV2) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - s := model.GetStorage() - - user, err := controller.GetCurrentUser(c) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - projectName := c.Param("project_name") - err = v1.CheckIsProjectMember(user.Name, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - var offset uint32 - if req.PageIndex >= 1 { - offset = req.PageSize * (req.PageIndex - 1) - } - data := map[string]interface{}{ - "filter_instance_name": req.FilterInstanceName, - "filter_project_name": projectName, - "filter_db_host": req.FilterDBHost, - "filter_db_port": req.FilterDBPort, - "filter_db_user": req.FilterDBUser, - "filter_rule_template_name": req.FilterRuleTemplateName, - "filter_db_type": req.FilterDBType, - "limit": req.PageSize, - "offset": offset, - } - - instances, count, err := s.GetInstancesByReq(data, user) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - templateNamesInProject, err := s.GetRuleTemplateNamesByProjectName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - instancesRes := []InstanceResV2{} - for _, instance := range instances { - var ruleTemplate *RuleTemplateV2 - if len(instance.RuleTemplateNames) >= 1 { - ruleTemplate = &RuleTemplateV2{ - Name: instance.RuleTemplateNames[0], - } - - if !utils.StringsContains(templateNamesInProject, ruleTemplate.Name) { - ruleTemplate.IsGlobalRuleTemplate = true - } - } - - instanceReq := InstanceResV2{ - Name: instance.Name, - DBType: instance.DbType, - Host: instance.Host, - Port: instance.Port, - User: instance.User, - Desc: instance.Desc, - MaintenanceTimes: v1.ConvertPeriodToMaintenanceTimeResV1(instance.MaintenancePeriod), - RuleTemplate: ruleTemplate, - SQLQueryConfig: &v1.SQLQueryConfigResV1{ - MaxPreQueryRows: instance.SqlQueryConfig.MaxPreQueryRows, - QueryTimeoutSecond: instance.SqlQueryConfig.QueryTimeoutSecond, - AuditEnabled: instance.SqlQueryConfig.AuditEnabled, - AllowQueryWhenLessThanAuditLevel: instance.SqlQueryConfig.AllowQueryWhenLessThanAuditLevel, - }, - Source: instance.Source, - } - instancesRes = append(instancesRes, instanceReq) - } - return c.JSON(http.StatusOK, &GetInstancesResV2{ - BaseRes: controller.NewBaseReq(nil), - Data: instancesRes, - TotalNums: count, - }) -} - -type CreateInstanceReqV2 struct { - Name string `json:"instance_name" form:"instance_name" example:"test" valid:"required,name"` - DBType string `json:"db_type" form:"db_type" example:"mysql"` - User string `json:"db_user" form:"db_user" example:"root" valid:"required"` - Host string `json:"db_host" form:"db_host" example:"10.10.10.10" valid:"required,ip_addr|uri|hostname|hostname_rfc1123"` - Port string `json:"db_port" form:"db_port" example:"3306" valid:"required,port"` - Password string `json:"db_password" form:"db_password" example:"123456" valid:"required"` - Desc string `json:"desc" example:"this is a test instance"` - SQLQueryConfig *v1.SQLQueryConfigReqV1 `json:"sql_query_config" form:"sql_query_config"` - MaintenanceTimes []*v1.MaintenanceTimeReqV1 `json:"maintenance_times" form:"maintenance_times"` - RuleTemplateName string `json:"rule_template_name" form:"rule_template_name" valid:"required"` - AdditionalParams []*v1.InstanceAdditionalParamReqV1 `json:"additional_params" form:"additional_params"` -} - -// CreateInstance create instance -// @Summary 添加实例 -// @Description create a instance -// @Id createInstanceV2 -// @Tags instance -// @Security ApiKeyAuth -// @Accept json -// @Param project_name path string true "project name" -// @Param instance body v2.CreateInstanceReqV2 true "add instance" -// @Success 200 {object} controller.BaseRes -// @router /v2/projects/{project_name}/instances [post] -func CreateInstance(c echo.Context) error { - s := model.GetStorage() - req := new(CreateInstanceReqV2) - if err := controller.BindAndValidateReq(c, req); err != nil { - return err - } - - projectName := c.Param("project_name") - - userName := controller.GetUserName(c) - err := v1.CheckIsProjectManager(userName, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrProjectNotExist(projectName)) - } - if project.IsArchived() { - return controller.JSONBaseErrorReq(c, v1.ErrProjectArchived) - } - - _, exist, err = s.GetInstanceByNameAndProjectName(req.Name, projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataExist, fmt.Errorf("instance is exist"))) - } - - if req.DBType == "" { - req.DBType = driverV2.DriverTypeMySQL - } - - maintenancePeriod := v1.ConvertMaintenanceTimeReqV1ToPeriod(req.MaintenanceTimes) - if !maintenancePeriod.SelfCheck() { - return controller.JSONBaseErrorReq(c, v1.ErrWrongTimePeriod) - } - - additionalParams := driver.GetPluginManager().AllAdditionalParams()[req.DBType] - for _, additionalParam := range req.AdditionalParams { - err = additionalParams.SetParamValue(additionalParam.Name, additionalParam.Value) - if err != nil { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, err)) - } - } - - sqlQueryConfig := model.SqlQueryConfig{} - if req.SQLQueryConfig != nil { - sqlQueryConfig = model.SqlQueryConfig{ - MaxPreQueryRows: req.SQLQueryConfig.MaxPreQueryRows, - QueryTimeoutSecond: req.SQLQueryConfig.QueryTimeoutSecond, - AuditEnabled: req.SQLQueryConfig.AuditEnabled, - AllowQueryWhenLessThanAuditLevel: req.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel, - } - } - // default value - if sqlQueryConfig.QueryTimeoutSecond == 0 { - sqlQueryConfig.QueryTimeoutSecond = 10 - } - // default value - if sqlQueryConfig.MaxPreQueryRows == 0 { - sqlQueryConfig.MaxPreQueryRows = 100 - } - - if sqlQueryConfig.AuditEnabled && sqlQueryConfig.AllowQueryWhenLessThanAuditLevel == "" { - sqlQueryConfig.AllowQueryWhenLessThanAuditLevel = string(driverV2.RuleLevelError) - } - - instance := &model.Instance{ - DbType: req.DBType, - Name: req.Name, - User: req.User, - Host: req.Host, - Port: req.Port, - Password: req.Password, - Desc: req.Desc, - AdditionalParams: additionalParams, - MaintenancePeriod: maintenancePeriod, - SqlQueryConfig: sqlQueryConfig, - WorkflowTemplateId: project.WorkflowTemplateId, - ProjectId: project.ID, - Source: model.InstanceSourceSQLE, - } - - var templates []*model.RuleTemplate - template, exist, err := s.GetGlobalAndProjectRuleTemplateByNameAndProjectId(req.RuleTemplateName, project.ID) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrRuleTemplateNotExist) - } - templates = append(templates, template) - - err = v1.CheckInstanceAndRuleTemplateDbType(templates, instance) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - err = s.Save(instance) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - err = s.UpdateInstanceRuleTemplates(instance, templates...) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) -} - type GetInstanceResV2 struct { controller.BaseRes Data InstanceResV2 `json:"data"` @@ -308,23 +58,23 @@ type GetInstanceResV2 struct { // @Success 200 {object} v2.GetInstanceResV2 // @router /v2/projects/{project_name}/instances/{instance_name}/ [get] func GetInstance(c echo.Context) error { - s := model.GetStorage() instanceName := c.Param("instance_name") - projectName := c.Param("project_name") - username := controller.GetUserName(c) - err := v1.CheckIsProjectMember(username, projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } - instance, exist, err := s.GetInstanceDetailByNameAndProjectName(instanceName, projectName) + instance, exist, err := dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, instanceName) if err != nil { return controller.JSONBaseErrorReq(c, err) } if !exist { return controller.JSONBaseErrorReq(c, v1.ErrInstanceNoAccess) } - + ruletemplate, err := model.GetStorage().GetRuleTemplateById(instance.RuleTemplateId) + if err == nil { + instance.RuleTemplates = []model.RuleTemplate{*ruletemplate} + } return c.JSON(http.StatusOK, &GetInstanceResV2{ BaseRes: controller.NewBaseReq(nil), Data: convertInstanceToRes(instance), @@ -350,12 +100,11 @@ func convertInstanceToRes(instance *model.Instance) InstanceResV2 { Source: instance.Source, } - if len(instance.RuleTemplates) > 0 { + if len(instance.RuleTemplates) != 0 { + ruleTemplate := instance.RuleTemplates[0] instanceResV2.RuleTemplate = &RuleTemplateV2{ - Name: instance.RuleTemplates[0].Name, - } - if instance.RuleTemplates[0].ProjectId == model.ProjectIdForGlobalRuleTemplate { - instanceResV2.RuleTemplate.IsGlobalRuleTemplate = true + Name: ruleTemplate.Name, + IsGlobalRuleTemplate: ruleTemplate.ProjectId == model.ProjectIdForGlobalRuleTemplate, } } for _, param := range instance.AdditionalParams { diff --git a/sqle/api/controller/v2/sql_audit.go b/sqle/api/controller/v2/sql_audit.go index d43df89c14..7b629d6ab9 100644 --- a/sqle/api/controller/v2/sql_audit.go +++ b/sqle/api/controller/v2/sql_audit.go @@ -2,12 +2,12 @@ package v2 import ( e "errors" - "fmt" "net/http" parser "github.com/actiontech/mybatis-mapper-2-sql" "github.com/actiontech/sqle/sqle/api/controller" v1 "github.com/actiontech/sqle/sqle/api/controller/v1" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" @@ -68,7 +68,7 @@ func DirectAudit(c echo.Context) error { l := log.NewEntry().WithField(c.Path(), "direct audit failed") - task, err := server.AuditSQLByDBType(l, sql, req.InstanceType, nil, "") + task, err := server.AuditSQLByDBType(l, sql, req.InstanceType) if err != nil { l.Errorf("audit sqls failed: %v", err) return controller.JSONBaseErrorReq(c, v1.ErrDirectAudit) @@ -136,11 +136,16 @@ func DirectAuditFiles(c echo.Context) error { return err } - user := controller.GetUserName(c) - s := model.GetStorage() - if yes, err := s.IsProjectMember(user, req.ProjectName); err != nil { - return controller.JSONBaseErrorReq(c, fmt.Errorf("check privilege failed: %v", err)) - } else if !yes { + userId := controller.GetUserID(c) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), req.ProjectName) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + up, err := dms.NewUserPermission(userId, projectUid) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if !up.IsProjectMember() { return controller.JSONBaseErrorReq(c, errors.New(errors.ErrAccessDeniedError, e.New("you are not the project member"))) } @@ -164,7 +169,7 @@ func DirectAuditFiles(c echo.Context) error { var instance *model.Instance var exist bool if req.InstanceName != nil { - instance, exist, err = s.GetInstanceByNameAndProjectName(*req.InstanceName, req.ProjectName) + instance, exist, err = dms.GetInstanceInProjectByName(c.Request().Context(), projectUid, *req.InstanceName) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -182,7 +187,7 @@ func DirectAuditFiles(c echo.Context) error { if instance != nil && schemaName != "" { task, err = server.DirectAuditByInstance(l, sqls, schemaName, instance) } else { - task, err = server.AuditSQLByDBType(l, sqls, req.InstanceType, nil, "") + task, err = server.AuditSQLByDBType(l, sqls, req.InstanceType) } if err != nil { l.Errorf("audit sqls failed: %v", err) diff --git a/sqle/api/controller/v2/task.go b/sqle/api/controller/v2/task.go index 7ade890e52..2b02eb41de 100644 --- a/sqle/api/controller/v2/task.go +++ b/sqle/api/controller/v2/task.go @@ -5,7 +5,6 @@ import ( "github.com/actiontech/sqle/sqle/api/controller" v1 "github.com/actiontech/sqle/sqle/api/controller/v1" - "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/model" "github.com/labstack/echo/v4" @@ -67,13 +66,11 @@ func GetTaskSQLs(c echo.Context) error { } s := model.GetStorage() taskId := c.Param("task_id") - task, exist, err := s.GetTaskById(taskId) + task, err := v1.GetTaskById(c.Request().Context(), taskId) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) - } + err = v1.CheckCurrentUserCanViewTask(c, task) if err != nil { return controller.JSONBaseErrorReq(c, err) diff --git a/sqle/api/controller/v2/workflow.go b/sqle/api/controller/v2/workflow.go index c7aacd9da9..3e7cab29a3 100644 --- a/sqle/api/controller/v2/workflow.go +++ b/sqle/api/controller/v2/workflow.go @@ -1,23 +1,24 @@ package v2 import ( + "context" _err "errors" "fmt" "net/http" - "strconv" + "strings" "time" - "github.com/actiontech/sqle/sqle/server" - + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + v1 "github.com/actiontech/sqle/sqle/api/controller/v1" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" + "github.com/actiontech/sqle/sqle/model" "github.com/actiontech/sqle/sqle/notification" "github.com/actiontech/sqle/sqle/pkg/im" + "github.com/actiontech/sqle/sqle/server" "github.com/actiontech/sqle/sqle/utils" - "github.com/actiontech/sqle/sqle/model" - - v1 "github.com/actiontech/sqle/sqle/api/controller/v1" - "github.com/actiontech/sqle/sqle/api/controller" "github.com/labstack/echo/v4" ) @@ -47,55 +48,35 @@ type WorkflowStepResV2 struct { // @Success 200 {object} controller.BaseRes // @router /v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/approve [post] func ApproveWorkflowV2(c echo.Context) error { - projectName := c.Param("project_name") - workflowId := c.Param("workflow_id") - - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) + projectUid, err := dms.GetPorjectUIDByName(c.Request().Context(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrProjectNotExist(projectName)) - } - userName := controller.GetUserName(c) - if err := v1.CheckIsProjectMember(userName, project.Name); err != nil { - return controller.JSONBaseErrorReq(c, err) - } + workflowId := c.Param("workflow_id") - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(projectName, workflowId) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } + s := model.GetStorage() - err = v1.CheckCurrentUserCanOperateWorkflow(c, project, workflow, []uint{}) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - stepIdStr := c.Param("workflow_step_id") - stepId, err := v1.FormatStringToInt(stepIdStr) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectUid, workflowId, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - user, err := controller.GetCurrentUser(c) + err = v1.CheckCurrentUserCanOperateWorkflow(c, projectUid, workflow, []dmsV1.OpPermissionType{}) if err != nil { return controller.JSONBaseErrorReq(c, err) } - workflowIdStr := strconv.Itoa(int(workflow.ID)) - workflow, exist, err = s.GetWorkflowDetailById(workflowIdStr) + stepIdStr := c.Param("workflow_step_id") + stepId, err := v1.FormatStringToInt(stepIdStr) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } nextStep := workflow.NextStep() @@ -108,10 +89,10 @@ func ApproveWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - go im.UpdateApprove(workflow.ID, user, model.ApproveStatusAgree, "") + go im.UpdateApprove(workflow.WorkflowId, user, model.ApproveStatusAgree, "") if nextStep != nil { - go im.CreateApprove(strconv.Itoa(int(workflow.ID))) + go im.CreateApprove(string(workflow.ProjectId), workflow.WorkflowId) } return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) @@ -140,26 +121,19 @@ func RejectWorkflowV2(c echo.Context) error { s := model.GetStorage() - projectName := c.Param("project_name") - project, exist, err := s.GetProjectByName(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrProjectNotExist(projectName)) - } workflowID := c.Param("workflow_id") - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(project.Name, workflowID) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectUid, workflowID, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } // RejectWorkflow no need extra operation code for now. - err = v1.CheckCurrentUserCanOperateWorkflow(c, project, workflow, []uint{}) + err = v1.CheckCurrentUserCanOperateWorkflow(c, projectUid, workflow, []dmsV1.OpPermissionType{}) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -170,20 +144,11 @@ func RejectWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - user, err := controller.GetCurrentUser(c) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - workflowIdStr := strconv.Itoa(int(workflow.ID)) - workflow, exist, err = s.GetWorkflowDetailById(workflowIdStr) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } - err = server.CheckUserCanOperateStep(user, workflow, stepId) if err != nil { return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, err)) @@ -202,7 +167,7 @@ func RejectWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - go im.UpdateApprove(workflow.ID, user, model.ApproveStatusRefuse, req.Reason) + go im.UpdateApprove(workflow.WorkflowId, user, model.ApproveStatusRefuse, req.Reason) return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) } @@ -219,17 +184,13 @@ func RejectWorkflowV2(c echo.Context) error { func CancelWorkflowV2(c echo.Context) error { s := model.GetStorage() - projectName := c.Param("project_name") - project, exist, err := s.GetProjectByName(projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrProjectNotExist(projectName)) - } workflowID := c.Param("workflow_id") - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(project.Name, workflowID) + workflow, exist, err := s.GetWorkflowByProjectAndWorkflowId(projectUid, workflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -237,27 +198,22 @@ func CancelWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) } - err = v1.CheckCurrentUserCanOperateWorkflow(c, project, workflow, []uint{}) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - - workflow, err = checkCancelWorkflow(project.Name, workflow.WorkflowId) + err = v1.CheckCurrentUserCanOperateWorkflow(c, projectUid, workflow, []dmsV1.OpPermissionType{}) if err != nil { return controller.JSONBaseErrorReq(c, err) } - user, err := controller.GetCurrentUser(c) + workflow, err = checkCancelWorkflow(projectUid, workflow.WorkflowId) if err != nil { return controller.JSONBaseErrorReq(c, err) } - isManager, err := s.IsProjectManager(user.Name, projectName) + up, err := dms.NewUserPermission(controller.GetUserID(c), projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !(user.ID == workflow.CreateUserId || user.Name == model.DefaultAdminUser || isManager) { + if !(controller.GetUserID(c) == workflow.CreateUserId || up.IsAdmin()) { return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("you are not allow to operate the workflow"))) } @@ -270,19 +226,21 @@ func CancelWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - go im.BatchCancelApprove([]uint{workflow.ID}, user) + user, err := controller.GetCurrentUser(c, dms.GetUser) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + go im.BatchCancelApprove([]string{workflow.WorkflowId}, user) return controller.JSONBaseErrorReq(c, nil) } -func checkCancelWorkflow(projectName, workflowID string) (*model.Workflow, error) { - workflow, exist, err := model.GetStorage().GetWorkflowDetailByWorkflowID(projectName, workflowID) +func checkCancelWorkflow(projectId, workflowID string) (*model.Workflow, error) { + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectId, workflowID, model.GetStorage().GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return nil, err } - if !exist { - return nil, v1.ErrWorkflowNoAccess - } + if !(workflow.Record.Status == model.WorkflowStatusWaitForAudit || workflow.Record.Status == model.WorkflowStatusWaitForExecution || workflow.Record.Status == model.WorkflowStatusReject) { @@ -312,25 +270,20 @@ func BatchCancelWorkflowsV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - projectName := c.Param("project_name") - user, err := controller.GetCurrentUser(c) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if err := v1.CheckIsProjectManager(user.Name, projectName); err != nil { - return controller.JSONBaseErrorReq(c, err) - } - workflows := make([]*model.Workflow, len(req.WorkflowIDList)) - workflowIds := make([]uint, 0, len(req.WorkflowIDList)) + workflowIds := make([]string, 0, len(req.WorkflowIDList)) for i, workflowID := range req.WorkflowIDList { - workflow, err := checkCancelWorkflow(projectName, workflowID) + workflow, err := checkCancelWorkflow(projectUid, workflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } workflows[i] = workflow - workflowIds = append(workflowIds, workflow.ID) + workflowIds = append(workflowIds, workflow.WorkflowId) workflow.Record.Status = model.WorkflowStatusCancel workflow.Record.CurrentWorkflowStepId = 0 } @@ -338,7 +291,10 @@ func BatchCancelWorkflowsV2(c echo.Context) error { if err := model.GetStorage().BatchUpdateWorkflowStatus(workflows); err != nil { return controller.JSONBaseErrorReq(c, err) } - + user, err := controller.GetCurrentUser(c, dms.GetUser) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } go im.BatchCancelApprove(workflowIds, user) return controller.JSONBaseErrorReq(c, nil) @@ -364,31 +320,33 @@ func BatchCompleteWorkflowsV2(c echo.Context) error { return err } - projectName := c.Param("project_name") - user, err := controller.GetCurrentUser(c) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - s := model.GetStorage() - isManager, err := s.IsProjectManager(user.Name, projectName) + user, err := controller.GetCurrentUser(c, dms.GetUser) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + up, err := dms.NewUserPermission(user.GetIDStr(), projectUid) if err != nil { return controller.JSONBaseErrorReq(c, err) } workflows := make([]*model.Workflow, len(req.WorkflowIDList)) for i, workflowID := range req.WorkflowIDList { - workflow, err := checkCanCompleteWorkflow(projectName, workflowID) + workflow, err := checkCanCompleteWorkflow(projectUid, workflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } // 执行上线的人可以决定真的上线这个工单还是直接标记完成 lastStep := workflow.Record.Steps[len(workflow.Record.Steps)-1] - canFinishWorkflow := isManager + canFinishWorkflow := up.IsAdmin() if !canFinishWorkflow { - for _, assignee := range lastStep.Assignees { - if assignee.Name == user.Name { + for _, assignee := range strings.Split(lastStep.Assignees, ",") { + if assignee == user.GetIDStr() { canFinishWorkflow = true break } @@ -400,7 +358,7 @@ func BatchCompleteWorkflowsV2(c echo.Context) error { } lastStep.State = model.WorkflowStepStateApprove - lastStep.OperationUserId = user.ID + lastStep.OperationUserId = user.GetIDStr() workflows[i] = workflow workflow.Record.Status = model.WorkflowStatusFinish workflow.Record.CurrentWorkflowStepId = 0 @@ -408,7 +366,7 @@ func BatchCompleteWorkflowsV2(c echo.Context) error { needExecInstanceRecords := []*model.WorkflowInstanceRecord{} for _, inst := range workflow.Record.InstanceRecords { if !inst.IsSQLExecuted { - inst.ExecutionUserId = user.ID + inst.ExecutionUserId = user.GetIDStr() inst.IsSQLExecuted = true needExecInstanceRecords = append(needExecInstanceRecords, inst) } @@ -421,14 +379,12 @@ func BatchCompleteWorkflowsV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, nil) } -func checkCanCompleteWorkflow(projectName, workflowID string) (*model.Workflow, error) { - workflow, exist, err := model.GetStorage().GetWorkflowDetailByWorkflowID(projectName, workflowID) +func checkCanCompleteWorkflow(projectId, workflowID string) (*model.Workflow, error) { + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectId, workflowID, model.GetStorage().GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return nil, err } - if !exist { - return nil, v1.ErrWorkflowNoAccess - } + if !(workflow.Record.Status == model.WorkflowStatusWaitForExecution) { return nil, errors.New(errors.DataInvalid, fmt.Errorf("workflow status is %s, not allow operate it", workflow.Record.Status)) @@ -448,19 +404,17 @@ func checkCanCompleteWorkflow(projectName, workflowID string) (*model.Workflow, // @Success 200 {object} controller.BaseRes // @router /v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/execute [post] func ExecuteOneTaskOnWorkflowV2(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } workflowID := c.Param("workflow_id") s := model.GetStorage() - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(projectName, workflowID) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectUid, workflowID, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } - - workflowId := fmt.Sprintf("%v", workflow.ID) taskIdStr := c.Param("task_id") taskId, err := v1.FormatStringToInt(taskIdStr) @@ -468,18 +422,11 @@ func ExecuteOneTaskOnWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - workflow, exist, err = s.GetWorkflowDetailById(workflowId) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } - user, err := controller.GetCurrentUser(c) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - err = v1.PrepareForTaskExecution(c, projectName, workflow, user, taskId) + err = v1.PrepareForTaskExecution(c, projectUid, workflow, user, taskId) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -489,10 +436,10 @@ func ExecuteOneTaskOnWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } if !isCan { - return controller.JSONBaseErrorReq(c, fmt.Errorf("task has no need to be executed. taskId=%v workflowId=%v", taskId, workflowId)) + return controller.JSONBaseErrorReq(c, fmt.Errorf("task has no need to be executed. taskId=%v workflowId=%v", taskId, workflow.WorkflowId)) } - err = server.ExecuteWorkflow(workflow, map[uint]uint{uint(taskId): user.ID}) + err = server.ExecuteWorkflow(workflow, map[uint]string{uint(taskId): user.GetIDStr()}) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -529,15 +476,15 @@ type GetWorkflowTasksItemV2 struct { // @Success 200 {object} v2.GetWorkflowTasksResV2 // @router /v2/projects/{project_name}/workflows/{workflow_id}/tasks [get] func GetSummaryOfWorkflowTasksV2(c echo.Context) error { - projectName := c.Param("project_name") - workflowId := c.Param("workflow_id") - - if err := CheckCurrentUserCanViewWorkflow(c, workflowId, projectName); err != nil { + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { return controller.JSONBaseErrorReq(c, err) } + workflowId := c.Param("workflow_id") + s := model.GetStorage() - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(projectName, workflowId) + workflow, exist, err := s.GetWorkflowByProjectAndWorkflowId(projectUid, workflowId) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -545,9 +492,14 @@ func GetSummaryOfWorkflowTasksV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) } + err = v1.CheckCurrentUserCanOperateWorkflow(c, projectUid, workflow, []dmsV1.OpPermissionType{dmsV1.OpPermissionTypeViewOthersWorkflow}) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + queryData := map[string]interface{}{ - "workflow_id": workflowId, - "project_name": projectName, + "workflow_id": workflowId, + "project_id": projectUid, } var taskDetails []*model.WorkflowTasksSummaryDetail @@ -566,6 +518,17 @@ func GetSummaryOfWorkflowTasksV2(c echo.Context) error { } } + for i, detail := range taskDetails { + instance, exist, err := dms.GetInstanceInProjectById(c.Request().Context(), projectUid, detail.InstanceId) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if exist { + taskDetails[i].InstanceName = instance.Name + taskDetails[i].InstanceMaintenancePeriod = instance.MaintenancePeriod + } + } + return c.JSON(http.StatusOK, &GetWorkflowTasksResV2{ BaseRes: controller.NewBaseReq(nil), Data: convertWorkflowToTasksSummaryRes(taskDetails), @@ -576,6 +539,14 @@ func convertWorkflowToTasksSummaryRes(taskDetails []*model.WorkflowTasksSummaryD res := make([]*GetWorkflowTasksItemV2, len(taskDetails)) for i, taskDetail := range taskDetails { + userNames := make([]string, 0) + for _, userId := range strings.Split(taskDetail.CurrentStepAssigneeUserIds.String, ",") { + if userId == "" { + continue + } + userNames = append(userNames, dms.GetUserNameWithDelTag(userId)) + } + res[i] = &GetWorkflowTasksItemV2{ TaskId: taskDetail.TaskId, InstanceName: utils.AddDelTag(taskDetail.InstanceDeletedAt, taskDetail.InstanceName), @@ -583,11 +554,11 @@ func convertWorkflowToTasksSummaryRes(taskDetails []*model.WorkflowTasksSummaryD ExecStartTime: taskDetail.TaskExecStartAt, ExecEndTime: taskDetail.TaskExecEndAt, ScheduleTime: taskDetail.InstanceScheduledAt, - CurrentStepAssigneeUser: taskDetail.CurrentStepAssigneeUsers, + CurrentStepAssigneeUser: userNames, TaskPassRate: taskDetail.TaskPassRate, TaskScore: taskDetail.TaskScore, InstanceMaintenanceTimes: v1.ConvertPeriodToMaintenanceTimeResV1(taskDetail.InstanceMaintenancePeriod), - ExecutionUserName: utils.AddDelTag(taskDetail.ExecutionUserDeletedAt, taskDetail.ExecutionUserName), + ExecutionUserName: dms.GetUserNameWithDelTag(taskDetail.ExecutionUserId), } } @@ -627,43 +598,25 @@ func CreateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - projectName := c.Param("project_name") - - s := model.GetStorage() - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrProjectNotExist(projectName)) - } - if project.IsArchived() { - return controller.JSONBaseErrorReq(c, v1.ErrProjectArchived) - } - - user, err := controller.GetCurrentUser(c) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if err := v1.CheckIsProjectMember(user.Name, project.Name); err != nil { - return controller.JSONBaseErrorReq(c, err) - } + s := model.GetStorage() - workflowId, err := utils.GenUid() + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - _, exist, err = s.GetWorkflowByProjectAndWorkflowName(project.Name, req.Subject) + // dms-todo: 与 dms 生成uid保持一致 + workflowId, err := utils.GenUid() if err != nil { return controller.JSONBaseErrorReq(c, err) } - if exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataExist, fmt.Errorf("workflow[%v] is exist", req.Subject))) - } - _, exist, err = s.GetWorkflowByProjectNameAndWorkflowId(project.Name, workflowId) + _, exist, err := s.GetWorkflowByProjectAndWorkflowId(projectUid, workflowId) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -683,18 +636,39 @@ func CreateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) } - insIdtMap := make(map[uint] /* project instance id */ struct{}, len(project.Instances)) - for _, instance := range project.Instances { - insIdtMap[instance.ID] = struct{}{} + instanceIds := make([]uint64, 0, len(tasks)) + for _, task := range tasks { + instanceIds = append(instanceIds, task.InstanceId) + } + + instances, err := dms.GetInstancesInProjectByIds(c.Request().Context(), projectUid, instanceIds) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + + instanceMap := map[uint64]*model.Instance{} + for _, instance := range instances { + instanceMap[instance.ID] = instance + } + + workflowTemplate, exist, err := s.GetWorkflowTemplateByProjectId(model.ProjectUID(projectUid)) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + if !exist { + return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("the task instance is not bound workflow template"))) } - workflowTemplateId := tasks[0].Instance.WorkflowTemplateId for _, task := range tasks { + if instance, ok := instanceMap[task.InstanceId]; ok { + task.Instance = instance + } + if task.Instance == nil { return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("instance is not exist. taskId=%v", task.ID))) } - if _, ok := insIdtMap[task.InstanceId]; !ok { + if task.Instance.ProjectId != projectUid { return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("instance is not in project. taskId=%v", task.ID))) } @@ -706,7 +680,7 @@ func CreateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, fmt.Errorf("workflow's execute sql is null. taskId=%v", task.ID))) } - if task.CreateUserId != user.ID { + if task.CreateUserId != uint64(user.ID) { return controller.JSONBaseErrorReq(c, errors.New(errors.DataConflict, fmt.Errorf("the task is not created by yourself. taskId=%v", task.ID))) } @@ -714,20 +688,19 @@ func CreateWorkflowV2(c echo.Context) error { if task.SQLSource == model.TaskSQLSourceFromMyBatisXMLFile { return controller.JSONBaseErrorReq(c, v1.ErrForbidMyBatisXMLTask(task.ID)) } - - // all instances must use the same workflow template - if task.Instance.WorkflowTemplateId != workflowTemplateId { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataConflict, - fmt.Errorf("all instances must use the same workflow template"))) - } } // check user role operations { - err = v1.CheckCurrentUserCanCreateWorkflow(user, tasks, projectName) + + canOperationInstance, err := v1.CheckCurrentUserCanCreateWorkflow(c.Request().Context(), projectUid, user, tasks) if err != nil { return controller.JSONBaseErrorReq(c, err) } + if !canOperationInstance { + return controller.JSONBaseErrorReq(c, fmt.Errorf("can't operation instance")) + } + } count, err := s.GetWorkflowRecordCountByTaskIds(taskIds) @@ -738,25 +711,40 @@ func CreateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, errTaskHasBeenUsed) } - template, exist, err := s.GetWorkflowTemplateById(workflowTemplateId) + err = v1.CheckWorkflowCanCommit(workflowTemplate, tasks) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, - fmt.Errorf("the task instance is not bound workflow template"))) - } - err = v1.CheckWorkflowCanCommit(template, tasks) + stepTemplates, err := s.GetWorkflowStepsByTemplateId(workflowTemplate.ID) if err != nil { - return controller.JSONBaseErrorReq(c, err) + return err } - stepTemplates, err := s.GetWorkflowStepsByTemplateId(template.ID) + memberWithPermissions, _, err := dmsobject.ListMembersInProject(c.Request().Context(), controller.GetDMSServerAddress(), dmsV1.ListMembersForInternalReq{ + ProjectUid: projectUid, + PageSize: 999, + PageIndex: 1, + }) if err != nil { return err } - err = s.CreateWorkflowV2(req.Subject, workflowId, req.Desc, user, tasks, stepTemplates, project.ID) + + err = s.CreateWorkflowV2(req.Subject, workflowId, req.Desc, user, tasks, stepTemplates, model.ProjectUID(projectUid), func(tasks []*model.Task) (auditWorkflowUsers, canExecUser [][]*model.User) { + auditWorkflowUsers = make([][]*model.User, len(tasks)) + executorWorkflowUsers := make([][]*model.User, len(tasks)) + for i, task := range tasks { + auditWorkflowUsers[i], err = v1.GetCanOpInstanceUsers(memberWithPermissions, task.Instance, []dmsV1.OpPermissionType{dmsV1.OpPermissionTypeAuditWorkflow}) + if err != nil { + return + } + executorWorkflowUsers[i], err = v1.GetCanOpInstanceUsers(memberWithPermissions, task.Instance, []dmsV1.OpPermissionType{dmsV1.OpPermissionTypeExecuteWorkflow}) + if err != nil { + return + } + } + return auditWorkflowUsers, executorWorkflowUsers + }) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -769,10 +757,9 @@ func CreateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("should exist at least one workflow after create workflow"))) } - workFlowId := strconv.Itoa(int(workflow.ID)) - go notification.NotifyWorkflow(workFlowId, notification.WorkflowNotifyTypeCreate) + go notification.NotifyWorkflow(string(workflow.ProjectId), workflow.WorkflowId, notification.WorkflowNotifyTypeCreate) - go im.CreateApprove(workFlowId) + go im.CreateApprove(string(workflow.ProjectId), workflow.WorkflowId) return c.JSON(http.StatusOK, &CreateWorkflowResV2{ BaseRes: controller.NewBaseReq(nil), @@ -805,19 +792,20 @@ func UpdateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + workflowId := c.Param("workflow_id") s := model.GetStorage() - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(projectName, workflowId) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectUid, workflowId, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, errors.NewDataNotExistErr("workflow not exist")) - } - err = v1.CheckCurrentUserCanOperateWorkflow(c, &model.Project{Name: projectName}, workflow, []uint{}) + err = v1.CheckCurrentUserCanOperateWorkflow(c, projectUid, workflow, []dmsV1.OpPermissionType{}) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -830,7 +818,22 @@ func UpdateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, errors.NewTaskNoExistOrNoAccessErr()) } - user, err := controller.GetCurrentUser(c) + instanceIds := make([]uint64, 0, len(tasks)) + for _, task := range tasks { + instanceIds = append(instanceIds, task.InstanceId) + } + + instances, err := dms.GetInstancesInProjectByIds(c.Request().Context(), projectUid, instanceIds) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + + instanceMap := map[uint64]*model.Instance{} + for _, instance := range instances { + instanceMap[instance.ID] = instance + } + + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -839,6 +842,10 @@ func UpdateWorkflowV2(c echo.Context) error { for i, task := range tasks { taskIds[i] = task.ID + if instance, ok := instanceMap[task.InstanceId]; ok { + task.Instance = instance + } + count, err := s.GetTaskSQLCountByTaskID(task.ID) if err != nil { return controller.JSONBaseErrorReq(c, err) @@ -856,7 +863,7 @@ func UpdateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, v1.ErrInstanceNotExist) } - if user.ID != task.CreateUserId { + if uint64(user.ID) != task.CreateUserId { return controller.JSONBaseErrorReq(c, errors.New(errors.DataConflict, fmt.Errorf("the task is not created by yourself. taskId=%v", task.ID))) } @@ -874,26 +881,17 @@ func UpdateWorkflowV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, errTaskHasBeenUsed) } - workflowIdStr := fmt.Sprintf("%v", workflow.ID) - workflow, exist, err = s.GetWorkflowDetailById(workflowIdStr) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } - if workflow.Record.Status != model.WorkflowStatusReject { return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, fmt.Errorf("workflow status is %s, not allow operate it", workflow.Record.Status))) } - if user.ID != workflow.CreateUserId { + if user.GetIDStr() != workflow.CreateUserId { return controller.JSONBaseErrorReq(c, errors.New(errors.DataNotExist, fmt.Errorf("you are not allow to operate the workflow"))) } - template, exist, err := s.GetWorkflowTemplateById(tasks[0].Instance.WorkflowTemplateId) + template, exist, err := s.GetWorkflowTemplateByProjectId(workflow.ProjectId) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -911,10 +909,9 @@ func UpdateWorkflowV2(c echo.Context) error { if err != nil { return c.JSON(http.StatusOK, controller.NewBaseReq(err)) } - go notification.NotifyWorkflow(workflowIdStr, notification.WorkflowNotifyTypeCreate) + go notification.NotifyWorkflow(string(workflow.ProjectId), workflow.WorkflowId, notification.WorkflowNotifyTypeCreate) - workFlowId := strconv.Itoa(int(workflow.ID)) - go im.CreateApprove(workFlowId) + go im.CreateApprove(string(workflow.ProjectId), workflow.WorkflowId) return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) } @@ -938,26 +935,24 @@ type UpdateWorkflowScheduleReqV2 struct { // @Success 200 {object} controller.BaseRes // @router /v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/schedule [put] func UpdateWorkflowScheduleV2(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + workflowId := c.Param("workflow_id") s := model.GetStorage() - - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(projectName, workflowId) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectUid, workflowId, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } - err = v1.CheckCurrentUserCanOperateWorkflow(c, &model.Project{Name: projectName}, workflow, []uint{}) + err = v1.CheckCurrentUserCanOperateWorkflow(c, projectUid, workflow, []dmsV1.OpPermissionType{}) if err != nil { return controller.JSONBaseErrorReq(c, err) } - workflowId = strconv.Itoa(int(workflow.ID)) - taskId := c.Param("task_id") taskIdUint, err := v1.FormatStringToUint64(taskId) if err != nil { @@ -968,17 +963,11 @@ func UpdateWorkflowScheduleV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, err) } - user, err := controller.GetCurrentUser(c) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } - workflow, exist, err = s.GetWorkflowDetailById(workflowId) - if err != nil { - return controller.JSONBaseErrorReq(c, err) - } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } + currentStep := workflow.CurrentStep() if currentStep == nil { return controller.JSONBaseErrorReq(c, errors.New(errors.DataInvalid, _err.New("workflow current step not found"))) @@ -1013,7 +1002,7 @@ func UpdateWorkflowScheduleV2(c echo.Context) error { "task has been executed"))) } - instance, exist, err := s.GetInstanceById(fmt.Sprintf("%v", curTaskRecord.InstanceId)) + instance, exist, err := dms.GetInstanceInProjectById(c.Request().Context(), projectUid, curTaskRecord.InstanceId) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1025,7 +1014,7 @@ func UpdateWorkflowScheduleV2(c echo.Context) error { return controller.JSONBaseErrorReq(c, v1.ErrWorkflowExecuteTimeIncorrect) } - err = s.UpdateInstanceRecordSchedule(curTaskRecord, user.ID, req.ScheduleTime) + err = s.UpdateInstanceRecordSchedule(curTaskRecord, user.GetIDStr(), req.ScheduleTime) if err != nil { return controller.JSONBaseErrorReq(c, err) } @@ -1044,31 +1033,32 @@ func UpdateWorkflowScheduleV2(c echo.Context) error { // @Success 200 {object} controller.BaseRes // @router /v2/projects/{project_name}/workflows/{workflow_id}/tasks/execute [post] func ExecuteTasksOnWorkflowV2(c echo.Context) error { - projectName := c.Param("project_name") + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name"), true) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } workflowId := c.Param("workflow_id") s := model.GetStorage() - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(projectName, workflowId) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectUid, workflowId, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } - user, err := controller.GetCurrentUser(c) + user, err := controller.GetCurrentUser(c, dms.GetUser) if err != nil { return controller.JSONBaseErrorReq(c, err) } + if err := v1.PrepareForWorkflowExecution(c, projectUid, workflow, user); err != nil { + return err + } - workflowId = fmt.Sprintf("%v", workflow.ID) - - err = server.ExecuteTasksProcess(workflowId, projectName, user) + err = server.ExecuteTasksProcess(workflow.WorkflowId, projectUid, user) if err != nil { return controller.JSONBaseErrorReq(c, err) } - im.UpdateApprove(workflow.ID, user, model.ApproveStatusAgree, "") + im.UpdateApprove(workflow.WorkflowId, user, model.ApproveStatusAgree, "") return c.JSON(http.StatusOK, controller.NewBaseReq(nil)) } @@ -1111,40 +1101,54 @@ type WorkflowResV2 struct { // @Success 200 {object} GetWorkflowResV2 // @router /v2/projects/{project_name}/workflows/{workflow_id}/ [get] func GetWorkflowV2(c echo.Context) error { - projectName := c.Param("project_name") - workflowID := c.Param("workflow_id") - - s := model.GetStorage() - - err := CheckCurrentUserCanViewWorkflow(c, workflowID, projectName) + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return controller.JSONBaseErrorReq(c, err) } + workflowID := c.Param("workflow_id") - workflow, exist, err := s.GetWorkflowByProjectNameAndWorkflowId(projectName, workflowID) + s := model.GetStorage() + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectUid, workflowID, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) - } - - workflowIdStr := strconv.Itoa(int(workflow.ID)) - workflow, exist, err = s.GetWorkflowDetailById(workflowIdStr) + err = v1.CheckCurrentUserCanOperateWorkflow(c, projectUid, workflow, []dmsV1.OpPermissionType{dmsV1.OpPermissionTypeViewOthersWorkflow}) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !exist { - return controller.JSONBaseErrorReq(c, v1.ErrWorkflowNoAccess) + + // TODO 优化为一次批量用户查询,history 记录也许一并处理 + for i := range workflow.Record.Steps { + step := workflow.Record.Steps[i] + AssigneesUserNames := make([]string, 0) + for _, id := range strings.Split(step.Assignees, ",") { + if id == "" { + continue + } + // user, err := dms.GetUser(c.Request().Context(), id, controller.GetDMSServerAddress()) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + AssigneesUserNames = append(AssigneesUserNames, dms.GetUserNameWithDelTag(id)) + } + step.Assignees = strings.Join(AssigneesUserNames, ",") + if workflow.CurrentStep() != nil && step.ID == workflow.CurrentStep().ID { + workflow.Record.CurrentStep = step + } + workflow.Record.Steps[i] = step } - history, err := s.GetWorkflowHistoryById(workflowIdStr) + history, err := s.GetWorkflowHistoryById(workflow.ID) if err != nil { return controller.JSONBaseErrorReq(c, err) } workflow.RecordHistory = history - + // createUser, err := dms.GetUser(c.Request().Context(), workflow.CreateUserId, controller.GetDMSServerAddress()) + // if err != nil { + // return controller.JSONBaseErrorReq(c, err) + // } + // workflow.CreateUser = createUser.Name return c.JSON(http.StatusOK, &GetWorkflowResV2{ BaseRes: controller.NewBaseReq(nil), Data: convertWorkflowToRes(workflow), @@ -1157,7 +1161,7 @@ func convertWorkflowToRes(workflow *model.Workflow) *WorkflowResV2 { WorkflowID: workflow.WorkflowId, Desc: workflow.Desc, Mode: workflow.Mode, - CreateUser: workflow.CreateUser.Name, + CreateUser: dms.GetUserNameWithDelTag(workflow.CreateUserId), CreateTime: &workflow.CreatedAt, } @@ -1190,7 +1194,7 @@ func convertWorkflowRecordToRes(workflow *model.Workflow, record *model.Workflow firstVirtualStep := &WorkflowStepResV2{ Type: stepType, OperationTime: &record.CreatedAt, - OperationUser: workflow.CreateUserName(), + OperationUser: dms.GetUserNameWithDelTag(workflow.CreateUserId), } steps = append(steps, firstVirtualStep) @@ -1231,54 +1235,8 @@ func convertWorkflowStepToRes(step *model.WorkflowStep) *WorkflowStepResV2 { State: step.State, Reason: step.Reason, Users: []string{}, + OperationUser: dms.GetUserNameWithDelTag(step.OperationUserId), } - if step.OperationUser != nil { - stepRes.OperationUser = step.OperationUser.Name - } - if step.Assignees != nil { - for _, user := range step.Assignees { - stepRes.Users = append(stepRes.Users, user.Name) - } - } + stepRes.Users = append(stepRes.Users, strings.Split(step.Assignees, ",")...) return stepRes } - -func CheckCurrentUserCanViewWorkflow(c echo.Context, workflowID, projectName string) error { - userName := controller.GetUserName(c) - s := model.GetStorage() - isManager, err := s.IsProjectManager(userName, projectName) - if err != nil { - return err - } - if userName == model.DefaultAdminUser || isManager { - return nil - } - user, err := controller.GetCurrentUser(c) - if err != nil { - return err - } - workflow, _, err := s.GetWorkflowByProjectNameAndWorkflowId(projectName, workflowID) - if err != nil { - return err - } - - access, err := s.UserCanAccessWorkflow(user, workflow) - if err != nil { - return err - } - if access { - return nil - } - instances, err := s.GetInstancesByWorkflowID(workflow.ID) - if err != nil { - return err - } - ok, err := s.CheckUserHasOpToAnyInstance(user, instances, []uint{model.OP_WORKFLOW_VIEW_OTHERS}) - if err != nil { - return err - } - if ok { - return nil - } - return v1.ErrWorkflowNoAccess -} diff --git a/sqle/api/middleware/jwt.go b/sqle/api/middleware/jwt.go index 9171d8d625..b0d2be792d 100644 --- a/sqle/api/middleware/jwt.go +++ b/sqle/api/middleware/jwt.go @@ -1,14 +1,16 @@ package middleware import ( + "context" "errors" "fmt" "net/http" "strings" + dmsCommonJwt "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/model" "github.com/actiontech/sqle/sqle/utils" - "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) @@ -25,11 +27,10 @@ func JWTTokenAdapter() echo.MiddlewareFunc { } // sqle-token为空时,可能是cookie过期被清理了,希望返回的错误是http.StatusUnauthorized // 但sqle-token为空时jwt返回的错误是http.StatusBadRequest - _, err := c.Cookie("sqle-token") + _, err := c.Cookie("dms-token") if err == http.ErrNoCookie && auth == "" { - return echo.NewHTTPError(http.StatusUnauthorized, "can not find sqle-token") + return echo.NewHTTPError(http.StatusUnauthorized, "can not find dms-token") } - return next(c) } } @@ -38,7 +39,7 @@ func JWTTokenAdapter() echo.MiddlewareFunc { func JWTWithConfig(key interface{}) echo.MiddlewareFunc { c := middleware.DefaultJWTConfig c.SigningKey = key - c.TokenLookup = "cookie:sqle-token,header:Authorization" // tell the middleware where to get token: from cookie and header + c.TokenLookup = "cookie:dms-token,header:Authorization" // tell the middleware where to get token: from cookie and header return middleware.JWTWithConfig(c) } @@ -58,11 +59,15 @@ func ScannerVerifier() echo.MiddlewareFunc { token = parts[1] } - apnInToken, err := utils.ParseAuditPlanName(token) + apnInToken, err := dmsCommonJwt.ParseAuditPlanName(token) + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) + } + + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) } - projectName := c.Param("project_name") apnInParam := c.Param("audit_plan_name") // 由于对生成的JWT Token的负载使用MD5算法进行预处理,因此在验证的时候也需要对param中的apn使用MD5处理 // 为了兼容老版本的JWT Token需要增加不经MD5处理的apnInParam和apnInToken的判断 @@ -70,7 +75,7 @@ func ScannerVerifier() echo.MiddlewareFunc { return echo.NewHTTPError(http.StatusInternalServerError, errAuditPlanMisMatch.Error()) } - apn, apnExist, err := model.GetStorage().GetAuditPlanFromProjectByName(projectName, apnInParam) + apn, apnExist, err := model.GetStorage().GetAuditPlanFromProjectByName(projectUid, apnInParam) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) } diff --git a/sqle/api/middleware/jwt_test.go b/sqle/api/middleware/jwt_test.go index 6d4fdbb439..8b97f89a4c 100644 --- a/sqle/api/middleware/jwt_test.go +++ b/sqle/api/middleware/jwt_test.go @@ -2,13 +2,18 @@ package middleware import ( "database/sql/driver" + "encoding/json" "fmt" + "log" "net/http" "net/http/httptest" "testing" "time" sqlmock "github.com/DATA-DOG/go-sqlmock" + dmsCommon "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + dmsCommonJwt "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/actiontech/sqle/sqle/api/controller" "github.com/actiontech/sqle/sqle/model" "github.com/actiontech/sqle/sqle/utils" "github.com/jinzhu/gorm" @@ -17,12 +22,42 @@ import ( "github.com/stretchr/testify/assert" ) +func mockServer() *httptest.Server { + f := func(w http.ResponseWriter, r *http.Request) { + response := dmsCommon.ListProjectReply{ + Data: []*dmsCommon.ListProject{{ + ProjectUid: "700300", + Name: "default", + Archived: false, + }}, + Total: 1, + } + res, err := json.Marshal(response) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + log.Printf("response err %v", err) + return + } + w.WriteHeader(http.StatusOK) + w.Header().Set("Content-Type", "application/json") + + _, err = w.Write(res) + if err != nil { + log.Printf("response err %v ", err) + } + } + return httptest.NewServer(http.HandlerFunc(f)) +} + func TestScannerVerifier(t *testing.T) { + server := mockServer() + defer server.Close() + controller.InitDMSServerAddress(server.URL) + e := echo.New() - jwt := utils.NewJWT(utils.JWTSecretKey) apName := "test_audit_plan" - projectName := "test_project" + projectUID := "700300" testUser := "test_user" h := func(c echo.Context) error { @@ -37,12 +72,12 @@ func TestScannerVerifier(t *testing.T) { res := httptest.NewRecorder() ctx := e.NewContext(req, res) ctx.SetParamNames("audit_plan_name", "project_name") - ctx.SetParamValues(apName, projectName) + ctx.SetParamValues(apName, projectUID) return ctx, res } { // test audit plan name don't match the token - token, err := jwt.CreateToken(testUser, time.Now().Add(1*time.Hour).Unix(), utils.WithAuditPlanName(apName)) + token, err := dmsCommonJwt.GenJwtToken(dmsCommonJwt.WithUserName(testUser), dmsCommonJwt.WithExpiredTime(1*time.Hour), dmsCommonJwt.WithAuditPlanName(apName)) assert.NoError(t, err) ctx, _ := newContextFunc(token, fmt.Sprintf("%s_modified", apName)) err = mw(h)(ctx) @@ -50,7 +85,7 @@ func TestScannerVerifier(t *testing.T) { } { // test unknown token - token, err := jwt.CreateToken(testUser, time.Now().Add(1*time.Hour).Unix()) + token, err := dmsCommonJwt.GenJwtToken(dmsCommonJwt.WithUserName(testUser), dmsCommonJwt.WithExpiredTime(1*time.Hour)) assert.NoError(t, err) ctx, _ := newContextFunc(token, apName) err = mw(h)(ctx) @@ -58,14 +93,14 @@ func TestScannerVerifier(t *testing.T) { } { // test audit plan token incorrect - token, err := jwt.CreateToken(testUser, time.Now().Add(1*time.Hour).Unix(), utils.WithAuditPlanName(apName)) + token, err := dmsCommonJwt.GenJwtToken(dmsCommonJwt.WithUserName(testUser), dmsCommonJwt.WithExpiredTime(1*time.Hour), dmsCommonJwt.WithAuditPlanName(apName)) assert.NoError(t, err) mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) assert.NoError(t, err) model.InitMockStorage(mockDB) - mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). - WithArgs(projectName, apName). + mock.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_id = ? AND name = ?))"). + WithArgs(projectUID, apName). WillReturnRows(sqlmock.NewRows([]string{"name", "token"}).AddRow(driver.Value(testUser), "test-token")) mock.ExpectClose() @@ -79,14 +114,14 @@ func TestScannerVerifier(t *testing.T) { } { // test audit plan not found - token, err := jwt.CreateToken(testUser, time.Now().Add(1*time.Hour).Unix(), utils.WithAuditPlanName(apName)) + token, err := dmsCommonJwt.GenJwtToken(dmsCommonJwt.WithUserName(testUser), dmsCommonJwt.WithExpiredTime(1*time.Hour), dmsCommonJwt.WithAuditPlanName(apName)) assert.NoError(t, err) mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) assert.NoError(t, err) model.InitMockStorage(mockDB) - mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). - WithArgs(projectName, apName). + mock.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_id = ? AND name = ?))"). + WithArgs(projectUID, apName). WillReturnError(gorm.ErrRecordNotFound) assert.NoError(t, err) model.InitMockStorage(mockDB) @@ -102,14 +137,14 @@ func TestScannerVerifier(t *testing.T) { } { // test check success - token, err := jwt.CreateToken(testUser, time.Now().Add(1*time.Hour).Unix(), utils.WithAuditPlanName(apName)) + token, err := dmsCommonJwt.GenJwtToken(dmsCommonJwt.WithUserName(testUser), dmsCommonJwt.WithExpiredTime(1*time.Hour), dmsCommonJwt.WithAuditPlanName(apName)) assert.NoError(t, err) mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) assert.NoError(t, err) model.InitMockStorage(mockDB) - mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). - WithArgs(projectName, apName). + mock.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_id = ? AND name = ?))"). + WithArgs(projectUID, apName). WillReturnRows(sqlmock.NewRows([]string{"name", "token"}).AddRow(testUser, token)) mock.ExpectClose() @@ -124,14 +159,14 @@ func TestScannerVerifier(t *testing.T) { } { // test default auth scheme success - token, err := jwt.CreateToken(testUser, time.Now().Add(1*time.Hour).Unix(), utils.WithAuditPlanName(apName)) + token, err := dmsCommonJwt.GenJwtToken(dmsCommonJwt.WithUserName(testUser), dmsCommonJwt.WithExpiredTime(1*time.Hour), dmsCommonJwt.WithAuditPlanName(apName)) assert.NoError(t, err) mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) assert.NoError(t, err) model.InitMockStorage(mockDB) - mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). - WithArgs(projectName, apName). + mock.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_id = ? AND name = ?))"). + WithArgs(projectUID, apName). WillReturnRows(sqlmock.NewRows([]string{"name", "token"}).AddRow(testUser, token)) mock.ExpectClose() @@ -148,11 +183,14 @@ func TestScannerVerifier(t *testing.T) { } func TestScannerVerifierIssue1758(t *testing.T) { + server := mockServer() + defer server.Close() + controller.InitDMSServerAddress(server.URL) e := echo.New() jwt := utils.NewJWT(utils.JWTSecretKey) apName120 := "test_name_length_120_000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - projectName := "default" + projectUid := "700300" userName := "admin" assert.Equal(t, 120, len(apName120)) h := func(c echo.Context) error { @@ -166,18 +204,18 @@ func TestScannerVerifierIssue1758(t *testing.T) { res := httptest.NewRecorder() ctx := e.NewContext(req, res) ctx.SetParamNames("audit_plan_name", "project_name") - ctx.SetParamValues(apName, projectName) + ctx.SetParamValues(apName, projectUid) return ctx, res } { // test check success - token, err := jwt.CreateToken(utils.Md5(userName), time.Now().Add(1*time.Hour).Unix(), utils.WithAuditPlanName(utils.Md5(apName120))) + token, err := dmsCommonJwt.GenJwtToken(dmsCommonJwt.WithUserName(utils.Md5(userName)), dmsCommonJwt.WithExpiredTime(1*time.Hour), dmsCommonJwt.WithAuditPlanName(utils.Md5(apName120))) assert.NoError(t, err) mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) assert.NoError(t, err) model.InitMockStorage(mockDB) - mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). - WithArgs(projectName, apName120). + mock.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_id = ? AND name = ?))"). + WithArgs(projectUid, apName120). WillReturnRows(sqlmock.NewRows([]string{"name", "token"}).AddRow(userName, token)) mock.ExpectClose() @@ -210,8 +248,8 @@ func TestScannerVerifierIssue1758(t *testing.T) { mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) assert.NoError(t, err) model.InitMockStorage(mockDB) - mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). - WithArgs(projectName, apName120). + mock.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_id = ? AND name = ?))"). + WithArgs(projectUid, apName120). WillReturnRows(sqlmock.NewRows([]string{"name", "token"}).AddRow(userName, token)) mock.ExpectClose() diff --git a/sqle/api/middleware/license.go b/sqle/api/middleware/license.go deleted file mode 100644 index d8cd0152dc..0000000000 --- a/sqle/api/middleware/license.go +++ /dev/null @@ -1,8 +0,0 @@ -package middleware - -import "github.com/labstack/echo/v4" - -func LicenseAdapter() echo.MiddlewareFunc { - //nolint:typecheck - return licenseAdapter() -} diff --git a/sqle/api/middleware/license_qa.go b/sqle/api/middleware/license_qa.go deleted file mode 100644 index 155b471f0b..0000000000 --- a/sqle/api/middleware/license_qa.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build !release -// +build !release - -package middleware - -import ( - "github.com/labstack/echo/v4" -) - -func licenseAdapter() echo.MiddlewareFunc { - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - return next(c) - } - } -} diff --git a/sqle/api/middleware/permission.go b/sqle/api/middleware/permission.go new file mode 100644 index 0000000000..e866e83377 --- /dev/null +++ b/sqle/api/middleware/permission.go @@ -0,0 +1,77 @@ +package middleware + +import ( + "context" + "net/http" + + dmsJWT "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/dms" + "github.com/labstack/echo/v4" +) + +// AdminUserAllowed is a `echo` middleware, only allow admin user to access next. +func AdminUserAllowed() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + uid, err := dmsJWT.GetUserUidStrFromContextWithOldJwt(c) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + up, err := dms.NewUserPermission(uid, "700300" /*TODO 支持不传空间 */) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + if up.IsAdmin() { + return next(c) + } + return echo.NewHTTPError(http.StatusForbidden) + } + } +} + +func ProjectAdminUserAllowed() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + uid, err := dmsJWT.GetUserUidStrFromContextWithOldJwt(c) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + up, err := dms.NewUserPermission(uid, projectUid) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + if up.IsAdmin() || up.IsProjectAdmin() { + return next(c) + } + return echo.NewHTTPError(http.StatusForbidden) + } + } +} + +func ProjectMemberAllowed() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + uid, err := dmsJWT.GetUserUidStrFromContextWithOldJwt(c) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + projectUid, err := dms.GetPorjectUIDByName(context.TODO(), c.Param("project_name")) + if err != nil { + return controller.JSONBaseErrorReq(c, err) + } + up, err := dms.NewUserPermission(uid, projectUid) + if err != nil { + return echo.NewHTTPError(http.StatusForbidden) + } + if up.IsAdmin() || up.IsProjectAdmin() || up.IsProjectMember() { + return next(c) + } + return echo.NewHTTPError(http.StatusForbidden) + } + } +} diff --git a/sqle/api/middleware/verify_user.go b/sqle/api/middleware/verify_user.go index b346b0c71f..73e3865768 100644 --- a/sqle/api/middleware/verify_user.go +++ b/sqle/api/middleware/verify_user.go @@ -1,26 +1,27 @@ package middleware import ( + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + dmsJWT "github.com/actiontech/dms/pkg/dms-common/api/jwt" + dmsObject "github.com/actiontech/dms/pkg/dms-common/dmsobject" "github.com/actiontech/sqle/sqle/api/controller" "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/model" - "github.com/labstack/echo/v4" ) func VerifyUserIsDisabled() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { - userName := controller.GetUserName(c) - user, isExist, err := model.GetStorage().GetUserByName(userName) + uid, err := dmsJWT.GetUserUidStrFromContextWithOldJwt(c) if err != nil { return controller.JSONBaseErrorReq(c, err) } - if !isExist { - return controller.JSONBaseErrorReq(c, errors.NewDataInvalidErr("user is not exist")) + user, err := dmsObject.GetUser(c.Request().Context(), uid, controller.GetDMSServerAddress()) + if err != nil { + return controller.JSONBaseErrorReq(c, err) } - if user.IsDisabled() { - return controller.JSONBaseErrorReq(c, errors.NewUserDisabledErr("current user is disabled")) + if user.Stat != v1.StatOK { + return controller.JSONBaseErrorReq(c, errors.NewUserDisabledErr("current user status is %s", user.Stat)) } return next(c) } diff --git a/sqle/cmd/sqled/gen_secret_pass.go b/sqle/cmd/sqled/gen_secret_pass.go index 6074981b0b..f147543b66 100644 --- a/sqle/cmd/sqled/gen_secret_pass.go +++ b/sqle/cmd/sqled/gen_secret_pass.go @@ -5,16 +5,15 @@ import ( "io/ioutil" "os" + dmsCommonAes "github.com/actiontech/dms/pkg/dms-common/pkg/aes" "github.com/actiontech/sqle/sqle/config" - "github.com/actiontech/sqle/sqle/utils" - "github.com/spf13/cobra" yaml "gopkg.in/yaml.v2" ) func genSecretPasswordCmd() *cobra.Command { run := func() error { - var cfg = &config.Config{} + var cfg = &config.SqleOptions{} if configPath != "" { b, err := ioutil.ReadFile(configPath) if err != nil { @@ -25,23 +24,23 @@ func genSecretPasswordCmd() *cobra.Command { return fmt.Errorf("unmarshal config file error %v", err) } - secretKey := cfg.Server.SqleCnf.SecretKey + secretKey := cfg.SecretKey if secretKey != "" { - if err := utils.SetSecretKey([]byte(secretKey)); err != nil { + if err = dmsCommonAes.ResetAesSecretKey(secretKey); err != nil { return fmt.Errorf("set secret key error, %v, check your secret key in config file", err) } } - password := cfg.Server.DBCnf.MysqlCnf.Password + password := cfg.Service.Database.Password if password == "" { return fmt.Errorf("mysql_password is empty") } - secretPassword, err := utils.AesEncrypt(password) + secretPassword, err := dmsCommonAes.AesEncrypt(password) if err != nil { return fmt.Errorf("gen secret password error, %d", err) } - cfg.Server.DBCnf.MysqlCnf.SecretPassword = secretPassword - cfg.Server.DBCnf.MysqlCnf.Password = "" + cfg.Service.Database.SecretPassword = secretPassword + cfg.Service.Database.Password = "" } else { return fmt.Errorf("--config is required") } diff --git a/sqle/cmd/sqled/sqled.go b/sqle/cmd/sqled/sqled.go index 838b509546..af106d0795 100644 --- a/sqle/cmd/sqled/sqled.go +++ b/sqle/cmd/sqled/sqled.go @@ -5,11 +5,11 @@ import ( "io/ioutil" "os" + dmsCommonConf "github.com/actiontech/dms/pkg/dms-common/conf" sqled "github.com/actiontech/sqle/sqle" "github.com/actiontech/sqle/sqle/config" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/utils" - "github.com/spf13/cobra" yaml "gopkg.in/yaml.v2" ) @@ -17,7 +17,7 @@ import ( var version string var port int -//var user string +// var user string var mysqlUser string var mysqlPass string var mysqlHost string @@ -77,7 +77,7 @@ func main() { } func run(cmd *cobra.Command, _ []string) error { - var cfg = &config.Config{} + var cfg = &config.Options{} // read config from file first, then read from cmd args. if configPath != "" { @@ -89,28 +89,29 @@ func run(cmd *cobra.Command, _ []string) error { if err != nil { return fmt.Errorf("unmarshal config file error %v", err) } - } else { mysqlPass, err := utils.DecodeString(mysqlPass) if err != nil { return fmt.Errorf("decode mysql password to string error : %v", err) } - cfg = &config.Config{ - Server: config.Server{ - SqleCnf: config.SqleConfig{ - SqleServerPort: port, + cfg = &config.Options{ + SqleOptions: config.SqleOptions{ + BaseOptions: dmsCommonConf.BaseOptions{ + APIServiceOpts: &dmsCommonConf.APIServerOpts{ + Port: port, + EnableHttps: httpsEnable, + CertFilePath: certFilePath, + KeyFilePath: keyFilePath, + }, + }, + Service: config.SeviceOpts{ AutoMigrateTable: autoMigrateTable, DebugLog: debug, LogPath: logPath, LogMaxSizeMB: logMaxSizeMB, LogMaxBackupNumber: logMaxBackupNumber, - EnableHttps: httpsEnable, - CertFilePath: certFilePath, - KeyFilePath: keyFilePath, PluginPath: pluginPath, - }, - DBCnf: config.DatabaseConfig{ - MysqlCnf: config.MysqlConfig{ + Database: config.Database{ Host: mysqlHost, Port: mysqlPort, User: mysqlUser, @@ -132,5 +133,5 @@ func run(cmd *cobra.Command, _ []string) error { os.Remove(pidFile) }() } - return sqled.Run(cfg) + return sqled.Run(&cfg.SqleOptions) } diff --git a/sqle/common/instance.go b/sqle/common/instance.go index bfc50989b6..d198f35c60 100644 --- a/sqle/common/instance.go +++ b/sqle/common/instance.go @@ -23,7 +23,7 @@ func CheckInstanceIsConnectable(instance *model.Instance) error { return nil } -func CheckDeleteInstance(instanceId uint) error { +func CheckDeleteInstance(instanceId int64) error { s := model.GetStorage() isUnFinished, err := s.IsWorkflowUnFinishedByInstanceId(instanceId) diff --git a/sqle/config/config.go b/sqle/config/config.go index 38085d26b8..03159e3bf6 100644 --- a/sqle/config/config.go +++ b/sqle/config/config.go @@ -1,37 +1,29 @@ package config -type Config struct { - Server Server `yaml:"server"` -} +import dmsCommonConf "github.com/actiontech/dms/pkg/dms-common/conf" -type Server struct { - SqleCnf SqleConfig `yaml:"sqle_config"` - DBCnf DatabaseConfig `yaml:"db_config"` - SQLQueryConfig SQLQueryConfig `yaml:"sql_query_config"` - PluginConfig []PluginConfig `yaml:"plugin_config"` +type Options struct { + SqleOptions SqleOptions `yaml:"sqle"` } - -type SqleConfig struct { - ServerId string `yaml:"server_id"` - EnableClusterMode bool `yaml:"enable_cluster_mode"` - SqleServerPort int `yaml:"server_port"` - EnableHttps bool `yaml:"enable_https"` - CertFilePath string `yaml:"cert_file_path"` - KeyFilePath string `yaml:"key_file_path"` - AutoMigrateTable bool `yaml:"auto_migrate_table"` - DebugLog bool `yaml:"debug_log"` - LogPath string `yaml:"log_path"` - LogMaxSizeMB int `yaml:"log_max_size_mb"` - LogMaxBackupNumber int `yaml:"log_max_backup_number"` - PluginPath string `yaml:"plugin_path"` - SecretKey string `yaml:"secret_key"` +type SqleOptions struct { + dmsCommonConf.BaseOptions `yaml:",inline"` + DMSServerAddress string `yaml:"dms_server_address"` + Service SeviceOpts `yaml:"service"` } -type DatabaseConfig struct { - MysqlCnf MysqlConfig `yaml:"mysql_cnf"` +type SeviceOpts struct { + EnableClusterMode bool `yaml:"enable_cluster_mode"` + AutoMigrateTable bool `yaml:"auto_migrate_table"` + DebugLog bool `yaml:"debug_log"` + LogPath string `yaml:"log_path"` + LogMaxSizeMB int `yaml:"log_max_size_mb"` + LogMaxBackupNumber int `yaml:"log_max_backup_number"` + PluginPath string `yaml:"plugin_path"` + Database Database `yaml:"database"` + PluginConfig []PluginConfig `yaml:"plugin_config"` } -type MysqlConfig struct { +type Database struct { Host string `yaml:"mysql_host"` Port string `yaml:"mysql_port"` User string `yaml:"mysql_user"` @@ -40,14 +32,6 @@ type MysqlConfig struct { Schema string `yaml:"mysql_schema"` } -type SQLQueryConfig struct { - EnableHttps bool `yaml:"enable_https"` - CloudBeaverHost string `yaml:"cloud_beaver_host"` - CloudBeaverPort string `yaml:"cloud_beaver_port"` - CloudBeaverAdminUser string `yaml:"cloud_beaver_admin_user"` - CloudBeaverAdminPassword string `yaml:"cloud_beaver_admin_password"` -} - type PluginConfig struct { PluginName string `yaml:"plugin_name"` CMD string `yaml:"cmd"` diff --git a/sqle/dms/common.go b/sqle/dms/common.go new file mode 100644 index 0000000000..8d57d969c6 --- /dev/null +++ b/sqle/dms/common.go @@ -0,0 +1,215 @@ +package dms + +import ( + "context" + "fmt" + "strconv" + "strings" + "time" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + dmsRegister "github.com/actiontech/dms/pkg/dms-common/register" + "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/config" + "github.com/actiontech/sqle/sqle/log" + "github.com/actiontech/sqle/sqle/model" +) + +func GetAllUsers(ctx context.Context, dmsAddr string) ([]*model.User, error) { + ret := make([]*model.User, 0) + for pageIndex, pageSize := 1, 10; ; pageIndex++ { + users, _, err := dmsobject.ListUsers(ctx, controller.GetDMSServerAddress(), dmsV1.ListUserReq{PageSize: uint32(pageSize), PageIndex: uint32(pageIndex), FilterDeletedUser: true}) + if err != nil { + return nil, err + } + for _, user := range users { + ret = append(ret, convertListUserToModel(user)) + } + if len(users) < pageSize { + break + } + } + return ret, nil +} + +func GetMapUsers(ctx context.Context, userUid []string, dmsAddr string) (map[string] /*user_id*/ *model.User, error) { + users, err := GetUsers(ctx, userUid, dmsAddr) + if err != nil { + return nil, err + } + ret := make(map[string]*model.User) + for _, user := range users { + ret[user.GetIDStr()] = user + } + if len(users) == 0 { + return nil, fmt.Errorf("cant't find any users") + } + return ret, nil +} + +func GetUsers(ctx context.Context, userUid []string, dmsAddr string) ([]*model.User, error) { + users, _, err := dmsobject.ListUsers(ctx, controller.GetDMSServerAddress(), dmsV1.ListUserReq{PageSize: 999, PageIndex: 1, FilterDeletedUser: true, FilterByUids: strings.Join(userUid, ",")}) + if err != nil { + return nil, err + } + ret := make([]*model.User, 0) + for _, user := range users { + ret = append(ret, convertListUserToModel(user)) + } + return ret, nil +} + +func convertListUserToModel(user *dmsV1.ListUser) *model.User { + id, _ := strconv.Atoi(user.UserUid) + model_ := model.Model{ID: uint(id)} + if user.IsDeleted { + // 仅记录为已删除 + model_.DeletedAt = &time.Time{} + } + ret := &model.User{ + Model: model_, + Name: user.Name, + Email: user.Email, + Phone: user.Phone, + WeChatID: user.WxID, + } + if user.Stat != dmsV1.StatOK { + ret.Stat = 1 + } + return ret +} + +func GetUser(ctx context.Context, userUid string, dmsAddr string) (*model.User, error) { + dmsUser, err := dmsobject.GetUser(ctx, userUid, dmsAddr) + if err != nil { + return nil, err + } + return convertUserToModel(dmsUser), nil + +} + +func convertUserToModel(user *dmsV1.GetUser) *model.User { + id, _ := strconv.Atoi(user.UserUid) + model_ := model.Model{ID: uint(id)} + ret := &model.User{ + Model: model_, + Name: user.Name, + Email: user.Email, + Phone: user.Phone, + WeChatID: user.WxID, + } + if user.Stat != dmsV1.StatOK { + ret.Stat = 1 + } + return ret +} + +// dms-todo: 1. 缓存 user 信息;2. 后续考虑所有需要name的接口返回 user id + name 组合的形式 +func GetUserNameWithDelTag(userId string) string { + if userId == "" { + return "" + } + users, _, err := dmsobject.ListUsers(context.TODO(), controller.GetDMSServerAddress(), dmsV1.ListUserReq{PageSize: 1, PageIndex: 1, FilterDeletedUser: true, FilterByUids: userId}) + if err != nil { + log.NewEntry().WithField("user_id", userId).Errorln("fail to get user from dms") + return "" + } + if len(users) == 0 { + return "" + } + user := users[0] + + if user.IsDeleted { + return fmt.Sprintf("%s[x]", user.Name) + } + return user.Name +} + +// dms-todo: 临时方案 +func GetPorjectUIDByName(ctx context.Context, projectName string, needActive ...bool) (projectUID string, err error) { + project, err := GetPorjectByName(ctx, projectName) + if err != nil { + return "", err + } + + if len(needActive) == 1 && needActive[0] && project.Archived { + return "", fmt.Errorf("project is archived") + } + return project.ProjectUid, nil +} + +func GetPorjectByName(ctx context.Context, projectName string) (project *dmsV1.ListProject, err error) { + ret, total, err := dmsobject.ListProjects(ctx, controller.GetDMSServerAddress(), dmsV1.ListProjectReq{ + PageSize: 1, + PageIndex: 1, + FilterByName: projectName, + }) + if err != nil { + return nil, err + } + if total == 0 || len(ret) == 0 { + return nil, fmt.Errorf("project %s not found", projectName) + } + + return ret[0], nil +} + +func GetProjects() ([]string, error) { + projectIds := make([]string, 0) + projects, _, err := dmsobject.ListProjects(context.Background(), controller.GetDMSServerAddress(), dmsV1.ListProjectReq{ + PageSize: 9999, + PageIndex: 1, + }) + if err != nil { + return nil, err + } + for _, namespce := range projects { + projectIds = append(projectIds, namespce.ProjectUid) + } + return projectIds, nil +} + +func RegisterAsDMSTarget(sqleConfig *config.SqleOptions) error { + controller.InitDMSServerAddress(sqleConfig.DMSServerAddress) + InitDMSServerAddress(sqleConfig.DMSServerAddress) + ctx := context.Background() + + // 向DMS注册反向代理 + if err := dmsRegister.RegisterDMSProxyTarget(ctx, controller.GetDMSServerAddress(), "sqle", fmt.Sprintf("http://%v:%v", sqleConfig.APIServiceOpts.Addr, sqleConfig.APIServiceOpts.Port) /* TODO https的处理*/, config.Version, []string{"/sqle/v"}); nil != err { + return fmt.Errorf("failed to register dms proxy target: %v", err) + } + // 注册校验接口 + if err := dmsRegister.RegisterDMSPlugin(ctx, controller.GetDMSServerAddress(), &dmsV1.Plugin{ + Name: "sqle", + OperateDataResourceHandleUrl: fmt.Sprintf("http://%s:%d/%s/%s", sqleConfig.APIServiceOpts.Addr, sqleConfig.APIServiceOpts.Port, "v1", "data_resource/handle"), + }); err != nil { + return fmt.Errorf("failed to register dms plugin for operation data source handle") + } + + return nil +} + +func ListProjectUserTips(ctx context.Context, projectUid string) (users []*model.User, err error) { + dmsUsers, _, err := dmsobject.ListMembersInProject(ctx, controller.GetDMSServerAddress(), dmsV1.ListMembersForInternalReq{ + PageSize: 999, + PageIndex: 1, + ProjectUid: projectUid, + }) + if err != nil { + return nil, fmt.Errorf("get user from dms error: %v", err) + } + + for _, dmsUser := range dmsUsers { + id, err := strconv.Atoi(dmsUser.User.Uid) + if err != nil { + return nil, err + } + model_ := model.Model{ID: uint(id)} + users = append(users, &model.User{ + Model: model_, + Name: dmsUser.User.Name, + }) + } + return users, nil +} diff --git a/sqle/dms/instance.go b/sqle/dms/instance.go new file mode 100644 index 0000000000..60c39cee63 --- /dev/null +++ b/sqle/dms/instance.go @@ -0,0 +1,469 @@ +package dms + +import ( + "context" + "fmt" + "strconv" + "time" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + dmsCommonAes "github.com/actiontech/dms/pkg/dms-common/pkg/aes" + "github.com/actiontech/sqle/sqle/errors" + "github.com/actiontech/sqle/sqle/model" + "github.com/actiontech/sqle/sqle/pkg/params" +) + +func getInstances(ctx context.Context, req dmsV1.ListDBServiceReq) ([]*model.Instance, error) { + var ret = make([]*model.Instance, 0) + + var limit, pageIndex uint32 = 20, 1 + + for ; ; pageIndex++ { + req.PageIndex = pageIndex + req.PageSize = limit + + dbServices, _, err := func() ([]*dmsV1.ListDBService, int64, error) { + newCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + return dmsobject.ListDbServices(newCtx, GetDMSServerAddress(), req) + }() + + if err != nil { + return nil, fmt.Errorf("get instances from dms error: %v", err) + } + + for _, item := range dbServices { + if item.SQLEConfig == nil || item.SQLEConfig.RuleTemplateID == "" { + continue + } + + instance, err := convertInstance(item) + if err != nil { + return nil, fmt.Errorf("convert instance error: %v", err) + } + + ret = append(ret, instance) + } + + if len(dbServices) < int(limit) { + break + } + } + + return ret, nil +} + +func getInstance(ctx context.Context, req dmsV1.ListDBServiceReq) (*model.Instance, bool, error) { + newCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + dbServices, total, err := dmsobject.ListDbServices(newCtx, GetDMSServerAddress(), req) + + if err != nil { + return nil, false, fmt.Errorf("get instances from dms error: %v", err) + } + + if total == 0 { + return nil, false, nil + } + + instance, err := convertInstance(dbServices[0]) + if err != nil { + return nil, false, fmt.Errorf("convert instance error: %v", err) + } + + return instance, true, nil +} + +func convertInstance(instance *dmsV1.ListDBService) (*model.Instance, error) { + instanceId, err := strconv.ParseInt(instance.DBServiceUid, 0, 64) + if err != nil { + return nil, err + } + + ruleTemplateId, err := strconv.ParseInt(instance.SQLEConfig.RuleTemplateID, 0, 64) + if err != nil { + return nil, err + } + + var maintenancePeriod = make(model.Periods, 0) + for _, item := range instance.MaintenanceTimes { + maintenancePeriod = append(maintenancePeriod, &model.Period{ + StartHour: item.MaintenanceStartTime.Hour, + StartMinute: item.MaintenanceStartTime.Minute, + EndHour: item.MaintenanceStopTime.Hour, + EndMinute: item.MaintenanceStopTime.Minute, + }) + } + + decryptPassword, err := dmsCommonAes.AesDecrypt(instance.Password) + if err != nil { + return nil, err + } + + additionalParams := make(params.Params, 0, len(instance.AdditionalParams)) + for _, item := range instance.AdditionalParams { + additionalParams = append(additionalParams, ¶ms.Param{ + Key: item.Name, + Value: item.Value, + Desc: item.Description, + Type: params.ParamType(item.Type), + }) + } + + sqlQueryConfig := model.SqlQueryConfig{} + if instance.SQLEConfig != nil { + sqlQueryConfig = model.SqlQueryConfig{ + MaxPreQueryRows: instance.SQLEConfig.SQLQueryConfig.MaxPreQueryRows, + QueryTimeoutSecond: instance.SQLEConfig.SQLQueryConfig.QueryTimeoutSecond, + AuditEnabled: instance.SQLEConfig.SQLQueryConfig.AuditEnabled, + AllowQueryWhenLessThanAuditLevel: string(instance.SQLEConfig.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel), + } + } + + return &model.Instance{ + ID: uint64(instanceId), + Name: instance.Name, + DbType: instance.DBType, + RuleTemplateId: uint64(ruleTemplateId), + RuleTemplateName: instance.SQLEConfig.RuleTemplateName, + ProjectId: instance.ProjectUID, + MaintenancePeriod: maintenancePeriod, + Host: instance.Host, + Port: instance.Port, + User: instance.User, + Password: decryptPassword, + Desc: instance.Desc, + AdditionalParams: additionalParams, + SqlQueryConfig: sqlQueryConfig, + }, nil +} + +func GetInstancesInProject(ctx context.Context, projectUid string) ([]*model.Instance, error) { + return getInstances(ctx, dmsV1.ListDBServiceReq{ + ProjectUid: projectUid, + }) +} + +func GetInstancesInProjectByType(ctx context.Context, projectUid, dbType string) ([]*model.Instance, error) { + return getInstances(ctx, dmsV1.ListDBServiceReq{ + ProjectUid: projectUid, + FilterByDBType: dbType, + }) +} + +func GetInstancesNameInProjectByRuleTemplateName(ctx context.Context, projectUid, ruleTemplateName string) ([]string, error) { + instances, err := getInstances(ctx, dmsV1.ListDBServiceReq{ + ProjectUid: projectUid, + }) + + if err != nil { + return nil, err + } + + ret := make([]string, 0) + for _, instance := range instances { + if instance.RuleTemplateName == ruleTemplateName { + ret = append(ret, instance.Name) + } + } + + return ret, nil +} + +func GetInstancesNameByRuleTemplateName(ctx context.Context, ruleTemplateName string) ([]string, error) { + instances, err := getInstances(ctx, dmsV1.ListDBServiceReq{}) + + if err != nil { + return nil, err + } + + ret := make([]string, 0) + for _, instance := range instances { + if instance.RuleTemplateName == ruleTemplateName { + ret = append(ret, instance.Name) + } + } + + return ret, nil +} + +func GetInstanceInProjectByName(ctx context.Context, projectUid, name string) (*model.Instance, bool, error) { + if len(projectUid) == 0 || len(name) == 0 { + return nil, false, nil + } + + return getInstance(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + FilterByName: name, + ProjectUid: projectUid, + }) +} + +func GetInstancesInProjectByNames(ctx context.Context, projectUid string, names []string) (instances []*model.Instance, err error) { + for _, name := range names { + instance, isExist, err := getInstance(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + FilterByName: name, + ProjectUid: projectUid, + }) + + if err != nil { + return nil, err + } + + if isExist { + instances = append(instances, instance) + } + } + + return instances, err +} + +func GetInstanceNamesInProjectByIds(ctx context.Context, projectUid string, instanceIds []string) ([]string, error) { + ret := make([]string, 0) + for _, instanceId := range instanceIds { + instance, exist, err := getInstance(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + FilterByUID: instanceId, + ProjectUid: projectUid, + }) + + if err != nil { + return nil, err + } + + if exist { + ret = append(ret, instance.Name) + } + } + + return ret, nil +} + +func GetInstanceNamesInProject(ctx context.Context, projectUid string) ([]string, error) { + ret := make([]string, 0) + + instances, err := getInstances(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + ProjectUid: projectUid, + }) + + if err != nil { + return nil, err + } + + for _, instance := range instances { + ret = append(ret, instance.Name) + } + + return ret, nil +} + +func GetInstancesById(ctx context.Context, instanceId uint64) (*model.Instance, bool, error) { + if instanceId == 0 { + return nil, false, nil + } + + return getInstance(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + FilterByUID: strconv.FormatUint(instanceId, 10), + }) +} + +func GetInstancesByIds(ctx context.Context, instanceIds []uint64) ([]*model.Instance, error) { + ret := make([]*model.Instance, 0) + for _, instanceId := range instanceIds { + instance, exist, err := getInstance(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + FilterByUID: strconv.FormatUint(instanceId, 10), + }) + + if err != nil { + return nil, err + } + + if exist { + ret = append(ret, instance) + } + } + + return ret, nil +} + +func GetInstanceIdNameMapByIds(ctx context.Context, instanceIds []uint64) (map[uint64]string, error) { + // todo: remove duplicate instance id + ret := make(map[uint64]string) + for _, instanceId := range instanceIds { + instance, exist, err := getInstance(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + FilterByUID: strconv.FormatUint(instanceId, 10), + }) + + if err != nil { + return nil, err + } + + if exist { + ret[instance.ID] = instance.Name + } + } + + return ret, nil +} + +func GetInstanceInProjectById(ctx context.Context, projectUid string, instanceId uint64) (*model.Instance, bool, error) { + if len(projectUid) == 0 || instanceId == 0 { + return nil, false, nil + } + + return getInstance(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + FilterByUID: strconv.FormatUint(instanceId, 10), + ProjectUid: projectUid, + }) +} + +func GetInstancesInProjectByIds(ctx context.Context, projectUid string, instanceIds []uint64) ([]*model.Instance, error) { + ret := make([]*model.Instance, 0) + for _, instanceId := range instanceIds { + instance, exist, err := getInstance(ctx, dmsV1.ListDBServiceReq{ + PageSize: 1, + FilterByUID: strconv.FormatUint(instanceId, 10), + ProjectUid: projectUid, + }) + + if err != nil { + return nil, err + } + + if exist { + ret = append(ret, instance) + } + } + + return ret, nil +} + +type InstanceTypeCount struct { + DBType string `json:"db_type"` + Count int64 `json:"count"` +} + +func GetInstanceCountGroupType(ctx context.Context) ([]InstanceTypeCount, error) { + instances, err := getInstances(ctx, dmsV1.ListDBServiceReq{}) + + if err != nil { + return nil, err + } + + var typeCountMap = map[string]int64{} + + for _, instance := range instances { + typeCountMap[instance.DbType]++ + } + + ret := make([]InstanceTypeCount, 0, len(typeCountMap)) + for dbType, count := range typeCountMap { + ret = append(ret, InstanceTypeCount{ + DBType: dbType, + Count: count, + }) + } + + return ret, nil +} + +func GetWorkflowDetailByWorkflowId(projectId, workflowId string, fn func(projectId, workflowId string) (*model.Workflow, bool, error)) (*model.Workflow, error) { + workflow, exist, err := fn(projectId, workflowId) + if err != nil { + return nil, err + } + if !exist { + return nil, errors.New(errors.DataNotExist, fmt.Errorf("workflow is not exist or you can't access it")) + } + + instanceIds := make([]uint64, 0, len(workflow.Record.InstanceRecords)) + for _, item := range workflow.Record.InstanceRecords { + instanceIds = append(instanceIds, item.InstanceId) + } + + if len(instanceIds) == 0 { + return workflow, nil + } + + instances, err := GetInstancesInProjectByIds(context.Background(), string(workflow.ProjectId), instanceIds) + if err != nil { + return nil, err + } + instanceMap := map[uint64]*model.Instance{} + for _, instance := range instances { + instanceMap[instance.ID] = instance + } + for i, item := range workflow.Record.InstanceRecords { + if instance, ok := instanceMap[item.InstanceId]; ok { + workflow.Record.InstanceRecords[i].Instance = instance + } + } + + return workflow, nil +} + +func GetAuditPlanWithInstanceFromProjectByName(projectId, name string, fn func(projectId, name string) (*model.AuditPlan, bool, error)) (*model.AuditPlan, bool, error) { + auditPlan, exist, err := fn(projectId, name) + if err != nil { + return nil, false, err + } + if !exist { + return nil, false, nil + } + + instance, exists, err := GetInstanceInProjectByName(context.Background(), projectId, auditPlan.InstanceName) + if err != nil { + return nil, false, err + } + if exists { + auditPlan.Instance = instance + } + return auditPlan, true, nil +} + +func GetActiveAuditPlansWithInstance(fn func() ([]*model.AuditPlan, error)) ([]*model.AuditPlan, error) { + auditPlans, err := fn() + if err != nil { + return nil, err + } + + for i, item := range auditPlans { + // todo dms不支持跨项目查询实例,所以单个查询 + instance, exists, err := GetInstanceInProjectByName(context.Background(), string(item.ProjectId), item.Name) + if err != nil { + continue + } + if exists { + auditPlans[i].Instance = instance + } + } + return auditPlans, nil +} + +func GetAuditPlanWithInstanceById(id uint, fn func(id uint) (*model.AuditPlan, bool, error)) (*model.AuditPlan, bool, error) { + auditPlan, exist, err := fn(id) + if err != nil { + return nil, false, err + } + if !exist { + return nil, false, nil + } + + instance, exists, err := GetInstanceInProjectByName(context.Background(), string(auditPlan.ProjectId), auditPlan.InstanceName) + if err != nil { + return nil, false, err + } + if exists { + auditPlan.Instance = instance + } + return auditPlan, true, nil +} diff --git a/sqle/dms/permission.go b/sqle/dms/permission.go new file mode 100644 index 0000000000..2ce344b124 --- /dev/null +++ b/sqle/dms/permission.go @@ -0,0 +1,123 @@ +package dms + +import ( + "context" + "fmt" + + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/log" + "github.com/ungerik/go-dry" +) + +type UserPermission struct { + userId string + projectId string + isAdmin bool + opPermissionItem []v1.OpPermissionItem +} + +func NewUserPermission(userId, projectId string) (*UserPermission, error) { + opPermissions, isAdmin, err := dmsobject.GetUserOpPermission(context.TODO(), projectId, userId, controller.GetDMSServerAddress()) + if err != nil { + return nil, fmt.Errorf("get user op permission from dms error: %v", err) + } + return &UserPermission{ + userId: userId, + projectId: projectId, + isAdmin: isAdmin, + opPermissionItem: opPermissions, + }, nil +} + +func (p *UserPermission) IsAdmin() bool { + return p.isAdmin +} + +func (p *UserPermission) IsProjectAdmin() bool { + for _, userOpPermission := range p.opPermissionItem { + if userOpPermission.RangeType == v1.OpRangeTypeProject { + return true + } + } + return false +} + +// dms-todo: 1. 判断用户是 project 成员的方式成本高,看是否可以优化. 2. 捕捉错误. +func (p *UserPermission) IsProjectMember() bool { + members, _, err := dmsobject.ListMembersInProject(context.TODO(), controller.GetDMSServerAddress(), v1.ListMembersForInternalReq{PageSize: 999, PageIndex: 1, ProjectUid: p.projectId}) + if err != nil { + log.NewEntry().WithField("project_id", p.projectId).Errorln("fail to list member in project from dms") + return false + } + for _, member := range members { + if member.User.Uid == p.userId { + return true + } + } + return false +} + +func (p *UserPermission) isPermissionMatch(opType v1.OpPermissionType, opTypes ...v1.OpPermissionType) bool { + for i := range opTypes { + if opTypes[i] == opType { + return true + } + } + return false +} + +func (p *UserPermission) CanOpInstanceNoAdmin(instanceId string, OpTypes ...v1.OpPermissionType) bool { + for _, userOpPermission := range p.opPermissionItem { + // 判断是否是数据源权限 + if userOpPermission.RangeType != v1.OpRangeTypeDBService { + continue + } + // 判断权限类型是否一致 + if !p.isPermissionMatch(userOpPermission.OpPermissionType, OpTypes...) { + continue + } + // 判断权限对应的资源内有指定的数据源 + if dry.StringInSlice(instanceId, userOpPermission.RangeUids) { + return true + } + } + return false +} + +func (p *UserPermission) GetInstancesByOP(OpTypes ...v1.OpPermissionType) []string { + instances := []string{} + instanceMap := map[string]struct{}{} + + for _, userOpPermission := range p.opPermissionItem { + // 判断是否是数据源权限 + if userOpPermission.RangeType != v1.OpRangeTypeDBService { + continue + } + // 判断权限类型是否一致 + if !p.isPermissionMatch(userOpPermission.OpPermissionType, OpTypes...) { + continue + } + for _, id := range userOpPermission.RangeUids { + if _, ok := instanceMap[id]; ok { + continue + } + instances = append(instances, id) + instanceMap[id] = struct{}{} + } + } + return instances +} + +func GetAllOpPermissions() []v1.OpPermissionType { + return []v1.OpPermissionType{ + v1.OpPermissionTypeAuditWorkflow, + v1.OpPermissionTypeCreateWorkflow, + v1.OpPermissionTypeExecuteWorkflow, + v1.OpPermissionTypeViewOthersWorkflow, + v1.OpPermissionTypeSaveAuditPlan, + v1.OpPermissionTypeViewOtherAuditPlan, + v1.OpPermissionTypeSQLQuery, + } +} diff --git a/sqle/dms/server.go b/sqle/dms/server.go new file mode 100644 index 0000000000..13dbde5d8e --- /dev/null +++ b/sqle/dms/server.go @@ -0,0 +1,11 @@ +package dms + +var dmsServerAddress string + +func GetDMSServerAddress() string { + return dmsServerAddress +} + +func InitDMSServerAddress(addr string) { + dmsServerAddress = addr +} diff --git a/sqle/docs/docs.go b/sqle/docs/docs.go index 0409bc122a..d23da309c1 100644 --- a/sqle/docs/docs.go +++ b/sqle/docs/docs.go @@ -113,24 +113,6 @@ var doc = `{ } } }, - "/v1/basic_info": { - "get": { - "description": "get sqle basic info", - "tags": [ - "global" - ], - "summary": "获取 sqle 基本信息", - "operationId": "getSQLEInfoV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetSQLEInfoResV1" - } - } - } - } - }, "/v1/company_notice": { "get": { "security": [ @@ -299,101 +281,6 @@ var doc = `{ } } }, - "/v1/configurations/feishu": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get feishu configuration", - "tags": [ - "configuration" - ], - "summary": "获取飞书配置", - "operationId": "getFeishuConfigurationV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetFeishuConfigurationResV1" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update feishu configuration", - "consumes": [ - "application/json" - ], - "tags": [ - "configuration" - ], - "summary": "添加或更新飞书配置", - "operationId": "updateFeishuConfigurationV1", - "parameters": [ - { - "description": "update feishu configuration req", - "name": "param", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateFeishuConfigurationReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/configurations/feishu/test": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "test feishu configuration", - "consumes": [ - "application/json" - ], - "tags": [ - "configuration" - ], - "summary": "测试飞书配置", - "operationId": "testFeishuConfigV1", - "parameters": [ - { - "description": "test feishu configuration req", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.TestFeishuConfigurationReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.TestFeishuConfigResV1" - } - } - } - } - }, "/v1/configurations/feishu_audit": { "get": { "security": [ @@ -489,64 +376,6 @@ var doc = `{ } } }, - "/v1/configurations/ldap": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get LDAP configuration", - "tags": [ - "configuration" - ], - "summary": "获取 LDAP 配置", - "operationId": "getLDAPConfigurationV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetLDAPConfigurationResV1" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update LDAP configuration", - "consumes": [ - "application/json" - ], - "tags": [ - "configuration" - ], - "summary": "添加 LDAP 配置", - "operationId": "updateLDAPConfigurationV1", - "parameters": [ - { - "description": "update LDAP configuration req", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.LDAPConfigurationReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, "/v1/configurations/license": { "get": { "security": [ @@ -661,24 +490,24 @@ var doc = `{ } } }, - "/v1/configurations/oauth2": { + "/v1/configurations/system_variables": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get Oauth2 configuration", + "description": "get system variables", "tags": [ "configuration" ], - "summary": "获取 Oauth2 配置", - "operationId": "getOauth2ConfigurationV1", + "summary": "获取系统变量", + "operationId": "getSystemVariablesV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetOauth2ConfigurationResV1" + "$ref": "#/definitions/v1.GetSystemVariablesResV1" } } } @@ -689,23 +518,23 @@ var doc = `{ "ApiKeyAuth": [] } ], - "description": "update Oauth2 configuration", + "description": "update system variables", "consumes": [ "application/json" ], "tags": [ "configuration" ], - "summary": "修改 Oauth2 配置", - "operationId": "updateOauth2ConfigurationV1", + "summary": "修改系统变量", + "operationId": "updateSystemVariablesV1", "parameters": [ { - "description": "update Oauth2 configuration req", - "name": "conf", + "description": "update system variables request", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.Oauth2ConfigurationReqV1" + "$ref": "#/definitions/v1.UpdateSystemVariablesReqV1" } } ], @@ -719,45 +548,62 @@ var doc = `{ } } }, - "/v1/configurations/oauth2/tips": { + "/v1/custom_rules": { "get": { - "description": "get Oauth2 tips", + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "get all custom rule template", "tags": [ - "configuration" + "rule_template" + ], + "summary": "自定义规则列表", + "operationId": "getCustomRulesV1", + "parameters": [ + { + "type": "string", + "description": "filter db type", + "name": "filter_db_type", + "in": "query" + }, + { + "type": "string", + "description": "filter desc", + "name": "filter_desc", + "in": "query" + } ], - "summary": "获取 Oauth2 基本信息", - "operationId": "getOauth2Tips", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetOauth2TipsResV1" + "$ref": "#/definitions/v1.GetCustomRulesResV1" } } } - } - }, - "/v1/configurations/personalise": { - "patch": { + }, + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update personalise config", + "description": "create custom rule", "tags": [ - "configuration" + "rule_template" ], - "summary": "更新个性化设置", - "operationId": "personalise", + "summary": "添加自定义规则", + "operationId": "createCustomRuleV1", "parameters": [ { - "description": "personalise req", - "name": "conf", + "description": "add custom rule", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.PersonaliseReqV1" + "$ref": "#/definitions/v1.CreateCustomRuleReqV1" } } ], @@ -771,28 +617,25 @@ var doc = `{ } } }, - "/v1/configurations/personalise/logo": { - "post": { + "/v1/custom_rules/{db_type}/rule_types": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "upload logo", - "consumes": [ - "multipart/form-data" - ], + "description": "get rule type by db type", "tags": [ - "configuration" + "rule_template" ], - "summary": "上传Logo", - "operationId": "uploadLogo", + "summary": "获取规则分类", + "operationId": "getRuleTypeByDBTypeV1", "parameters": [ { - "type": "file", - "description": "logo file", - "name": "logo", - "in": "formData", + "type": "string", + "description": "db type", + "name": "db_type", + "in": "query", "required": true } ], @@ -800,58 +643,62 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.UploadLogoResV1" + "$ref": "#/definitions/v1.GetRuleTypeByDBTypeResV1" } } } } }, - "/v1/configurations/smtp": { + "/v1/custom_rules/{rule_id}": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get SMTP configuration", + "description": "get custom rule by rule_id", "tags": [ - "configuration" + "rule_template" + ], + "summary": "获取自定义规则", + "operationId": "getCustomRuleV1", + "parameters": [ + { + "type": "string", + "description": "rule id", + "name": "rule_id", + "in": "path", + "required": true + } ], - "summary": "获取 SMTP 配置", - "operationId": "getSMTPConfigurationV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSMTPConfigurationResV1" + "$ref": "#/definitions/v1.GetCustomRuleResV1" } } } }, - "patch": { + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update SMTP configuration", - "consumes": [ - "application/json" - ], + "description": "delete custom rule", "tags": [ - "configuration" + "rule_template" ], - "summary": "添加 SMTP 配置", - "operationId": "updateSMTPConfigurationV1", + "summary": "删除自定义规则", + "operationId": "deleteCustomRuleV1", "parameters": [ { - "description": "update SMTP configuration req", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateSMTPConfigurationReqV1" - } + "type": "string", + "description": "rule id", + "name": "rule_id", + "in": "path", + "required": true } ], "responses": { @@ -862,32 +709,34 @@ var doc = `{ } } } - } - }, - "/v1/configurations/smtp/test": { - "post": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test SMTP configuration", - "consumes": [ - "application/json" - ], + "description": "update custom rule", "tags": [ - "configuration" + "rule_template" ], - "summary": "测试 邮箱 配置", - "operationId": "testSMTPConfigurationV1", + "summary": "更新自定义规则", + "operationId": "updateCustomRuleV1", "parameters": [ { - "description": "test SMTP configuration req", - "name": "req", + "type": "string", + "description": "rule id", + "name": "rule_id", + "in": "path", + "required": true + }, + { + "description": "update custom rule", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.TestSMTPConfigurationReqV1" + "$ref": "#/definitions/v1.UpdateCustomRuleReqV1" } } ], @@ -895,216 +744,350 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TestSMTPConfigurationResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/configurations/sql_query": { + "/v1/dashboard": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sqle query configuration", + "description": "get dashboard info", + "produces": [ + "application/json" + ], "tags": [ - "configuration" + "dashboard" + ], + "summary": "获取 dashboard 信息", + "operationId": "getDashboardV1", + "parameters": [ + { + "type": "string", + "description": "filter project name", + "name": "filter_project_name", + "in": "query" + } ], - "summary": "获取SQL查询配置信息", - "operationId": "getSQLQueryConfiguration", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSQLQueryConfigurationResV1" + "$ref": "#/definitions/v1.GetDashboardResV1" } } } } }, - "/v1/configurations/system_variables": { + "/v1/operation_records": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get system variables", + "description": "Get operation record list", "tags": [ - "configuration" + "OperationRecord" + ], + "summary": "获取操作记录列表", + "operationId": "getOperationRecordListV1", + "parameters": [ + { + "type": "string", + "description": "filter_operate_time_from", + "name": "filter_operate_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_time_to", + "name": "filter_operate_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_project_name", + "name": "filter_operate_project_name", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy_search_operate_user_name", + "name": "fuzzy_search_operate_user_name", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_type_name", + "name": "filter_operate_type_name", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_action", + "name": "filter_operate_action", + "in": "query" + }, + { + "type": "integer", + "description": "page_index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "page_size", + "name": "page_size", + "in": "query", + "required": true + } ], - "summary": "获取系统变量", - "operationId": "getSystemVariablesV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSystemVariablesResV1" + "$ref": "#/definitions/v1.GetOperationRecordListResV1" } } } - }, - "patch": { + } + }, + "/v1/operation_records/exports": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update system variables", - "consumes": [ - "application/json" - ], + "description": "Export operation record list", "tags": [ - "configuration" + "OperationRecord" ], - "summary": "修改系统变量", - "operationId": "updateSystemVariablesV1", + "summary": "导出操作记录列表", + "operationId": "getExportOperationRecordListV1", "parameters": [ { - "description": "update system variables request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateSystemVariablesReqV1" - } + "type": "string", + "description": "filter_operate_time_from", + "name": "filter_operate_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_time_to", + "name": "filter_operate_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_project_name", + "name": "filter_operate_project_name", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy_search_operate_user_name", + "name": "fuzzy_search_operate_user_name", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_type_name", + "name": "filter_operate_type_name", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_action", + "name": "filter_operate_action", + "in": "query" } ], "responses": { "200": { - "description": "OK", + "description": "get export operation record list", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/configurations/webhook": { + "/v1/operation_records/operation_actions": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow webhook config", + "description": "Get operation action list", "tags": [ - "configuration" + "OperationRecord" ], - "summary": "获取全局工单 WebHook 配置", - "operationId": "getGlobalWorkflowWebHookConfig", + "summary": "获取操作内容列表", + "operationId": "getOperationActionList", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowWebHookConfigResV1" + "$ref": "#/definitions/v1.GetOperationActionListResV1" } } } - }, - "patch": { + } + }, + "/v1/operation_records/operation_type_names": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update webhook config", + "description": "Get operation type name list", "tags": [ - "configuration" - ], - "summary": "更新工单 WebHook 配置", - "operationId": "updateGlobalWebHookConfig", - "parameters": [ - { - "description": "update webhook config", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.WebHookConfigV1" - } - } + "OperationRecord" ], + "summary": "获取操作类型名列表", + "operationId": "GetOperationTypeNameList", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetOperationTypeNamesListResV1" } } } } }, - "/v1/configurations/webhook/test": { - "post": { + "/v1/operations": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test workflow webhook config", + "description": "get permission operations", "tags": [ - "configuration" + "operation" ], - "summary": "测试全局工单 WebHook 配置", - "operationId": "testGlobalWorkflowWebHookConfig", + "summary": "获取权限动作列表", + "operationId": "GetOperationsV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TestWorkflowWebHookConfigResV1" + "$ref": "#/definitions/v1.GetOperationsResV1" } } } } }, - "/v1/configurations/wechat": { + "/v1/projects/{project_name}/audit_plans": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get WeChat configuration", + "description": "get audit plan info list", "tags": [ - "configuration" + "audit_plan" + ], + "summary": "获取扫描任务信息列表", + "operationId": "getAuditPlansV1", + "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "filter audit plan db type", + "name": "filter_audit_plan_db_type", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search audit plan name", + "name": "fuzzy_search_audit_plan_name", + "in": "query" + }, + { + "type": "string", + "description": "filter audit plan type", + "name": "filter_audit_plan_type", + "in": "query" + }, + { + "type": "string", + "description": "filter audit plan instance name", + "name": "filter_audit_plan_instance_name", + "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true + } ], - "summary": "获取 企业微信 配置", - "operationId": "getWeChatConfigurationV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWeChatConfigurationResV1" + "$ref": "#/definitions/v1.GetAuditPlansResV1" } } } }, - "patch": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update WeChat configuration", + "description": "create audit plan", "consumes": [ "application/json" ], "tags": [ - "configuration" + "audit_plan" ], - "summary": "添加 企业微信 配置", - "operationId": "updateWeChatConfigurationV1", + "summary": "添加扫描任务", + "operationId": "createAuditPlanV1", "parameters": [ { - "description": "update WeChat configuration req", - "name": "instance", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "description": "create audit plan", + "name": "audit_plan", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateWeChatConfigurationReqV1" + "$ref": "#/definitions/v1.CreateAuditPlanReqV1" } } ], @@ -1118,99 +1101,115 @@ var doc = `{ } } }, - "/v1/configurations/wechat/test": { - "post": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test WeChat configuration", - "consumes": [ - "application/json" - ], + "description": "get audit plan", "tags": [ - "configuration" + "audit_plan" ], - "summary": "测试 企业微信 配置", - "operationId": "testWeChatConfigurationV1", + "summary": "获取指定扫描任务", + "operationId": "getAuditPlanV1", "parameters": [ { - "description": "test WeChat configuration req", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.TestWeChatConfigurationReqV1" - } + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TestWeChatConfigurationResV1" + "$ref": "#/definitions/v1.GetAuditPlanResV1" } } } - } - }, - "/v1/custom_rules": { - "get": { + }, + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get all custom rule template", + "description": "delete audit plan", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "自定义规则列表", - "operationId": "getCustomRulesV1", + "summary": "删除扫描任务", + "operationId": "deleteAuditPlanV1", "parameters": [ { "type": "string", - "description": "filter db type", - "name": "filter_db_type", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { "type": "string", - "description": "filter desc", - "name": "filter_desc", - "in": "query" + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetCustomRulesResV1" + "$ref": "#/definitions/controller.BaseRes" } } } }, - "post": { + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create custom rule", + "description": "update audit plan", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "添加自定义规则", - "operationId": "createCustomRuleV1", + "summary": "更新扫描任务", + "operationId": "updateAuditPlanV1", "parameters": [ { - "description": "add custom rule", - "name": "instance", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "description": "update audit plan", + "name": "audit_plan", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateCustomRuleReqV1" + "$ref": "#/definitions/v1.UpdateAuditPlanReqV1" } } ], @@ -1224,25 +1223,32 @@ var doc = `{ } } }, - "/v1/custom_rules/{db_type}/rule_types": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get rule type by db type", + "description": "get audit plan notify config", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "获取规则分类", - "operationId": "getRuleTypeByDBTypeV1", + "summary": "获取扫描任务消息推送设置", + "operationId": "getAuditPlanNotifyConfigV1", "parameters": [ { "type": "string", - "description": "db type", - "name": "db_type", - "in": "query", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", "required": true } ], @@ -1250,60 +1256,83 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleTypeByDBTypeResV1" + "$ref": "#/definitions/v1.GetAuditPlanNotifyConfigResV1" } } } - } - }, - "/v1/custom_rules/{rule_id}": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get custom rule by rule_id", + "description": "update audit plan notify config", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "获取自定义规则", - "operationId": "getCustomRuleV1", + "summary": "更新扫描任务通知设置", + "operationId": "updateAuditPlanNotifyConfigV1", "parameters": [ { "type": "string", - "description": "rule id", - "name": "rule_id", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", "in": "path", "required": true + }, + { + "description": "update audit plan notify config", + "name": "config", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateAuditPlanNotifyConfigReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetCustomRuleResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - }, - "delete": { + } + }, + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config/test": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete custom rule", + "description": "Test audit task message push", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "删除自定义规则", - "operationId": "deleteCustomRuleV1", + "summary": "测试扫描任务消息推送", + "operationId": "testAuditPlanNotifyConfigV1", "parameters": [ { "type": "string", - "description": "rule id", - "name": "rule_id", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", "in": "path", "required": true } @@ -1312,267 +1341,359 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.TestAuditPlanNotifyConfigResV1" } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update custom rule", + "description": "get audit plan report list", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "更新自定义规则", - "operationId": "updateCustomRuleV1", + "summary": "获取指定扫描任务的报告列表", + "operationId": "getAuditPlanReportsV1", "parameters": [ { "type": "string", - "description": "rule id", - "name": "rule_id", + "description": "project name", + "name": "project_name", "in": "path", "required": true }, { - "description": "update custom rule", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateCustomRuleReqV1" - } + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetAuditPlanReportsResV1" } } } } }, - "/v1/dashboard": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get dashboard info", - "produces": [ - "application/json" - ], + "description": "get audit plan report", "tags": [ - "dashboard" + "audit_plan" ], - "summary": "获取 dashboard 信息", - "operationId": "getDashboardV1", + "summary": "获取指定扫描任务的SQL扫描记录统计信息", + "operationId": "getAuditPlanReportV1", "parameters": [ { "type": "string", - "description": "filter project name", - "name": "filter_project_name", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetDashboardResV1" - } - } - } - } - }, - "/v1/dashboard/project_tips": { - "get": { - "security": [ + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, { - "ApiKeyAuth": [] + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true } ], - "description": "get dashboard project tips", - "produces": [ - "application/json" - ], - "tags": [ - "dashboard" - ], - "summary": "获取dashboard项目提示列表", - "operationId": "getDashboardProjectTipsV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetDashboardProjectTipsResV1" + "$ref": "#/definitions/v1.GetAuditPlanReportResV1" } } } } }, - "/v1/instance_additional_metas": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/export": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance additional metas", + "description": "export audit plan report as csv", "tags": [ - "instance" + "audit_plan" + ], + "summary": "以csv的形式导出扫描报告", + "operationId": "exportAuditPlanReportV1", + "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + } ], - "summary": "获取实例的额外属性列表", - "operationId": "getInstanceAdditionalMetas", "responses": { "200": { - "description": "OK", + "description": "get export audit plan report", "schema": { - "$ref": "#/definitions/v1.GetInstanceAdditionalMetasResV1" + "type": "file" } } } } }, - "/v1/instance_connection": { - "post": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test instance db connection 注:可直接提交创建实例接口的body,该接口的json 内容是创建实例的 json 的子集", - "consumes": [ - "application/json" - ], + "description": "get audit plan report SQLs", "tags": [ - "instance" + "audit_plan" ], - "summary": "实例连通性测试(实例提交前)", - "operationId": "checkInstanceIsConnectableV1", + "summary": "获取指定扫描任务的SQL扫描详情", + "operationId": "getAuditPlanReportsSQLsV1", "parameters": [ { - "description": "instance info", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.GetInstanceConnectableReqV1" - } + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstanceConnectableResV1" + "$ref": "#/definitions/v1.GetAuditPlanReportSQLsResV1" } } } } }, - "/v1/login": { - "post": { - "description": "user login", + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "get SQL explain and related table metadata for analysis", "tags": [ - "user" + "audit_plan" ], - "summary": "用户登录", - "operationId": "loginV1", + "summary": "获取task相关的SQL执行计划和表元数据", + "operationId": "getTaskAnalysisData", "parameters": [ { - "description": "user login request", - "name": "user", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UserLoginReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserLoginResV1" - } + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "sql number", + "name": "number", + "in": "path", + "required": true } - } - } - }, - "/v1/logout": { - "post": { - "description": "user logout", - "tags": [ - "user" ], - "summary": "用户登出", - "operationId": "logoutV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetAuditPlanAnalysisDataResV1" } } } } }, - "/v1/management_permissions": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get platform management permissions", + "description": "get audit plan SQLs", "tags": [ - "management_permission" + "audit_plan" + ], + "summary": "获取指定扫描任务的SQLs信息(不包括扫描结果)", + "operationId": "getAuditPlanSQLsV1", + "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true + } ], - "summary": "获取平台管理权限列表", - "operationId": "GetManagementPermissionsV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetManagementPermissionsResV1" + "$ref": "#/definitions/v1.GetAuditPlanSQLsResV1" } } } } }, - "/v1/oauth2/link": { - "get": { - "description": "oauth2 link", - "tags": [ - "oauth2" - ], - "summary": "oauth2通过此链接跳转到第三方登录网址", - "operationId": "Oauth2Link" - } - }, - "/v1/oauth2/user/bind": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full": { "post": { - "description": "bind Oauth2 user to sqle", + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "full sync audit plan SQLs", "tags": [ - "oauth2" + "audit_plan" ], - "summary": "绑定 Oauth2 和 sqle用户", - "operationId": "bindOauth2User", + "summary": "全量同步SQL到扫描任务", + "operationId": "fullSyncAuditPlanSQLsV1", + "deprecated": true, "parameters": [ { - "description": "bind oauth2 user req", - "name": "conf", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "description": "full sync audit plan SQLs request", + "name": "sqls", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.BindOauth2UserReqV1" + "$ref": "#/definitions/v1.FullSyncAuditPlanSQLsReqV1" } } ], @@ -1580,276 +1701,131 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.BindOauth2UserResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/operation_records": { - "get": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Get operation record list", + "description": "partial sync audit plan SQLs", "tags": [ - "OperationRecord" + "audit_plan" ], - "summary": "获取操作记录列表", - "operationId": "getOperationRecordListV1", + "summary": "增量同步SQL到扫描任务", + "operationId": "partialSyncAuditPlanSQLsV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "filter_operate_time_from", - "name": "filter_operate_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_time_to", - "name": "filter_operate_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_project_name", - "name": "filter_operate_project_name", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy_search_operate_user_name", - "name": "fuzzy_search_operate_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_type_name", - "name": "filter_operate_type_name", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { "type": "string", - "description": "filter_operate_action", - "name": "filter_operate_action", - "in": "query" - }, - { - "type": "integer", - "description": "page_index", - "name": "page_index", - "in": "query", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", "required": true }, { - "type": "integer", - "description": "page_size", - "name": "page_size", - "in": "query", - "required": true + "description": "partial sync audit plan SQLs request", + "name": "sqls", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.PartialSyncAuditPlanSQLsReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetOperationRecordListResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/operation_records/exports": { - "get": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/trigger": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Export operation record list", + "description": "trigger audit plan", "tags": [ - "OperationRecord" + "audit_plan" ], - "summary": "导出操作记录列表", - "operationId": "getExportOperationRecordListV1", + "summary": "触发扫描任务", + "operationId": "triggerAuditPlanV1", "parameters": [ { "type": "string", - "description": "filter_operate_time_from", - "name": "filter_operate_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_time_to", - "name": "filter_operate_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_project_name", - "name": "filter_operate_project_name", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy_search_operate_user_name", - "name": "fuzzy_search_operate_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_type_name", - "name": "filter_operate_type_name", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { "type": "string", - "description": "filter_operate_action", - "name": "filter_operate_action", - "in": "query" - } - ], - "responses": { - "200": { - "description": "get export operation record list", - "schema": { - "type": "file" - } - } - } - } - }, - "/v1/operation_records/operation_actions": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "Get operation action list", - "tags": [ - "OperationRecord" - ], - "summary": "获取操作内容列表", - "operationId": "getOperationActionList", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetOperationActionListResV1" - } - } - } - } - }, - "/v1/operation_records/operation_type_names": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "Get operation type name list", - "tags": [ - "OperationRecord" - ], - "summary": "获取操作类型名列表", - "operationId": "GetOperationTypeNameList", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetOperationTypeNamesListResV1" - } - } - } - } - }, - "/v1/operations": { - "get": { - "security": [ - { - "ApiKeyAuth": [] + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true } ], - "description": "get permission operations", - "tags": [ - "operation" - ], - "summary": "获取权限动作列表", - "operationId": "GetOperationsV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetOperationsResV1" + "$ref": "#/definitions/v1.TriggerAuditPlanResV1" } } } } }, - "/v1/project_tips": { + "/v1/projects/{project_name}/audit_whitelist": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get project tip list", + "description": "get all whitelist", "tags": [ - "project" + "audit_whitelist" ], - "summary": "获取项目提示列表", - "operationId": "getProjectTipsV1", + "summary": "获取Sql审核白名单", + "operationId": "getAuditWhitelistV1", "parameters": [ { - "enum": [ - "operation_record" - ], "type": "string", - "description": "functional module", - "name": "functional_module", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetProjectTipsResV1" - } - } - } - } - }, - "/v1/projects": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get project list", - "tags": [ - "project" - ], - "summary": "获取项目列表", - "operationId": "getProjectListV1", - "parameters": [ + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, { - "type": "integer", + "type": "string", "description": "page index", "name": "page_index", "in": "query", "required": true }, { - "type": "integer", - "default": 50, - "description": "size of per page", + "type": "string", + "description": "page size", "name": "page_size", "in": "query", "required": true @@ -1859,7 +1835,7 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectResV1" + "$ref": "#/definitions/v1.GetAuditWhitelistResV1" } } } @@ -1870,26 +1846,30 @@ var doc = `{ "ApiKeyAuth": [] } ], - "description": "create project", + "description": "create a sql whitelist", "consumes": [ "application/json" ], - "produces": [ - "application/json" - ], "tags": [ - "project" + "audit_whitelist" ], - "summary": "创建项目", - "operationId": "createProjectV1", + "summary": "添加SQL白名单", + "operationId": "createAuditWhitelistV1", "parameters": [ { - "description": "create project request", - "name": "project", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "description": "add sql whitelist req", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateProjectReqV1" + "$ref": "#/definitions/v1.CreateAuditWhitelistReqV1" } } ], @@ -1903,19 +1883,19 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/": { - "get": { + "/v1/projects/{project_name}/audit_whitelist/{audit_whitelist_id}/": { + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get project detail", + "description": "remove sql white", "tags": [ - "project" + "audit_whitelist" ], - "summary": "获取项目详情", - "operationId": "getProjectDetailV1", + "summary": "删除SQL白名单信息", + "operationId": "deleteAuditWhitelistByIdV1", "parameters": [ { "type": "string", @@ -1923,43 +1903,20 @@ var doc = `{ "name": "project_name", "in": "path", "required": true + }, + { + "type": "string", + "description": "audit whitelist id", + "name": "audit_whitelist_id", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectDetailResV1" - } - } - } - }, - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete project", - "tags": [ - "project" - ], - "summary": "删除项目", - "operationId": "deleteProjectV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/controller.BaseRes" } } } @@ -1970,18 +1927,15 @@ var doc = `{ "ApiKeyAuth": [] } ], - "description": "update project", + "description": "update sql whitelist by id", "consumes": [ "application/json" ], - "produces": [ - "application/json" - ], "tags": [ - "project" + "audit_whitelist" ], - "summary": "更新项目", - "operationId": "updateProjectV1", + "summary": "更新SQL白名单", + "operationId": "UpdateAuditWhitelistByIdV1", "parameters": [ { "type": "string", @@ -1991,52 +1945,21 @@ var doc = `{ "required": true }, { - "description": "create project request", - "name": "project", + "type": "string", + "description": "sql audit whitelist id", + "name": "audit_whitelist_id", + "in": "path", + "required": true + }, + { + "description": "update sql whitelist req", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateProjectReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.UpdateAuditWhitelistReqV1" } } - } - } - }, - "/v1/projects/{project_name}/archive": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "archive project", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "project" - ], - "summary": "归档项目", - "operationId": "archiveProjectV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } ], "responses": { "200": { @@ -2048,19 +1971,19 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/audit_plans": { + "/v1/projects/{project_name}/instance_tips": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan info list", + "description": "get instance tip list", "tags": [ - "audit_plan" + "instance" ], - "summary": "获取扫描任务信息列表", - "operationId": "getAuditPlansV1", + "summary": "获取实例提示列表", + "operationId": "getInstanceTipListV1", "parameters": [ { "type": "string", @@ -2071,67 +1994,51 @@ var doc = `{ }, { "type": "string", - "description": "filter audit plan db type", - "name": "filter_audit_plan_db_type", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search audit plan name", - "name": "fuzzy_search_audit_plan_name", + "description": "filter db type", + "name": "filter_db_type", "in": "query" }, { "type": "string", - "description": "filter audit plan type", - "name": "filter_audit_plan_type", + "description": "filter workflow template id", + "name": "filter_workflow_template_id", "in": "query" }, { + "enum": [ + "create_audit_plan", + "create_workflow", + "sql_manage" + ], "type": "string", - "description": "filter audit plan instance name", - "name": "filter_audit_plan_instance_name", + "description": "functional module", + "name": "functional_module", "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlansResV1" + "$ref": "#/definitions/v1.GetInstanceTipsResV1" } } } - }, + } + }, + "/v1/projects/{project_name}/instances/connections": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create audit plan", - "consumes": [ - "application/json" - ], + "description": "batch test instance db connections", "tags": [ - "audit_plan" + "instance" ], - "summary": "添加扫描任务", - "operationId": "createAuditPlanV1", + "summary": "批量测试实例连通性(实例提交后)", + "operationId": "batchCheckInstanceIsConnectableByName", "parameters": [ { "type": "string", @@ -2141,12 +2048,12 @@ var doc = `{ "required": true }, { - "description": "create audit plan", - "name": "audit_plan", + "description": "instances", + "name": "instances", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateAuditPlanReqV1" + "$ref": "#/definitions/v1.BatchCheckInstanceConnectionsReqV1" } } ], @@ -2154,25 +2061,25 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.BatchGetInstanceConnectionsResV1" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/": { + "/v1/projects/{project_name}/instances/{instance_name}/connection": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan", + "description": "test instance db connection", "tags": [ - "audit_plan" + "instance" ], - "summary": "获取指定扫描任务", - "operationId": "getAuditPlanV1", + "summary": "实例连通性测试(实例提交后)", + "operationId": "checkInstanceIsConnectableByNameV1", "parameters": [ { "type": "string", @@ -2183,8 +2090,8 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", "in": "path", "required": true } @@ -2193,23 +2100,25 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanResV1" + "$ref": "#/definitions/v1.GetInstanceConnectableResV1" } } } - }, - "delete": { + } + }, + "/v1/projects/{project_name}/instances/{instance_name}/rules": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete audit plan", + "description": "get instance all rule", "tags": [ - "audit_plan" + "instance" ], - "summary": "删除扫描任务", - "operationId": "deleteAuditPlanV1", + "summary": "获取实例应用的规则列表", + "operationId": "getInstanceRuleListV1", "parameters": [ { "type": "string", @@ -2220,8 +2129,8 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", "in": "path", "required": true } @@ -2230,23 +2139,25 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetRulesResV1" } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/instances/{instance_name}/schemas": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update audit plan", + "description": "instance schema list", "tags": [ - "audit_plan" + "instance" ], - "summary": "更新扫描任务", - "operationId": "updateAuditPlanV1", + "summary": "实例 Schema 列表", + "operationId": "getInstanceSchemasV1", "parameters": [ { "type": "string", @@ -2257,44 +2168,35 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", "in": "path", "required": true - }, - { - "description": "update audit plan", - "name": "audit_plan", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateAuditPlanReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetInstanceSchemaResV1" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config": { + "/v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan notify config", + "description": "list table by schema", "tags": [ - "audit_plan" + "instance" ], - "summary": "获取扫描任务消息推送设置", - "operationId": "getAuditPlanNotifyConfigV1", + "summary": "获取数据库下的所有表", + "operationId": "listTableBySchema", "parameters": [ { "type": "string", @@ -2305,8 +2207,15 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "schema name", + "name": "schema_name", "in": "path", "required": true } @@ -2315,23 +2224,25 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanNotifyConfigResV1" + "$ref": "#/definitions/v1.ListTableBySchemaResV1" } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables/{table_name}/metadata": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update audit plan notify config", + "description": "get table metadata", "tags": [ - "audit_plan" + "instance" ], - "summary": "更新扫描任务通知设置", - "operationId": "updateAuditPlanNotifyConfigV1", + "summary": "获取表元数据", + "operationId": "getTableMetadata", "parameters": [ { "type": "string", @@ -2342,44 +2253,49 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", "in": "path", "required": true }, { - "description": "update audit plan notify config", - "name": "config", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateAuditPlanNotifyConfigReqV1" - } + "type": "string", + "description": "schema name", + "name": "schema_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "table name", + "name": "table_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetTableMetadataResV1" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config/test": { + "/v1/projects/{project_name}/rule_template_tips": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Test audit task message push", + "description": "get rule template tips in project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "测试扫描任务消息推送", - "operationId": "testAuditPlanNotifyConfigV1", + "summary": "获取项目规则模板提示", + "operationId": "getProjectRuleTemplateTipsV1", "parameters": [ { "type": "string", @@ -2390,35 +2306,34 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true + "description": "filter db type", + "name": "filter_db_type", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TestAuditPlanNotifyConfigResV1" + "$ref": "#/definitions/v1.GetRuleTemplateTipsResV1" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports": { + "/v1/projects/{project_name}/rule_templates": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan report list", + "description": "get all rule template in a project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取指定扫描任务的报告列表", - "operationId": "getAuditPlanReportsV1", + "summary": "项目规则模板列表", + "operationId": "getProjectRuleTemplateListV1", "parameters": [ { "type": "string", @@ -2427,13 +2342,6 @@ var doc = `{ "in": "path", "required": true }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, { "type": "integer", "description": "page index", @@ -2453,25 +2361,26 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanReportsResV1" + "$ref": "#/definitions/v1.GetProjectRuleTemplatesResV1" } } } - } - }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/": { - "get": { + }, + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan report", + "description": "create a rule template in project", + "consumes": [ + "application/json" + ], "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取指定扫描任务的SQL扫描记录统计信息", - "operationId": "getAuditPlanReportV1", + "summary": "添加项目规则模板", + "operationId": "createProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2481,43 +2390,38 @@ var doc = `{ "required": true }, { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", - "in": "path", - "required": true + "description": "add rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.CreateProjectRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanReportResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/export": { + "/v1/projects/{project_name}/rule_templates/{rule_template_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export audit plan report as csv", + "description": "get rule template detail in project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "以csv的形式导出扫描报告", - "operationId": "exportAuditPlanReportV1", + "summary": "获取项目规则模板信息", + "operationId": "getProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2528,42 +2432,39 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true }, { "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", - "in": "path", - "required": true + "description": "fuzzy rule,keyword for desc and annotation", + "name": "fuzzy_keyword_rule", + "in": "query" } ], "responses": { "200": { - "description": "get export audit plan report", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/v1.GetProjectRuleTemplateResV1" } } } - } - }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls": { - "get": { + }, + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan report SQLs", + "description": "delete rule template in project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取指定扫描任务的SQL扫描详情", - "operationId": "getAuditPlanReportsSQLsV1", + "summary": "删除项目规则模板", + "operationId": "deleteProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2574,56 +2475,33 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanReportSQLsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - } - }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get SQL explain and related table metadata for analysis", + "description": "update rule template in project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取task相关的SQL执行计划和表元数据", - "operationId": "getTaskAnalysisData", + "summary": "更新项目规则模板", + "operationId": "updateProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2634,49 +2512,47 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true }, { - "type": "string", - "description": "sql number", - "name": "number", - "in": "path", - "required": true + "description": "update rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateProjectRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanAnalysisDataResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls": { - "get": { + "/v1/projects/{project_name}/rule_templates/{rule_template_name}/clone": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan SQLs", + "description": "clone a rule template in project", + "consumes": [ + "application/json" + ], "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取指定扫描任务的SQLs信息(不包括扫描结果)", - "operationId": "getAuditPlanSQLsV1", + "summary": "克隆项目规则模板", + "operationId": "cloneProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2687,50 +2563,44 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true }, { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true + "description": "clone rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.CloneProjectRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanSQLsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full": { - "post": { + "/v1/projects/{project_name}/rule_templates/{rule_template_name}/export": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "full sync audit plan SQLs", + "description": "export rule template in a project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "全量同步SQL到扫描任务", - "operationId": "fullSyncAuditPlanSQLsV1", - "deprecated": true, + "summary": "导出项目规则模板", + "operationId": "exportProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2741,105 +2611,94 @@ var doc = `{ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true - }, - { - "description": "full sync audit plan SQLs request", - "name": "sqls", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.FullSyncAuditPlanSQLsReqV1" - } } ], "responses": { "200": { - "description": "OK", + "description": "sqle rule template file", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial": { - "post": { + "/v1/projects/{project_name}/sql_audit_records": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "partial sync audit plan SQLs", + "description": "get sql audit records", "tags": [ - "audit_plan" + "sql_audit_record" ], - "summary": "增量同步SQL到扫描任务", - "operationId": "partialSyncAuditPlanSQLsV1", - "deprecated": true, + "summary": "获取SQL审核记录列表", + "operationId": "getSQLAuditRecordsV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "fuzzy search tags", + "name": "fuzzy_search_tags", + "in": "query" }, { + "enum": [ + "auditing", + "successfully" + ], "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true + "description": "filter sql audit status", + "name": "filter_sql_audit_status", + "in": "query" }, { - "description": "partial sync audit plan SQLs request", - "name": "sqls", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.PartialSyncAuditPlanSQLsReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/trigger": { - "post": { - "security": [ + "type": "integer", + "description": "filter instance id", + "name": "filter_instance_id", + "in": "query" + }, { - "ApiKeyAuth": [] - } - ], - "description": "trigger audit plan", - "tags": [ - "audit_plan" - ], - "summary": "触发扫描任务", - "operationId": "triggerAuditPlanV1", - "parameters": [ + "type": "string", + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "description": "filter create time to", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter sql audit record ids", + "name": "filter_sql_audit_record_ids", + "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", "required": true }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true } @@ -2848,25 +2707,29 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TriggerAuditPlanResV1" + "$ref": "#/definitions/v1.GetSQLAuditRecordsResV1" } } } - } - }, - "/v1/projects/{project_name}/audit_whitelist": { - "get": { + }, + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get all whitelist", + "description": "SQL audit\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.\n4. file[input_zip_file]: it is ZIP file that sql will be parsed from xml or sql file inside it.\n5. formData[git_http_url]:the url which scheme is http(s) and end with .git.\n6. formData[git_user_name]:The name of the user who owns the repository read access.\n7. formData[git_user_password]:The password corresponding to git_user_name.", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], "tags": [ - "audit_whitelist" + "sql_audit_record" ], - "summary": "获取Sql审核白名单", - "operationId": "getAuditWhitelistV1", + "summary": "SQL审核", + "operationId": "CreateSQLAuditRecordV1", "parameters": [ { "type": "string", @@ -2877,43 +2740,88 @@ var doc = `{ }, { "type": "string", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true + "description": "instance name", + "name": "instance_name", + "in": "formData" }, { "type": "string", - "description": "page size", - "name": "page_size", - "in": "query", - "required": true + "description": "schema of instance", + "name": "instance_schema", + "in": "formData" + }, + { + "type": "string", + "description": "db type of instance", + "name": "db_type", + "in": "formData" + }, + { + "type": "string", + "description": "sqls for audit", + "name": "sqls", + "in": "formData" + }, + { + "type": "file", + "description": "input SQL file", + "name": "input_sql_file", + "in": "formData" + }, + { + "type": "file", + "description": "input mybatis XML file", + "name": "input_mybatis_xml_file", + "in": "formData" + }, + { + "type": "file", + "description": "input ZIP file", + "name": "input_zip_file", + "in": "formData" + }, + { + "type": "string", + "description": "git repository url", + "name": "git_http_url", + "in": "formData" + }, + { + "type": "string", + "description": "the name of user to clone the repository", + "name": "git_user_name", + "in": "formData" + }, + { + "type": "string", + "description": "the password corresponding to git_user_name", + "name": "git_user_password", + "in": "formData" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditWhitelistResV1" + "$ref": "#/definitions/v1.CreateSQLAuditRecordResV1" } } } - }, - "post": { + } + }, + "/v1/projects/{project_name}/sql_audit_records/tag_tips": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create a sql whitelist", - "consumes": [ - "application/json" - ], + "description": "get sql audit record tag tips", "tags": [ - "audit_whitelist" + "sql_audit_record" ], - "summary": "添加SQL白名单", - "operationId": "createAuditWhitelistV1", + "summary": "获取SQL审核记录标签列表", + "operationId": "GetSQLAuditRecordTagTipsV1", "parameters": [ { "type": "string", @@ -2921,40 +2829,31 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "description": "add sql whitelist req", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateAuditWhitelistReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetSQLAuditRecordTagTipsResV1" } } } } }, - "/v1/projects/{project_name}/audit_whitelist/{audit_whitelist_id}/": { - "delete": { + "/v1/projects/{project_name}/sql_audit_records/{sql_audit_record_id}/": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "remove sql white", + "description": "get sql audit record info", "tags": [ - "audit_whitelist" + "sql_audit_record" ], - "summary": "删除SQL白名单信息", - "operationId": "deleteAuditWhitelistByIdV1", + "summary": "获取SQL审核记录信息", + "operationId": "getSQLAuditRecordV1", "parameters": [ { "type": "string", @@ -2965,8 +2864,8 @@ var doc = `{ }, { "type": "string", - "description": "audit whitelist id", - "name": "audit_whitelist_id", + "description": "sql audit record id", + "name": "sql_audit_record_id", "in": "path", "required": true } @@ -2975,7 +2874,7 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetSQLAuditRecordResV1" } } } @@ -2986,15 +2885,15 @@ var doc = `{ "ApiKeyAuth": [] } ], - "description": "update sql whitelist by id", + "description": "update SQL audit record", "consumes": [ "application/json" ], "tags": [ - "audit_whitelist" + "sql_audit_record" ], - "summary": "更新SQL白名单", - "operationId": "UpdateAuditWhitelistByIdV1", + "summary": "更新SQL审核记录", + "operationId": "updateSQLAuditRecordV1", "parameters": [ { "type": "string", @@ -3005,18 +2904,18 @@ var doc = `{ }, { "type": "string", - "description": "sql audit whitelist id", - "name": "audit_whitelist_id", + "description": "sql audit record id", + "name": "sql_audit_record_id", "in": "path", "required": true }, { - "description": "update sql whitelist req", - "name": "instance", + "description": "update SQL audit record", + "name": "param", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateAuditWhitelistReqV1" + "$ref": "#/definitions/v1.UpdateSQLAuditRecordReqV1" } } ], @@ -3030,19 +2929,20 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/instance_tips": { + "/v1/projects/{project_name}/sql_manages": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance tip list", + "description": "get sql manage list", "tags": [ - "instance" + "SqlManage" ], - "summary": "获取实例提示列表", - "operationId": "getInstanceTipListV1", + "summary": "获取管控sql列表", + "operationId": "GetSqlManageList", + "deprecated": true, "parameters": [ { "type": "string", @@ -3053,93 +2953,111 @@ var doc = `{ }, { "type": "string", - "description": "filter db type", - "name": "filter_db_type", + "description": "fuzzy search sql fingerprint", + "name": "fuzzy_search_sql_fingerprint", "in": "query" }, { "type": "string", - "description": "filter workflow template id", - "name": "filter_workflow_template_id", + "description": "assignee", + "name": "filter_assignee", + "in": "query" + }, + { + "type": "string", + "description": "instance name", + "name": "filter_instance_name", "in": "query" }, { "enum": [ - "create_audit_plan", - "create_workflow", - "sql_manage" + "audit_plan", + "sql_audit_record" ], "type": "string", - "description": "functional module", - "name": "functional_module", + "description": "source", + "name": "filter_source", "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetInstanceTipsResV1" - } - } - } - } - }, - "/v1/projects/{project_name}/instances": { - "get": { - "security": [ + }, { - "ApiKeyAuth": [] - } - ], - "description": "get instance info list", - "tags": [ - "instance" - ], - "summary": "获取实例信息列表", - "operationId": "getInstanceListV1", - "parameters": [ + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "type": "string", + "description": "audit level", + "name": "filter_audit_level", + "in": "query" + }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "last audit start time from", + "name": "filter_last_audit_start_time_from", + "in": "query" }, { "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", + "description": "last audit start time to", + "name": "filter_last_audit_start_time_to", + "in": "query" + }, + { + "enum": [ + "unhandled", + "solved", + "ignored", + "manual_audited" + ], + "type": "string", + "description": "status", + "name": "filter_status", "in": "query" }, { "type": "string", - "description": "filter db type", + "description": "rule name", + "name": "filter_rule_name", + "in": "query" + }, + { + "type": "string", + "description": "db type", "name": "filter_db_type", "in": "query" }, { "type": "string", - "description": "filter db host", - "name": "filter_db_host", + "description": "fuzzy search endpoint", + "name": "fuzzy_search_endpoint", "in": "query" }, { "type": "string", - "description": "filter db port", - "name": "filter_db_port", + "description": "fuzzy search schema name", + "name": "fuzzy_search_schema_name", "in": "query" }, { + "enum": [ + "first_appear_timestamp", + "last_receive_timestamp", + "fp_count" + ], "type": "string", - "description": "filter db user", - "name": "filter_db_user", + "description": "sort field", + "name": "sort_field", "in": "query" }, { + "enum": [ + "asc", + "desc" + ], "type": "string", - "description": "filter rule template name", - "name": "filter_rule_template_name", + "description": "sort order", + "name": "sort_order", "in": "query" }, { @@ -3161,27 +3079,25 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstancesResV1" + "$ref": "#/definitions/v1.GetSqlManageListResp" } } } - }, - "post": { + } + }, + "/v1/projects/{project_name}/sql_manages/batch": { + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create a instance", - "consumes": [ - "application/json" - ], + "description": "batch update sql manage", "tags": [ - "instance" + "SqlManage" ], - "summary": "添加实例", - "operationId": "createInstanceV1", - "deprecated": true, + "summary": "批量更新SQL管控", + "operationId": "BatchUpdateSqlManage", "parameters": [ { "type": "string", @@ -3191,12 +3107,12 @@ var doc = `{ "required": true }, { - "description": "add instance", - "name": "instance", + "description": "batch update sql manage request", + "name": "BatchUpdateSqlManageReq", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateInstanceReqV1" + "$ref": "#/definitions/v1.BatchUpdateSqlManageReq" } } ], @@ -3210,19 +3126,19 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/instances/connections": { - "post": { + "/v1/projects/{project_name}/sql_manages/exports": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "batch test instance db connections", + "description": "export sql manage", "tags": [ - "instance" + "SqlManage" ], - "summary": "批量测试实例连通性(实例提交后)", - "operationId": "batchCheckInstanceIsConnectableByName", + "summary": "导出SQL管控", + "operationId": "exportSqlManageV1", "parameters": [ { "type": "string", @@ -3232,160 +3148,138 @@ var doc = `{ "required": true }, { - "description": "instances", - "name": "instances", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.BatchCheckInstanceConnectionsReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.BatchGetInstanceConnectionsResV1" - } - } - } - } - }, - "/v1/projects/{project_name}/instances/{instance_name}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get instance db", - "tags": [ - "instance" - ], - "summary": "获取实例信息", - "operationId": "getInstanceV1", - "parameters": [ + "type": "string", + "description": "fuzzy search sql fingerprint", + "name": "fuzzy_search_sql_fingerprint", + "in": "query" + }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "assignee", + "name": "filter_assignee", + "in": "query" }, { "type": "string", "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetInstanceResV1" - } - } - } - }, - "delete": { - "security": [ + "name": "filter_instance_name", + "in": "query" + }, { - "ApiKeyAuth": [] - } - ], - "description": "delete instance db", - "tags": [ - "instance" - ], - "summary": "删除实例", - "operationId": "deleteInstanceV1", - "parameters": [ + "enum": [ + "audit_plan", + "sql_audit_record" + ], + "type": "string", + "description": "source", + "name": "filter_source", + "in": "query" + }, { + "enum": [ + "normal", + "notice", + "warn", + "error" + ], "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "audit level", + "name": "filter_audit_level", + "in": "query" }, { "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ + "description": "last audit start time from", + "name": "filter_last_audit_start_time_from", + "in": "query" + }, { - "ApiKeyAuth": [] - } - ], - "description": "update instance", - "tags": [ - "instance" - ], - "summary": "更新实例", - "operationId": "updateInstanceV1", - "parameters": [ + "type": "string", + "description": "last audit start time to", + "name": "filter_last_audit_start_time_to", + "in": "query" + }, { + "enum": [ + "unhandled", + "solved", + "ignored", + "manual_audited" + ], "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "status", + "name": "filter_status", + "in": "query" }, { "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true + "description": "db type", + "name": "filter_db_type", + "in": "query" }, { - "description": "update instance request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateInstanceReqV1" - } + "type": "string", + "description": "rule name", + "name": "filter_rule_name", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search endpoint", + "name": "fuzzy_search_endpoint", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search schema name", + "name": "fuzzy_search_schema_name", + "in": "query" + }, + { + "enum": [ + "first_appear_timestamp", + "last_receive_timestamp", + "fp_count" + ], + "type": "string", + "description": "sort field", + "name": "sort_field", + "in": "query" + }, + { + "enum": [ + "asc", + "desc" + ], + "type": "string", + "description": "sort order", + "name": "sort_order", + "in": "query" } ], "responses": { "200": { - "description": "OK", + "description": "export sql manage", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/connection": { + "/v1/projects/{project_name}/sql_manages/rule_tips": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test instance db connection", + "description": "get sql manage rule tips", "tags": [ - "instance" + "SqlManage" ], - "summary": "实例连通性测试(实例提交后)", - "operationId": "checkInstanceIsConnectableByNameV1", + "summary": "获取管控规则tips", + "operationId": "GetSqlManageRuleTips", "parameters": [ { "type": "string", @@ -3393,38 +3287,31 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstanceConnectableResV1" + "$ref": "#/definitions/v1.GetSqlManageRuleTipsResp" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/rules": { + "/v1/projects/{project_name}/sql_manages/{sql_manage_id}/sql_analysis": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance all rule", + "description": "get sql manage analysis", "tags": [ - "instance" + "SqlManage" ], - "summary": "获取实例应用的规则列表", - "operationId": "getInstanceRuleListV1", + "summary": "获取SQL管控SQL分析", + "operationId": "GetSqlManageSqlAnalysisV1", "parameters": [ { "type": "string", @@ -3435,8 +3322,8 @@ var doc = `{ }, { "type": "string", - "description": "instance name", - "name": "instance_name", + "description": "sql manage id", + "name": "sql_manage_id", "in": "path", "required": true } @@ -3445,25 +3332,25 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRulesResV1" + "$ref": "#/definitions/v1.GetSqlManageSqlAnalysisResp" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/schemas": { + "/v1/projects/{project_name}/statistic/audit_plans": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "instance schema list", + "description": "statistic audit plan", "tags": [ - "instance" + "statistic" ], - "summary": "实例 Schema 列表", - "operationId": "getInstanceSchemasV1", + "summary": "获取各类型数据源上的扫描任务数量", + "operationId": "statisticAuditPlanV1", "parameters": [ { "type": "string", @@ -3471,38 +3358,31 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstanceSchemaResV1" + "$ref": "#/definitions/v1.StatisticAuditPlanResV1" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables": { + "/v1/projects/{project_name}/statistic/audited_sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "list table by schema", + "description": "statistics audited sql", "tags": [ - "instance" + "statistic" ], - "summary": "获取数据库下的所有表", - "operationId": "listTableBySchema", + "summary": "获取审核SQL总数,以及触发审核规则的SQL数量", + "operationId": "statisticsAuditedSQLV1", "parameters": [ { "type": "string", @@ -3510,45 +3390,31 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "schema name", - "name": "schema_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.ListTableBySchemaResV1" + "$ref": "#/definitions/v1.StatisticsAuditedSQLResV1" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables/{table_name}/metadata": { + "/v1/projects/{project_name}/statistic/instance_health": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get table metadata", + "description": "get instance health", "tags": [ - "instance" + "statistic" ], - "summary": "获取表元数据", - "operationId": "getTableMetadata", + "summary": "获取各类型数据源的健康情况", + "operationId": "GetInstanceHealthV1", "parameters": [ { "type": "string", @@ -3556,79 +3422,32 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "schema name", - "name": "schema_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "table name", - "name": "table_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetTableMetadataResV1" + "$ref": "#/definitions/v1.GetInstanceHealthResV1" } } } } }, - "/v1/projects/{project_name}/member_groups": { + "/v1/projects/{project_name}/statistic/project_score": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get member groups", + "description": "get project score", "tags": [ - "user_group" + "statistic" ], - "summary": "获取成员组列表", - "operationId": "getMemberGroupsV1", + "summary": "获取项目分数", + "operationId": "GetProjectScoreV1", "parameters": [ - { - "type": "string", - "description": "filter user group name", - "name": "filter_user_group_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - }, { "type": "string", "description": "project name", @@ -3641,29 +3460,25 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetMemberGroupsRespV1" + "$ref": "#/definitions/v1.GetProjectScoreResV1" } } } - }, - "post": { + } + }, + "/v1/projects/{project_name}/statistic/risk_audit_plans": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "add member group", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get risk audit plan", "tags": [ - "user_group" + "statistic" ], - "summary": "添加成员组", - "operationId": "addMemberGroupV1", + "summary": "获取扫描任务报告评分低于60的扫描任务", + "operationId": "getRiskAuditPlanV1", "parameters": [ { "type": "string", @@ -3671,77 +3486,31 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "description": "add member group", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateMemberGroupReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetRiskAuditPlanResV1" } } } } }, - "/v1/projects/{project_name}/member_groups/{user_group_name}/": { + "/v1/projects/{project_name}/statistic/risk_workflow": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get member group", + "description": "statistic risk workflow", "tags": [ - "user_group" + "statistic" ], - "summary": "获取成员组信息", - "operationId": "getMemberGroupV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "user group name", - "name": "user_group_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetMemberGroupRespV1" - } - } - } - }, - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete member group", - "tags": [ - "user_group" - ], - "summary": "删除成员组", - "operationId": "deleteMemberGroupV1", + "summary": "获取存在风险的工单", + "operationId": "statisticRiskWorkflowV1", "parameters": [ { "type": "string", @@ -3749,42 +3518,31 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "user group name", - "name": "user_group_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.StatisticRiskWorkflowResV1" } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/statistic/role_user": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update member group", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get role user count", "tags": [ - "user_group" + "statistic" ], - "summary": "修改成员组", - "operationId": "updateMemberGroupV1", + "summary": "获取各角色类型对应的成员数量", + "operationId": "getRoleUserCountV1", "parameters": [ { "type": "string", @@ -3792,47 +3550,31 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "user group name", - "name": "user_group_name", - "in": "path", - "required": true - }, - { - "description": "update member_group", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateMemberGroupReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetRoleUserCountResV1" } } } } }, - "/v1/projects/{project_name}/member_tips": { + "/v1/projects/{project_name}/statistic/workflow_status": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get member tip list", + "description": "statistic workflow status", "tags": [ - "user" + "statistic" ], - "summary": "获取成员提示列表", - "operationId": "getMemberTipListV1", + "summary": "获取项目下工单各个状态的数量", + "operationId": "statisticWorkflowStatusV1", "parameters": [ { "type": "string", @@ -3846,52 +3588,26 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetMemberTipsResV1" + "$ref": "#/definitions/v1.GetWorkflowStatusCountResV1" } } } } }, - "/v1/projects/{project_name}/members": { + "/v1/projects/{project_name}/statistics": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get members", + "description": "get project statistics", "tags": [ - "user" + "statistic" ], - "summary": "获取成员列表", - "operationId": "getMembersV1", + "summary": "获取项目统计信息", + "operationId": "getProjectStatisticsV1", "parameters": [ - { - "type": "string", - "description": "filter user name", - "name": "filter_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - }, { "type": "string", "description": "project name", @@ -3904,18 +3620,20 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetMembersRespV1" + "$ref": "#/definitions/v1.GetProjectStatisticsResV1" } } } - }, + } + }, + "/v1/projects/{project_name}/task_groups": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "add member", + "description": "create tasks group.", "consumes": [ "application/json" ], @@ -3923,10 +3641,10 @@ var doc = `{ "application/json" ], "tags": [ - "user" + "task" ], - "summary": "添加成员", - "operationId": "addMemberV1", + "summary": "创建审核任务组", + "operationId": "createAuditTasksV1", "parameters": [ { "type": "string", @@ -3936,12 +3654,12 @@ var doc = `{ "required": true }, { - "description": "add member", - "name": "data", + "description": "parameters for creating audit tasks group", + "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateMemberReqV1" + "$ref": "#/definitions/v1.CreateAuditTasksGroupReqV1" } } ], @@ -3949,25 +3667,31 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.CreateAuditTasksGroupResV1" } } } } }, - "/v1/projects/{project_name}/members/{user_name}/": { - "get": { + "/v1/projects/{project_name}/tasks/audits": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get member", + "description": "create and audit a task, you can upload sql content in three ways, any one can be used, but only one is effective.\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], "tags": [ - "user" + "task" ], - "summary": "获取成员信息", - "operationId": "getMemberV1", + "summary": "创建Sql扫描任务并提交审核", + "operationId": "createAndAuditTaskV1", "parameters": [ { "type": "string", @@ -3978,33 +3702,65 @@ var doc = `{ }, { "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", + "description": "instance name", + "name": "instance_name", + "in": "formData", "required": true + }, + { + "type": "string", + "description": "schema of instance", + "name": "instance_schema", + "in": "formData" + }, + { + "type": "string", + "description": "sqls for audit", + "name": "sql", + "in": "formData" + }, + { + "type": "file", + "description": "input SQL file", + "name": "input_sql_file", + "in": "formData" + }, + { + "type": "file", + "description": "input mybatis XML file", + "name": "input_mybatis_xml_file", + "in": "formData" + }, + { + "type": "file", + "description": "input ZIP file", + "name": "input_zip_file", + "in": "formData" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetMemberRespV1" + "$ref": "#/definitions/v1.GetAuditTaskResV1" } } } - }, - "delete": { + } + }, + "/v1/projects/{project_name}/workflow_template": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete member", + "description": "get workflow template detail", "tags": [ - "user" + "workflow" ], - "summary": "删除成员", - "operationId": "deleteMemberV1", + "summary": "获取审批流程模板详情", + "operationId": "getWorkflowTemplateV1", "parameters": [ { "type": "string", @@ -4012,20 +3768,13 @@ var doc = `{ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowTemplateResV1" } } } @@ -4036,7 +3785,7 @@ var doc = `{ "ApiKeyAuth": [] } ], - "description": "update member", + "description": "update the workflow template", "consumes": [ "application/json" ], @@ -4044,10 +3793,10 @@ var doc = `{ "application/json" ], "tags": [ - "user" + "workflow" ], - "summary": "修改成员", - "operationId": "updateMemberV1", + "summary": "更新Sql审批流程模板", + "operationId": "updateWorkflowTemplateV1", "parameters": [ { "type": "string", @@ -4057,19 +3806,12 @@ var doc = `{ "required": true }, { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - }, - { - "description": "update member", - "name": "data", + "description": "create workflow template", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateMemberReqV1" + "$ref": "#/definitions/v1.UpdateWorkflowTemplateReqV1" } } ], @@ -4083,64 +3825,94 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/rule_template_tips": { + "/v1/projects/{project_name}/workflows": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get rule template tips in project", + "description": "get workflow list", "tags": [ - "rule_template" + "workflow" ], - "summary": "获取项目规则模板提示", - "operationId": "getProjectRuleTemplateTipsV1", + "summary": "获取工单列表", + "operationId": "getWorkflowsV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "filter subject", + "name": "filter_subject", + "in": "query" }, { "type": "string", - "description": "filter db type", - "name": "filter_db_type", + "description": "filter by workflow_id", + "name": "filter_workflow_id", "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetRuleTemplateTipsResV1" - } - } - } - } - }, - "/v1/projects/{project_name}/rule_templates": { - "get": { - "security": [ + }, { - "ApiKeyAuth": [] - } - ], - "description": "get all rule template in a project", - "tags": [ - "rule_template" - ], - "summary": "项目规则模板列表", - "operationId": "getProjectRuleTemplateListV1", - "parameters": [ + "type": "string", + "description": "fuzzy search by workflow description", + "name": "fuzzy_search_workflow_desc", + "in": "query" + }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter create time to", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_from", + "name": "filter_task_execute_start_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_to", + "name": "filter_task_execute_start_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter create user id", + "name": "filter_create_user_id", + "in": "query" + }, + { + "enum": [ + "wait_for_audit", + "wait_for_execution", + "rejected", + "executing", + "canceled", + "exec_failed", + "finished" + ], + "type": "string", + "description": "filter workflow status", + "name": "filter_status", + "in": "query" + }, + { + "type": "string", + "description": "filter current step assignee user id", + "name": "filter_current_step_assignee_user_id", + "in": "query" + }, + { + "type": "string", + "description": "filter instance name", + "name": "filter_task_instance_name", + "in": "query" }, { "type": "integer", @@ -4155,13 +3927,26 @@ var doc = `{ "name": "page_size", "in": "query", "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "fuzzy matching subject/workflow_id", + "name": "fuzzy_keyword", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectRuleTemplatesResV1" + "$ref": "#/definitions/v1.GetWorkflowsResV1" } } } @@ -4172,31 +3957,35 @@ var doc = `{ "ApiKeyAuth": [] } ], - "description": "create a rule template in project", + "description": "create workflow", "consumes": [ "application/json" ], + "produces": [ + "application/json" + ], "tags": [ - "rule_template" + "workflow" ], - "summary": "添加项目规则模板", - "operationId": "createProjectRuleTemplateV1", + "summary": "创建工单", + "operationId": "createWorkflowV1", + "deprecated": true, "parameters": [ + { + "description": "create workflow request", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.CreateWorkflowReqV1" + } + }, { "type": "string", "description": "project name", "name": "project_name", "in": "path", "required": true - }, - { - "description": "add rule template request", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateProjectRuleTemplateReqV1" - } } ], "responses": { @@ -4209,19 +3998,20 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/rule_templates/{rule_template_name}/": { - "get": { + "/v1/projects/{project_name}/workflows/cancel": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get rule template detail in project", + "description": "batch cancel workflows", "tags": [ - "rule_template" + "workflow" ], - "summary": "获取项目规则模板信息", - "operationId": "getProjectRuleTemplateV1", + "summary": "批量取消工单", + "operationId": "batchCancelWorkflowsV1", + "deprecated": true, "parameters": [ { "type": "string", @@ -4231,34 +4021,39 @@ var doc = `{ "required": true }, { - "type": "string", - "description": "rule template name", - "name": "rule_template_name", - "in": "path", - "required": true + "description": "batch cancel workflows request", + "name": "BatchCancelWorkflowsReqV1", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.BatchCancelWorkflowsReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectRuleTemplateResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - }, - "delete": { + } + }, + "/v1/projects/{project_name}/workflows/complete": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete rule template in project", + "description": "this api will directly change the work order status to finished without real online operation", "tags": [ - "rule_template" + "workflow" ], - "summary": "删除项目规则模板", - "operationId": "deleteProjectRuleTemplateV1", + "summary": "批量完成工单", + "operationId": "batchCompleteWorkflowsV1", + "deprecated": true, "parameters": [ { "type": "string", @@ -4268,11 +4063,13 @@ var doc = `{ "required": true }, { - "type": "string", - "description": "rule template name", - "name": "rule_template_name", - "in": "path", - "required": true + "description": "batch complete workflows request", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.BatchCompleteWorkflowsReqV1" + } } ], "responses": { @@ -4283,93 +4080,142 @@ var doc = `{ } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/workflows/exports": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update rule template in project", + "description": "export workflow", "tags": [ - "rule_template" + "workflow" ], - "summary": "更新项目规则模板", - "operationId": "updateProjectRuleTemplateV1", + "summary": "导出工单", + "operationId": "exportWorkflowV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "filter subject", + "name": "filter_subject", + "in": "query" }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "fuzzy search by workflow description", + "name": "fuzzy_search_workflow_desc", + "in": "query" + }, + { + "type": "string", + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter create time to", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_from", + "name": "filter_task_execute_start_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_to", + "name": "filter_task_execute_start_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter create user id", + "name": "filter_create_user_id", + "in": "query" + }, + { + "enum": [ + "wait_for_audit", + "wait_for_execution", + "rejected", + "executing", + "canceled", + "exec_failed", + "finished" + ], + "type": "string", + "description": "filter workflow status", + "name": "filter_status", + "in": "query" + }, + { + "type": "string", + "description": "filter current step assignee user id", + "name": "filter_current_step_assignee_user_id", + "in": "query" + }, + { + "type": "string", + "description": "filter instance name", + "name": "filter_task_instance_name", + "in": "query" + }, + { + "type": "string", + "description": "project name", + "name": "project_name", "in": "path", "required": true }, { - "description": "update rule template request", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateProjectRuleTemplateReqV1" - } + "type": "string", + "description": "fuzzy matching subject/workflow_id/desc", + "name": "fuzzy_keyword", + "in": "query" } ], "responses": { "200": { - "description": "OK", + "description": "export workflow", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/projects/{project_name}/rule_templates/{rule_template_name}/clone": { + "/v1/projects/{project_name}/workflows/{workflow_id}/tasks/terminate": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "clone a rule template in project", - "consumes": [ - "application/json" - ], + "description": "terminate multiple task by project and workflow", "tags": [ - "rule_template" + "workflow" ], - "summary": "克隆项目规则模板", - "operationId": "cloneProjectRuleTemplateV1", + "summary": "终止工单下多个上线任务", + "operationId": "terminateMultipleTaskByWorkflowV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow id", + "name": "workflow_id", "in": "path", "required": true }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true - }, - { - "description": "clone rule template request", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CloneProjectRuleTemplateReqV1" - } } ], "responses": { @@ -4382,20 +4228,27 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/rule_templates/{rule_template_name}/export": { - "get": { + "/v1/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/terminate": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export rule template in a project", + "description": "execute one task on workflow", "tags": [ - "rule_template" + "workflow" ], - "summary": "导出项目规则模板", - "operationId": "exportProjectRuleTemplateV1", + "summary": "终止单个上线任务", + "operationId": "terminateSingleTaskByWorkflowV1", "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, { "type": "string", "description": "project name", @@ -4405,88 +4258,42 @@ var doc = `{ }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "task id", + "name": "task_id", "in": "path", "required": true } ], "responses": { "200": { - "description": "sqle rule template file", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/sql_audit_records": { + "/v1/projects/{project_name}/workflows/{workflow_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql audit records", + "description": "get workflow detail", "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "获取SQL审核记录列表", - "operationId": "getSQLAuditRecordsV1", + "summary": "获取工单详情", + "operationId": "getWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "fuzzy search tags", - "name": "fuzzy_search_tags", - "in": "query" - }, - { - "enum": [ - "auditing", - "successfully" - ], - "type": "string", - "description": "filter sql audit status", - "name": "filter_sql_audit_status", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "type": "string", - "description": "filter create time from", - "name": "filter_create_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter create time to", - "name": "filter_create_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter sql audit record ids", - "name": "filter_sql_audit_record_ids", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", + "description": "workflow name", + "name": "workflow_name", + "in": "path", "required": true }, { @@ -4501,121 +4308,79 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSQLAuditRecordsResV1" + "$ref": "#/definitions/v1.GetWorkflowResV1" } } } }, - "post": { + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "SQL audit\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.\n4. file[input_zip_file]: it is ZIP file that sql will be parsed from xml or sql file inside it.\n5. formData[git_http_url]:the url which scheme is http(s) and end with .git.\n6. formData[git_user_name]:The name of the user who owns the repository read access.\n7. formData[git_user_password]:The password corresponding to git_user_name.", + "description": "update workflow when it is rejected to creator.", "consumes": [ - "multipart/form-data" + "application/json" ], "produces": [ "application/json" ], "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "SQL审核", - "operationId": "CreateSQLAuditRecordV1", + "summary": "更新工单(驳回后才可更新)", + "operationId": "updateWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "formData" - }, - { - "type": "string", - "description": "schema of instance", - "name": "instance_schema", - "in": "formData" - }, - { - "type": "string", - "description": "db type of instance", - "name": "db_type", - "in": "formData" - }, - { - "type": "string", - "description": "sqls for audit", - "name": "sqls", - "in": "formData" - }, - { - "type": "file", - "description": "input SQL file", - "name": "input_sql_file", - "in": "formData" - }, - { - "type": "file", - "description": "input mybatis XML file", - "name": "input_mybatis_xml_file", - "in": "formData" - }, - { - "type": "file", - "description": "input ZIP file", - "name": "input_zip_file", - "in": "formData" - }, - { - "type": "string", - "description": "git repository url", - "name": "git_http_url", - "in": "formData" - }, - { - "type": "string", - "description": "the name of user to clone the repository", - "name": "git_user_name", - "in": "formData" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { - "type": "string", - "description": "the password corresponding to git_user_name", - "name": "git_user_password", - "in": "formData" + "description": "update workflow request", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateWorkflowReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.CreateSQLAuditRecordResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/sql_audit_records/tag_tips": { - "get": { + "/v1/projects/{project_name}/workflows/{workflow_name}/cancel": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql audit record tag tips", + "description": "cancel workflow", "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "获取SQL审核记录标签列表", - "operationId": "GetSQLAuditRecordTagTipsV1", + "summary": "审批关闭(中止)", + "operationId": "cancelWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", @@ -4623,43 +4388,58 @@ var doc = `{ "name": "project_name", "in": "path", "required": true + }, + { + "type": "string", + "description": "workflow name", + "name": "workflow_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSQLAuditRecordTagTipsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/sql_audit_records/{sql_audit_record_id}/": { - "get": { + "/v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/approve": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql audit record info", + "description": "approve workflow", "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "获取SQL审核记录信息", - "operationId": "getSQLAuditRecordV1", + "summary": "审批通过", + "operationId": "approveWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { "type": "string", - "description": "sql audit record id", - "name": "sql_audit_record_id", + "description": "workflow step id", + "name": "workflow_step_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", "in": "path", "required": true } @@ -4668,27 +4448,34 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSQLAuditRecordResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] + } + }, + "/v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/reject": { + "post": { + "security": [ + { + "ApiKeyAuth": [] } ], - "description": "update SQL audit record", - "consumes": [ - "application/json" - ], + "description": "reject workflow", "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "更新SQL审核记录", - "operationId": "updateSQLAuditRecordV1", + "summary": "审批驳回", + "operationId": "rejectWorkflowV1", + "deprecated": true, "parameters": [ + { + "type": "string", + "description": "workflow name", + "name": "workflow_name", + "in": "path", + "required": true + }, { "type": "string", "description": "project name", @@ -4698,18 +4485,18 @@ var doc = `{ }, { "type": "string", - "description": "sql audit record id", - "name": "sql_audit_record_id", + "description": "workflow step id", + "name": "workflow_step_id", "in": "path", "required": true }, { - "description": "update SQL audit record", - "name": "param", + "description": "workflow approve request", + "name": "workflow_approve", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateSQLAuditRecordReqV1" + "$ref": "#/definitions/v1.RejectWorkflowReqV1" } } ], @@ -4723,149 +4510,33 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/sql_manages": { + "/v1/projects/{project_name}/workflows/{workflow_name}/tasks": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql manage list", + "description": "get summary of workflow instance tasks", "tags": [ - "SqlManage" + "workflow" ], - "summary": "获取管控sql列表", - "operationId": "GetSqlManageList", + "summary": "获取工单数据源任务概览", + "operationId": "getSummaryOfInstanceTasksV1", "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { "type": "string", - "description": "fuzzy search sql fingerprint", - "name": "fuzzy_search_sql_fingerprint", - "in": "query" - }, - { - "type": "string", - "description": "assignee", - "name": "filter_assignee", - "in": "query" - }, - { - "type": "string", - "description": "instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "enum": [ - "audit_plan", - "sql_audit_record" - ], - "type": "string", - "description": "source", - "name": "filter_source", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "audit level", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time from", - "name": "filter_last_audit_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time to", - "name": "filter_last_audit_start_time_to", - "in": "query" - }, - { - "enum": [ - "unhandled", - "solved", - "ignored", - "manual_audited" - ], - "type": "string", - "description": "status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "rule name", - "name": "filter_rule_name", - "in": "query" - }, - { - "type": "string", - "description": "db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search endpoint", - "name": "fuzzy_search_endpoint", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search schema name", - "name": "fuzzy_search_schema_name", - "in": "query" - }, - { - "enum": [ - "first_appear_timestamp", - "last_receive_timestamp", - "fp_count" - ], - "type": "string", - "description": "sort field", - "name": "sort_field", - "in": "query" - }, - { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "description": "sort order", - "name": "sort_order", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", + "description": "project name", + "name": "project_name", + "in": "path", "required": true } ], @@ -4873,41 +4544,40 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlManageListResp" + "$ref": "#/definitions/v1.GetWorkflowTasksResV1" } } } } }, - "/v1/projects/{project_name}/sql_manages/batch": { - "patch": { + "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/execute": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "batch update sql manage", + "description": "execute tasks on workflow", "tags": [ - "SqlManage" + "workflow" ], - "summary": "批量更新SQL管控", - "operationId": "BatchUpdateSqlManage", + "summary": "多数据源批量上线", + "operationId": "executeTasksOnWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { - "description": "batch update sql manage request", - "name": "BatchUpdateSqlManageReq", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.BatchUpdateSqlManageReq" - } + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true } ], "responses": { @@ -4920,165 +4590,140 @@ var doc = `{ } } }, - "/v1/projects/{project_name}/sql_manages/exports": { - "get": { + "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/execute": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export sql manage", + "description": "execute one task on workflow", "tags": [ - "SqlManage" + "workflow" ], - "summary": "导出SQL管控", - "operationId": "exportSqlManageV1", + "summary": "工单提交单个数据源上线", + "operationId": "executeOneTaskOnWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { "type": "string", - "description": "fuzzy search sql fingerprint", - "name": "fuzzy_search_sql_fingerprint", - "in": "query" - }, - { - "type": "string", - "description": "assignee", - "name": "filter_assignee", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { "type": "string", - "description": "instance name", - "name": "filter_instance_name", - "in": "query" - }, + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/controller.BaseRes" + } + } + } + } + }, + "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/schedule": { + "put": { + "security": [ { - "enum": [ - "audit_plan", - "sql_audit_record" - ], - "type": "string", - "description": "source", - "name": "filter_source", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "audit level", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time from", - "name": "filter_last_audit_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time to", - "name": "filter_last_audit_start_time_to", - "in": "query" - }, - { - "enum": [ - "unhandled", - "solved", - "ignored", - "manual_audited" - ], - "type": "string", - "description": "status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "rule name", - "name": "filter_rule_name", - "in": "query" - }, + "ApiKeyAuth": [] + } + ], + "description": "update workflow schedule.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "workflow" + ], + "summary": "设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置)", + "operationId": "updateWorkflowScheduleV1", + "deprecated": true, + "parameters": [ { "type": "string", - "description": "fuzzy search endpoint", - "name": "fuzzy_search_endpoint", - "in": "query" + "description": "workflow name", + "name": "workflow_name", + "in": "path", + "required": true }, { "type": "string", - "description": "fuzzy search schema name", - "name": "fuzzy_search_schema_name", - "in": "query" + "description": "task id", + "name": "task_id", + "in": "path", + "required": true }, { - "enum": [ - "first_appear_timestamp", - "last_receive_timestamp", - "fp_count" - ], "type": "string", - "description": "sort field", - "name": "sort_field", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "description": "sort order", - "name": "sort_order", - "in": "query" + "description": "update workflow schedule request", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateWorkflowScheduleReqV1" + } } ], "responses": { "200": { - "description": "export sql manage", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/sql_manages/rule_tips": { + "/v1/rule_knowledge/db_types/{db_type}/custom_rules/{rule_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql manage rule tips", + "description": "get custom rule knowledge", "tags": [ - "SqlManage" + "rule_template" ], - "summary": "获取管控规则tips", - "operationId": "GetSqlManageRuleTips", + "summary": "查看自定义规则知识库", + "operationId": "getCustomRuleKnowledgeV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule name", + "name": "rule_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "db type of rule", + "name": "db_type", "in": "path", "required": true } @@ -5087,69 +4732,83 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlManageRuleTipsResp" + "$ref": "#/definitions/v1.GetRuleKnowledgeResV1" } } } - } - }, - "/v1/projects/{project_name}/sql_manages/{sql_manage_id}/sql_analysis": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql manage analysis", + "description": "update custom rule knowledge", "tags": [ - "SqlManage" + "rule_template" ], - "summary": "获取SQL管控SQL分析", - "operationId": "GetSqlManageSqlAnalysisV1", + "summary": "更新自定义规则知识库", + "operationId": "updateCustomRuleKnowledge", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule name", + "name": "rule_name", "in": "path", "required": true }, { "type": "string", - "description": "sql manage id", - "name": "sql_manage_id", + "description": "db type of rule", + "name": "db_type", "in": "path", "required": true + }, + { + "description": "update rule knowledge", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateRuleKnowledgeReq" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlManageSqlAnalysisResp" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/statistic/audit_plans": { + "/v1/rule_knowledge/db_types/{db_type}/rules/{rule_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "statistic audit plan", + "description": "get rule knowledge", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取各类型数据源上的扫描任务数量", - "operationId": "statisticAuditPlanV1", + "summary": "查看规则知识库", + "operationId": "getRuleKnowledgeV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule name", + "name": "rule_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "db type of rule", + "name": "db_type", "in": "path", "required": true } @@ -5158,95 +4817,115 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.StatisticAuditPlanResV1" + "$ref": "#/definitions/v1.GetRuleKnowledgeResV1" } } } - } - }, - "/v1/projects/{project_name}/statistic/audited_sqls": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "statistics audited sql", + "description": "update rule knowledge", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取审核SQL总数,以及触发审核规则的SQL数量", - "operationId": "statisticsAuditedSQLV1", + "summary": "更新规则知识库", + "operationId": "updateRuleKnowledge", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule name", + "name": "rule_name", "in": "path", "required": true + }, + { + "type": "string", + "description": "db type of rule", + "name": "db_type", + "in": "path", + "required": true + }, + { + "description": "update rule knowledge", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateRuleKnowledgeReq" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.StatisticsAuditedSQLResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/statistic/instance_health": { + "/v1/rule_template_tips": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance health", + "description": "get global rule template tips", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取各类型数据源的健康情况", - "operationId": "GetInstanceHealthV1", + "summary": "获取全局规则模板提示", + "operationId": "getRuleTemplateTipsV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "filter db type", + "name": "filter_db_type", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstanceHealthResV1" + "$ref": "#/definitions/v1.GetRuleTemplateTipsResV1" } } } } }, - "/v1/projects/{project_name}/statistic/project_score": { + "/v1/rule_templates": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get project score", + "description": "get all global rule template", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取项目分数", - "operationId": "GetProjectScoreV1", + "summary": "全局规则模板列表", + "operationId": "getRuleTemplateListV1", "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", "required": true } ], @@ -5254,63 +4933,69 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectScoreResV1" + "$ref": "#/definitions/v1.GetRuleTemplatesResV1" } } } - } - }, - "/v1/projects/{project_name}/statistic/risk_audit_plans": { - "get": { + }, + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get risk audit plan", + "description": "create a global rule template", + "consumes": [ + "application/json" + ], "tags": [ - "statistic" + "rule_template" ], - "summary": "获取扫描任务报告评分低于60的扫描任务", - "operationId": "getRiskAuditPlanV1", + "summary": "添加全局规则模板", + "operationId": "createRuleTemplateV1", "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "add rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.CreateRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRiskAuditPlanResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/statistic/risk_workflow": { - "get": { + "/v1/rule_templates/parse": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "statistic risk workflow", + "description": "parse rule template", + "consumes": [ + "multipart/form-data" + ], "tags": [ - "statistic" + "rule_template" ], - "summary": "获取存在风险的工单", - "operationId": "statisticRiskWorkflowV1", + "summary": "解析规则模板文件", + "operationId": "importProjectRuleTemplateV1", "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "type": "file", + "description": "SQLE rule template file", + "name": "rule_template_file", + "in": "formData", "required": true } ], @@ -5318,62 +5003,66 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.StatisticRiskWorkflowResV1" + "$ref": "#/definitions/v1.ParseProjectRuleTemplateFileResV1" } } } } }, - "/v1/projects/{project_name}/statistic/role_user": { + "/v1/rule_templates/{rule_template_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get role user count", + "description": "get global rule template", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取各角色类型对应的成员数量", - "operationId": "getRoleUserCountV1", + "summary": "获取全局规则模板信息", + "operationId": "getRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true + }, + { + "type": "string", + "description": "fuzzy rule,keyword for desc and annotation", + "name": "fuzzy_keyword_rule", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRoleUserCountResV1" + "$ref": "#/definitions/v1.GetRuleTemplateResV1" } } } - } - }, - "/v1/projects/{project_name}/statistic/workflow_status": { - "get": { + }, + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "statistic workflow status", + "description": "delete global rule template", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取项目下工单各个状态的数量", - "operationId": "statisticWorkflowStatusV1", + "summary": "删除全局规则模板", + "operationId": "deleteRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true } @@ -5382,78 +5071,82 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowStatusCountResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - } - }, - "/v1/projects/{project_name}/statistics": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get project statistics", + "description": "update global rule template", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取项目统计信息", - "operationId": "getProjectStatisticsV1", + "summary": "更新全局规则模板", + "operationId": "updateRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true + }, + { + "description": "update rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectStatisticsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/task_groups": { + "/v1/rule_templates/{rule_template_name}/clone": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create tasks group.", + "description": "clone a rule template", "consumes": [ "application/json" ], - "produces": [ - "application/json" - ], "tags": [ - "task" + "rule_template" ], - "summary": "创建审核任务组", - "operationId": "createAuditTasksV1", + "summary": "克隆全局规则模板", + "operationId": "CloneRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true }, { - "description": "parameters for creating audit tasks group", + "description": "clone rule template request", "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateAuditTasksGroupReqV1" + "$ref": "#/definitions/v1.CloneRuleTemplateReqV1" } } ], @@ -5461,189 +5154,166 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.CreateAuditTasksGroupResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/tasks/audits": { - "post": { + "/v1/rule_templates/{rule_template_name}/export": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create and audit a task, you can upload sql content in three ways, any one can be used, but only one is effective.\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.", - "consumes": [ - "multipart/form-data" - ], - "produces": [ - "application/json" - ], + "description": "export rule template", "tags": [ - "task" + "rule_template" ], - "summary": "创建Sql扫描任务并提交审核", - "operationId": "createAndAuditTaskV1", + "summary": "导出全局规则模板", + "operationId": "exportRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "formData", - "required": true - }, - { - "type": "string", - "description": "schema of instance", - "name": "instance_schema", - "in": "formData" - }, - { - "type": "string", - "description": "sqls for audit", - "name": "sql", - "in": "formData" - }, - { - "type": "file", - "description": "input SQL file", - "name": "input_sql_file", - "in": "formData" - }, - { - "type": "file", - "description": "input mybatis XML file", - "name": "input_mybatis_xml_file", - "in": "formData" - }, - { - "type": "file", - "description": "input ZIP file", - "name": "input_zip_file", - "in": "formData" } ], "responses": { "200": { - "description": "OK", + "description": "sqle rule template file", "schema": { - "$ref": "#/definitions/v1.GetAuditTaskResV1" + "type": "file" } } } } }, - "/v1/projects/{project_name}/unarchive": { - "post": { + "/v1/rules": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "archive project", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get all rule template", "tags": [ - "project" + "rule_template" ], - "summary": "取消归档项目", - "operationId": "unarchiveProjectV1", + "summary": "规则列表", + "operationId": "getRuleListV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { + "description": "filter db type", + "name": "filter_db_type", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy rule,keyword for desc and annotation", + "name": "fuzzy_keyword_rule", + "in": "query" + }, + { + "type": "string", + "description": "filter global rule template name", + "name": "filter_global_rule_template_name", + "in": "query" + }, + { + "type": "string", + "description": "filter rule name list", + "name": "filter_rule_names", + "in": "query" + } + ], + "responses": { + "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetRulesResV1" } } } } }, - "/v1/projects/{project_name}/workflow_template": { + "/v1/sql_analysis": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow template detail", + "description": "Direct get sql analysis result", "tags": [ - "workflow" + "sql_analysis" ], - "summary": "获取审批流程模板详情", - "operationId": "getWorkflowTemplateV1", + "summary": "直接获取SQL分析结果", + "operationId": "directGetSQLAnalysisV1", "parameters": [ { "type": "string", "description": "project name", "name": "project_name", - "in": "path", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "instance name", + "name": "instance_name", + "in": "query", "required": true + }, + { + "type": "string", + "description": "schema name", + "name": "schema_name", + "in": "query" + }, + { + "type": "string", + "description": "sql", + "name": "sql", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowTemplateResV1" + "$ref": "#/definitions/v1.DirectGetSQLAnalysisResV1" } } } - }, - "patch": { + } + }, + "/v1/sql_audit": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update the workflow template", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "Direct audit sql", "tags": [ - "workflow" + "sql_audit" ], - "summary": "更新Sql审批流程模板", - "operationId": "updateWorkflowTemplateV1", + "summary": "直接审核SQL", + "operationId": "directAuditV1", + "deprecated": true, "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "create workflow template", - "name": "instance", + "description": "sqls that should be audited", + "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateWorkflowTemplateReqV1" + "$ref": "#/definitions/v1.DirectAuditReqV1" } } ], @@ -5651,166 +5321,63 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.DirectAuditResV1" } } } } }, - "/v1/projects/{project_name}/workflows": { + "/v1/statistic/instances/sql_average_execution_time": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow list", + "description": "get average execution time of sql", "tags": [ - "workflow" + "statistic" ], - "summary": "获取工单列表", - "operationId": "getWorkflowsV1", + "summary": "获取sql上线平均耗时,按平均耗时降序排列", + "operationId": "getSqlAverageExecutionTimeV1", "parameters": [ - { - "type": "string", - "description": "filter subject", - "name": "filter_subject", - "in": "query" - }, - { - "type": "string", - "description": "filter by workflow_id", - "name": "filter_workflow_id", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search by workflow description", - "name": "fuzzy_search_workflow_desc", - "in": "query" - }, - { - "type": "string", - "description": "filter create time from", - "name": "filter_create_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter create time to", - "name": "filter_create_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_from", - "name": "filter_task_execute_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_to", - "name": "filter_task_execute_start_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter create user name", - "name": "filter_create_user_name", - "in": "query" - }, - { - "enum": [ - "wait_for_audit", - "wait_for_execution", - "rejected", - "executing", - "canceled", - "exec_failed", - "finished" - ], - "type": "string", - "description": "filter workflow status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "filter current step assignee user name", - "name": "filter_current_step_assignee_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_task_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, { "type": "integer", - "description": "size of per page", - "name": "page_size", + "description": "the limit of result item number", + "name": "limit", "in": "query", "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowsResV1" + "$ref": "#/definitions/v1.GetSqlAverageExecutionTimeResV1" } } } - }, - "post": { + } + }, + "/v1/statistic/instances/sql_execution_fail_percent": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create workflow", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get sql execution fail percent", "tags": [ - "workflow" + "statistic" ], - "summary": "创建工单", - "operationId": "createWorkflowV1", - "deprecated": true, + "summary": "获取SQL上线失败率,按失败率降序排列", + "operationId": "getSqlExecutionFailPercentV1", "parameters": [ { - "description": "create workflow request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateWorkflowReqV1" - } - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "type": "integer", + "description": "the limit of result item number", + "name": "limit", + "in": "query", "required": true } ], @@ -5818,309 +5385,177 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetSqlExecutionFailPercentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/cancel": { - "post": { + "/v1/statistic/instances/type_percent": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "batch cancel workflows", + "description": "get database instances' types percent", "tags": [ - "workflow" - ], - "summary": "批量取消工单", - "operationId": "batchCancelWorkflowsV1", - "deprecated": true, - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "batch cancel workflows request", - "name": "BatchCancelWorkflowsReqV1", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.BatchCancelWorkflowsReqV1" - } - } + "statistic" ], + "summary": "获取数据源类型百分比", + "operationId": "getInstancesTypePercentV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetInstancesTypePercentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/complete": { - "post": { + "/v1/statistic/license/usage": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "this api will directly change the work order status to finished without real online operation", + "description": "get usage of license", "tags": [ - "workflow" + "statistic" ], - "summary": "批量完成工单", - "operationId": "batchCompleteWorkflowsV1", - "deprecated": true, - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "batch complete workflows request", - "name": "data", - "in": "body", - "required": true, + "summary": "获取License使用情况", + "operationId": "getLicenseUsageV1", + "responses": { + "200": { + "description": "OK", "schema": { - "$ref": "#/definitions/v1.BatchCompleteWorkflowsReqV1" + "$ref": "#/definitions/v1.GetLicenseUsageResV1" } } + } + } + }, + "/v1/statistic/workflows/audit_pass_percent": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "get workflow audit pass percent", + "tags": [ + "statistic" ], + "summary": "获取工单审核通过率", + "operationId": "getWorkflowAuditPassPercentV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowAuditPassPercentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/exports": { + "/v1/statistic/workflows/counts": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export workflow", + "description": "get workflow counts", "tags": [ - "workflow" - ], - "summary": "导出工单", - "operationId": "exportWorkflowV1", - "parameters": [ - { - "type": "string", - "description": "filter subject", - "name": "filter_subject", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search by workflow description", - "name": "fuzzy_search_workflow_desc", - "in": "query" - }, - { - "type": "string", - "description": "filter create time from", - "name": "filter_create_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter create time to", - "name": "filter_create_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_from", - "name": "filter_task_execute_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_to", - "name": "filter_task_execute_start_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter create user name", - "name": "filter_create_user_name", - "in": "query" - }, - { - "enum": [ - "wait_for_audit", - "wait_for_execution", - "rejected", - "executing", - "canceled", - "exec_failed", - "finished" - ], - "type": "string", - "description": "filter workflow status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "filter current step assignee user name", - "name": "filter_current_step_assignee_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_task_instance_name", - "in": "query" - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } + "statistic" ], + "summary": "获取工单数量统计数据", + "operationId": "getWorkflowCountV1", "responses": { "200": { - "description": "export workflow", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/v1.GetWorkflowCountsResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_id}/tasks/terminate": { - "post": { + "/v1/statistic/workflows/duration_of_waiting_for_audit": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "terminate multiple task by project and workflow", + "description": "get duration from workflow being created to audited", "tags": [ - "workflow" - ], - "summary": "终止工单下多个上线任务", - "operationId": "terminateMultipleTaskByWorkflowV1", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } + "statistic" ], + "summary": "获取工单从创建到审核结束的平均时长", + "operationId": "getWorkflowDurationOfWaitingForAuditV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowDurationOfWaitingForAuditResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/terminate": { - "post": { + "/v1/statistic/workflows/duration_of_waiting_for_execution": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "execute one task on workflow", + "description": "get duration from workflow being created to executed", "tags": [ - "workflow" - ], - "summary": "终止单个上线任务", - "operationId": "terminateSingleTaskByWorkflowV1", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } + "statistic" ], + "summary": "获取工单各从审核完毕到执行上线的平均时长", + "operationId": "getWorkflowDurationOfWaitingForExecutionV1", + "deprecated": true, "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowDurationOfWaitingForExecutionResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/": { + "/v1/statistic/workflows/each_day_counts": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow detail", + "description": "get counts of created workflow each day", "tags": [ - "workflow" + "statistic" ], - "summary": "获取工单详情", - "operationId": "getWorkflowV1", - "deprecated": true, + "summary": "获取每天工单创建数量", + "operationId": "getWorkflowCreatedCountEachDayV1", "parameters": [ { "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", + "description": "filter date from.(format:yyyy-mm-dd)", + "name": "filter_date_from", + "in": "query", "required": true }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "description": "filter date to.(format:yyyy-mm-dd)", + "name": "filter_date_to", + "in": "query", "required": true } ], @@ -6128,92 +5563,78 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowResV1" + "$ref": "#/definitions/v1.GetWorkflowCreatedCountsEachDayResV1" } } } - }, - "patch": { + } + }, + "/v1/statistic/workflows/instance_type_percent": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update workflow when it is rejected to creator.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get workflows percent counted by instance type", "tags": [ - "workflow" + "statistic" ], - "summary": "更新工单(驳回后才可更新)", - "operationId": "updateWorkflowV1", - "deprecated": true, - "parameters": [ - { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "update workflow request", - "name": "instance", - "in": "body", - "required": true, + "summary": "获取按数据源类型统计的工单百分比", + "operationId": "getWorkflowPercentCountedByInstanceTypeV1", + "responses": { + "200": { + "description": "OK", "schema": { - "$ref": "#/definitions/v1.UpdateWorkflowReqV1" + "$ref": "#/definitions/v1.GetWorkflowPercentCountedByInstanceTypeResV1" } } + } + } + }, + "/v1/statistic/workflows/pass_percent": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } ], + "description": "get workflow pass percent", + "tags": [ + "statistic" + ], + "summary": "获取工单通过率", + "operationId": "getWorkflowPassPercentV1", + "deprecated": true, "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowPassPercentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/cancel": { - "post": { + "/v1/statistic/workflows/rejected_percent_group_by_creator": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "cancel workflow", + "description": "get workflows rejected percent group by creator. The result will be sorted by rejected percent in descending order", "tags": [ - "workflow" + "statistic" ], - "summary": "审批关闭(中止)", - "operationId": "cancelWorkflowV1", - "deprecated": true, + "summary": "获取各个用户提交的工单驳回率,按驳回率降序排列", + "operationId": "getWorkflowRejectedPercentGroupByCreatorV1", "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", + "type": "integer", + "description": "the limit of result item number", + "name": "limit", + "in": "query", "required": true } ], @@ -6221,141 +5642,148 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowRejectedPercentGroupByCreatorResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/approve": { - "post": { + "/v1/statistic/workflows/rejected_percent_group_by_instance": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "approve workflow", + "description": "get workflow rejected percent group by instance. The result will be sorted by rejected percent in descending order", "tags": [ - "workflow" + "statistic" ], - "summary": "审批通过", - "operationId": "approveWorkflowV1", + "summary": "获取各个数据源相关的工单驳回率,按驳回率降序排列", + "operationId": "getWorkflowRejectedPercentGroupByInstanceV1", "deprecated": true, "parameters": [ { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow step id", - "name": "workflow_step_id", - "in": "path", + "type": "integer", + "description": "the limit of result item number", + "name": "limit", + "in": "query", "required": true - }, + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/v1.GetWorkflowRejectedPercentGroupByInstanceResV1" + } + } + } + } + }, + "/v1/statistic/workflows/status_count": { + "get": { + "security": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "ApiKeyAuth": [] } ], + "description": "get count of workflow status", + "tags": [ + "statistic" + ], + "summary": "获取各种状态工单的数量", + "operationId": "getWorkflowStatusCountV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowStatusCountResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/reject": { + "/v1/task_groups/audit": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "reject workflow", + "description": "audit task group.\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.\n4. file[input_zip_file]: it is zip file, sql will be parsed from it.", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], "tags": [ - "workflow" + "task" ], - "summary": "审批驳回", - "operationId": "rejectWorkflowV1", - "deprecated": true, + "summary": "审核任务组", + "operationId": "auditTaskGroupIdV1", "parameters": [ { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", + "type": "integer", + "description": "group id of tasks", + "name": "task_group_id", + "in": "formData", "required": true }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "sqls for audit", + "name": "sql", + "in": "formData" }, { - "type": "string", - "description": "workflow step id", - "name": "workflow_step_id", - "in": "path", - "required": true + "type": "file", + "description": "input SQL file", + "name": "input_sql_file", + "in": "formData" }, { - "description": "workflow approve request", - "name": "workflow_approve", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.RejectWorkflowReqV1" - } + "type": "file", + "description": "input mybatis XML file", + "name": "input_mybatis_xml_file", + "in": "formData" + }, + { + "type": "file", + "description": "input ZIP file", + "name": "input_zip_file", + "in": "formData" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.AuditTaskGroupResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/tasks": { + "/v1/tasks/audits/{task_id}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get summary of workflow instance tasks", + "description": "get task", "tags": [ - "workflow" + "task" ], - "summary": "获取工单数据源任务概览", - "operationId": "getSummaryOfInstanceTasksV1", - "deprecated": true, + "summary": "获取Sql扫描任务信息", + "operationId": "getAuditTaskV1", "parameters": [ { "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", + "description": "task id", + "name": "task_id", "in": "path", "required": true } @@ -6364,38 +5792,30 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowTasksResV1" + "$ref": "#/definitions/v1.GetAuditTaskResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/execute": { - "post": { + "/v1/tasks/audits/{task_id}/sql_content": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "execute tasks on workflow", + "description": "get SQL content for the audit task", "tags": [ - "workflow" + "task" ], - "summary": "多数据源批量上线", - "operationId": "executeTasksOnWorkflowV1", - "deprecated": true, + "summary": "获取指定扫描任务的SQL内容", + "operationId": "getAuditTaskSQLContentV1", "parameters": [ { "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", + "description": "task id", + "name": "task_id", "in": "path", "required": true } @@ -6404,41 +5824,26 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetAuditTaskSQLContentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/execute": { - "post": { + "/v1/tasks/audits/{task_id}/sql_file": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "execute one task on workflow", + "description": "download SQL file for the audit task", "tags": [ - "workflow" + "task" ], - "summary": "工单提交单个数据源上线", - "operationId": "executeOneTaskOnWorkflowV1", - "deprecated": true, + "summary": "下载指定扫描任务的SQL文件", + "operationId": "downloadAuditTaskSQLFileV1", "parameters": [ - { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, { "type": "string", "description": "task id", @@ -6449,42 +5854,28 @@ var doc = `{ ], "responses": { "200": { - "description": "OK", + "description": "sql file", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/schedule": { - "put": { + "/v1/tasks/audits/{task_id}/sql_report": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update workflow schedule.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "download report file of all SQLs information belong to the specified audit task", "tags": [ - "workflow" + "task" ], - "summary": "设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置)", - "operationId": "updateWorkflowScheduleV1", - "deprecated": true, + "summary": "下载指定扫描任务的SQLs信息报告", + "operationId": "downloadAuditTaskSQLReportV1", "parameters": [ - { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, { "type": "string", "description": "task id", @@ -6493,91 +5884,95 @@ var doc = `{ "required": true }, { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "update workflow schedule request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateWorkflowScheduleReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/role_tips": { - "get": { - "security": [ - { - "ApiKeyAuth": [] + "type": "boolean", + "description": "select unique (fingerprint and audit result) for task sql", + "name": "no_duplicate", + "in": "query" } ], - "description": "get role tip list", - "tags": [ - "role" - ], - "summary": "获取角色提示列表", - "operationId": "getRoleTipListV1", "responses": { "200": { - "description": "OK", + "description": "sql report csv file", "schema": { - "$ref": "#/definitions/v1.GetRoleTipsResV1" + "type": "file" } } } } }, - "/v1/roles": { + "/v1/tasks/audits/{task_id}/sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get role list", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get information of all SQLs belong to the specified audit task", "tags": [ - "role" + "task" ], - "summary": "获取角色列表", - "operationId": "getRoleListV1", + "summary": "获取指定扫描任务的SQLs信息", + "operationId": "getAuditTaskSQLsV1", "parameters": [ { "type": "string", - "description": "filter role name", - "name": "filter_role_name", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "enum": [ + "initialized", + "doing", + "succeeded", + "failed", + "manually_executed" + ], + "type": "string", + "description": "filter: exec status of task sql", + "name": "filter_exec_status", + "in": "query" + }, + { + "enum": [ + "initialized", + "doing", + "finished" + ], + "type": "string", + "description": "filter: audit status of task sql", + "name": "filter_audit_status", "in": "query" }, { - "type": "integer", + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "type": "string", + "description": "filter: audit level of task sql", + "name": "filter_audit_level", + "in": "query" + }, + { + "type": "boolean", + "description": "select unique (fingerprint and audit result) for task sql", + "name": "no_duplicate", + "in": "query" + }, + { + "type": "string", "description": "page index", "name": "page_index", "in": "query", "required": true }, { - "type": "integer", - "description": "size of per page", + "type": "string", + "description": "page size", "name": "page_size", "in": "query", "required": true @@ -6587,37 +5982,50 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRolesResV1" + "$ref": "#/definitions/v1.GetAuditTaskSQLsResV1" } } } - }, - "post": { + } + }, + "/v1/tasks/audits/{task_id}/sqls/{number}": { + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create role", + "description": "modify the relevant information of a certain SQL in the audit task", "consumes": [ "application/json" ], - "produces": [ - "application/json" - ], "tags": [ - "role" + "task" ], - "summary": "创建角色", - "operationId": "createRoleV1", + "summary": "修改扫描任务中某条SQL的相关信息", + "operationId": "updateAuditTaskSQLsV1", "parameters": [ { - "description": "create role", - "name": "instance", + "type": "string", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "sql number", + "name": "number", + "in": "path", + "required": true + }, + { + "description": "modify the relevant information of a certain SQL in the audit task", + "name": "audit_plan", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateRoleReqV1" + "$ref": "#/definitions/v1.UpdateAuditTaskSQLsReqV1" } } ], @@ -6631,30 +6039,31 @@ var doc = `{ } } }, - "/v1/roles/{role_name}/": { - "delete": { + "/v1/tasks/audits/{task_id}/sqls/{number}/analysis": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete role", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get SQL explain and related table metadata for analysis", "tags": [ - "role" + "task" ], - "summary": "删除角色", - "operationId": "deleteRoleV1", + "summary": "获取task相关的SQL执行计划和表元数据", + "operationId": "getTaskAnalysisData", "parameters": [ { "type": "string", - "description": "role name", - "name": "role_name", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "sql number", + "name": "number", "in": "path", "required": true } @@ -6663,129 +6072,167 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetTaskAnalysisDataResV1" } } } - }, - "patch": { + } + }, + "/v1/user_tips": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update role", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get user tip list", "tags": [ - "role" + "user" ], - "summary": "更新角色信息", - "operationId": "updateRoleV1", + "summary": "获取用户提示列表", + "operationId": "getUserTipListV1", "parameters": [ { "type": "string", - "description": "role name", - "name": "role_name", - "in": "path", + "description": "project name", + "name": "filter_project", + "in": "query", "required": true - }, - { - "description": "update role request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateRoleReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetUserTipsResV1" } } } } }, - "/v1/rule_knowledge/db_types/{db_type}/custom_rules/{rule_name}/": { + "/v1/workflows": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get custom rule knowledge", + "description": "get global workflow list", "tags": [ - "rule_template" + "workflow" ], - "summary": "查看自定义规则知识库", - "operationId": "getCustomRuleKnowledgeV1", + "summary": "获取全局工单列表", + "operationId": "getGlobalWorkflowsV1", "parameters": [ { "type": "string", - "description": "rule name", - "name": "rule_name", - "in": "path", - "required": true + "description": "filter subject", + "name": "filter_subject", + "in": "query" }, { "type": "string", - "description": "db type of rule", - "name": "db_type", - "in": "path", - "required": true - } - ], + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter create time to", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_from", + "name": "filter_task_execute_start_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_to", + "name": "filter_task_execute_start_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter create user id", + "name": "filter_create_user_id", + "in": "query" + }, + { + "enum": [ + "wait_for_audit", + "wait_for_execution", + "rejected", + "executing", + "canceled", + "exec_failed", + "finished" + ], + "type": "string", + "description": "filter workflow status", + "name": "filter_status", + "in": "query" + }, + { + "type": "string", + "description": "filter current step assignee user id", + "name": "filter_current_step_assignee_user_id", + "in": "query" + }, + { + "type": "string", + "description": "filter instance id", + "name": "filter_task_instance_name", + "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true + } + ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleKnowledgeResV1" + "$ref": "#/definitions/v1.GetWorkflowsResV1" } } } - }, - "patch": { + } + }, + "/v2/audit_files": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update custom rule knowledge", + "description": "Direct audit sql from SQL files and MyBatis files", "tags": [ - "rule_template" + "sql_audit" ], - "summary": "更新自定义规则知识库", - "operationId": "updateCustomRuleKnowledge", + "summary": "直接从文件内容提取SQL并审核,SQL文件暂时只支持一次解析一个文件", + "operationId": "directAuditFilesV2", "parameters": [ { - "type": "string", - "description": "rule name", - "name": "rule_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "db type of rule", - "name": "db_type", - "in": "path", - "required": true - }, - { - "description": "update rule knowledge", + "description": "files that should be audited", "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateRuleKnowledgeReq" + "$ref": "#/definitions/v2.DirectAuditFileReqV2" } } ], @@ -6793,142 +6240,140 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v2.DirectAuditResV2" } } } } }, - "/v1/rule_knowledge/db_types/{db_type}/rules/{rule_name}/": { + "/v2/configurations/drivers": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get rule knowledge", + "description": "get drivers", "tags": [ - "rule_template" - ], - "summary": "查看规则知识库", - "operationId": "getRuleKnowledgeV1", - "parameters": [ - { - "type": "string", - "description": "rule name", - "name": "rule_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "db type of rule", - "name": "db_type", - "in": "path", - "required": true - } + "configuration" ], + "summary": "获取当前 server 支持的审核类型", + "operationId": "getDriversV2", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleKnowledgeResV1" + "$ref": "#/definitions/v2.GetDriversRes" } } } - }, - "patch": { + } + }, + "/v2/projects/{project_name}/audit_plans": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update rule knowledge", + "description": "get audit plan info list", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "更新规则知识库", - "operationId": "updateRuleKnowledge", + "summary": "获取扫描任务信息列表", + "operationId": "getAuditPlansV2", "parameters": [ { "type": "string", - "description": "rule name", - "name": "rule_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true }, { "type": "string", - "description": "db type of rule", - "name": "db_type", - "in": "path", - "required": true + "description": "filter audit plan db type", + "name": "filter_audit_plan_db_type", + "in": "query" }, { - "description": "update rule knowledge", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateRuleKnowledgeReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/rule_template_tips": { - "get": { - "security": [ + "type": "string", + "description": "fuzzy search audit plan name", + "name": "fuzzy_search_audit_plan_name", + "in": "query" + }, { - "ApiKeyAuth": [] - } - ], - "description": "get global rule template tips", - "tags": [ - "rule_template" - ], - "summary": "获取全局规则模板提示", - "operationId": "getRuleTemplateTipsV1", - "parameters": [ + "type": "string", + "description": "filter audit plan type", + "name": "filter_audit_plan_type", + "in": "query" + }, { "type": "string", - "description": "filter db type", - "name": "filter_db_type", + "description": "filter audit plan instance name", + "name": "filter_audit_plan_instance_name", "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleTemplateTipsResV1" + "$ref": "#/definitions/v2.GetAuditPlansResV2" } } } } }, - "/v1/rule_templates": { + "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get all global rule template", + "description": "get audit plan report SQLs", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "全局规则模板列表", - "operationId": "getRuleTemplateListV1", + "summary": "获取指定扫描任务的SQL扫描详情", + "operationId": "getAuditPlanReportsSQLs", "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + }, { "type": "integer", "description": "page index", @@ -6948,100 +6393,51 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleTemplatesResV1" + "$ref": "#/definitions/v2.GetAuditPlanReportSQLsResV2" } } } - }, - "post": { + } + }, + "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create a global rule template", - "consumes": [ - "application/json" - ], + "description": "get SQL explain and related table metadata for analysis", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "添加全局规则模板", - "operationId": "createRuleTemplateV1", + "summary": "获取task相关的SQL执行计划和表元数据", + "operationId": "getAuditPlantAnalysisDataV2", "parameters": [ { - "description": "add rule template request", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateRuleTemplateReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/rule_templates/parse": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "parse rule template", - "consumes": [ - "multipart/form-data" - ], - "tags": [ - "rule_template" - ], - "summary": "解析规则模板文件", - "operationId": "importProjectRuleTemplateV1", - "parameters": [ + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, { - "type": "file", - "description": "SQLE rule template file", - "name": "rule_template_file", - "in": "formData", + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.ParseProjectRuleTemplateFileResV1" - } - } - } - } - }, - "/v1/rule_templates/{rule_template_name}/": { - "get": { - "security": [ + }, { - "ApiKeyAuth": [] - } - ], - "description": "get global rule template", - "tags": [ - "rule_template" - ], - "summary": "获取全局规则模板信息", - "operationId": "getRuleTemplateV1", - "parameters": [ + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "sql number", + "name": "number", "in": "path", "required": true } @@ -7050,68 +6446,47 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleTemplateResV1" + "$ref": "#/definitions/v2.GetAuditPlanAnalysisDataResV2" } } } - }, - "delete": { + } + }, + "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete global rule template", + "description": "full sync audit plan SQLs", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "删除全局规则模板", - "operationId": "deleteRuleTemplateV1", + "summary": "全量同步SQL到扫描任务", + "operationId": "fullSyncAuditPlanSQLsV2", "parameters": [ { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update global rule template", - "tags": [ - "rule_template" - ], - "summary": "更新全局规则模板", - "operationId": "updateRuleTemplateV1", - "parameters": [ + }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "audit plan name", + "name": "audit_plan_name", "in": "path", "required": true }, { - "description": "update rule template request", - "name": "req", + "description": "full sync audit plan SQLs request", + "name": "sqls", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateRuleTemplateReqV1" + "$ref": "#/definitions/v2.FullSyncAuditPlanSQLsReqV2" } } ], @@ -7125,37 +6500,41 @@ var doc = `{ } } }, - "/v1/rule_templates/{rule_template_name}/clone": { + "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "clone a rule template", - "consumes": [ - "application/json" - ], + "description": "partial sync audit plan SQLs", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "克隆全局规则模板", - "operationId": "CloneRuleTemplateV1", + "summary": "增量同步SQL到扫描任务", + "operationId": "partialSyncAuditPlanSQLsV2", "parameters": [ { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true }, { - "description": "clone rule template request", - "name": "req", + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "description": "partial sync audit plan SQLs request", + "name": "sqls", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CloneRuleTemplateReqV1" + "$ref": "#/definitions/v2.PartialSyncAuditPlanSQLsReqV2" } } ], @@ -7169,276 +6548,355 @@ var doc = `{ } } }, - "/v1/rule_templates/{rule_template_name}/export": { + "/v2/projects/{project_name}/instances/{instance_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export rule template", + "description": "get instance db", "tags": [ - "rule_template" + "instance" ], - "summary": "导出全局规则模板", - "operationId": "exportRuleTemplateV1", + "summary": "获取实例信息", + "operationId": "getInstanceV2", "parameters": [ { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "sqle rule template file", - "schema": { - "type": "file" - } - } - } - } - }, - "/v1/rules": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get all rule template", - "tags": [ - "rule_template" - ], - "summary": "规则列表", - "operationId": "getRuleListV1", - "parameters": [ - { - "type": "string", - "description": "filter db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "filter global rule template name", - "name": "filter_global_rule_template_name", - "in": "query" }, { "type": "string", - "description": "filter rule name list", - "name": "filter_rule_names", - "in": "query" + "description": "instance name", + "name": "instance_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRulesResV1" + "$ref": "#/definitions/v2.GetInstanceResV2" } } } } }, - "/v1/sql_analysis": { + "/v2/projects/{project_name}/sql_manages": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Direct get sql analysis result", + "description": "get sql manage list", "tags": [ - "sql_analysis" + "SqlManage" ], - "summary": "直接获取SQL分析结果", - "operationId": "directGetSQLAnalysisV1", + "summary": "获取管控sql列表", + "operationId": "GetSqlManageListV2", "parameters": [ { "type": "string", "description": "project name", "name": "project_name", - "in": "query", + "in": "path", "required": true }, { "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "query", - "required": true + "description": "fuzzy search sql fingerprint", + "name": "fuzzy_search_sql_fingerprint", + "in": "query" }, { "type": "string", - "description": "schema name", - "name": "schema_name", + "description": "assignee", + "name": "filter_assignee", "in": "query" }, { "type": "string", - "description": "sql", - "name": "sql", + "description": "instance name", + "name": "filter_instance_name", + "in": "query" + }, + { + "enum": [ + "audit_plan", + "sql_audit_record" + ], + "type": "string", + "description": "source", + "name": "filter_source", + "in": "query" + }, + { + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "type": "string", + "description": "audit level", + "name": "filter_audit_level", + "in": "query" + }, + { + "type": "string", + "description": "last audit start time from", + "name": "filter_last_audit_start_time_from", + "in": "query" + }, + { + "type": "string", + "description": "last audit start time to", + "name": "filter_last_audit_start_time_to", + "in": "query" + }, + { + "enum": [ + "unhandled", + "solved", + "ignored", + "manual_audited" + ], + "type": "string", + "description": "status", + "name": "filter_status", + "in": "query" + }, + { + "type": "string", + "description": "rule name", + "name": "filter_rule_name", "in": "query" + }, + { + "type": "string", + "description": "db type", + "name": "filter_db_type", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search endpoint", + "name": "fuzzy_search_endpoint", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search schema name", + "name": "fuzzy_search_schema_name", + "in": "query" + }, + { + "enum": [ + "first_appear_timestamp", + "last_receive_timestamp", + "fp_count" + ], + "type": "string", + "description": "sort field", + "name": "sort_field", + "in": "query" + }, + { + "enum": [ + "asc", + "desc" + ], + "type": "string", + "description": "sort order", + "name": "sort_order", + "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.DirectGetSQLAnalysisResV1" + "$ref": "#/definitions/v2.GetSqlManageListResp" } } } } }, - "/v1/sql_audit": { + "/v2/projects/{project_name}/workflows": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Direct audit sql", + "description": "create workflow", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], "tags": [ - "sql_audit" + "workflow" ], - "summary": "直接审核SQL", - "operationId": "directAuditV1", - "deprecated": true, + "summary": "创建工单", + "operationId": "createWorkflowV2", "parameters": [ { - "description": "sqls that should be audited", - "name": "req", + "description": "create workflow request", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.DirectAuditReqV1" + "$ref": "#/definitions/v2.CreateWorkflowReqV2" } + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.DirectAuditResV1" + "$ref": "#/definitions/v2.CreateWorkflowResV2" } } } } }, - "/v1/static/instance_logo": { - "get": { + "/v2/projects/{project_name}/workflows/cancel": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance type logo", + "description": "batch cancel workflows", "tags": [ - "instance" + "workflow" ], - "summary": "获取实例类型logo", - "operationId": "getInstanceTypeLogo", + "summary": "批量取消工单", + "operationId": "batchCancelWorkflowsV2", "parameters": [ { "type": "string", - "description": "instance type", - "name": "instance_type", - "in": "query", + "description": "project name", + "name": "project_name", + "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "get instance type logo", + }, + { + "description": "batch cancel workflows request", + "name": "BatchCancelWorkflowsReqV2", + "in": "body", + "required": true, "schema": { - "type": "file" + "$ref": "#/definitions/v2.BatchCancelWorkflowsReqV2" } } - } - } - }, - "/v1/static/logo": { - "get": { - "description": "get logo", - "tags": [ - "configuration" - ], - "summary": "获取logo", - "operationId": "getLogo", - "parameters": [ - { - "type": "string", - "description": "timestamp", - "name": "timestamp", - "in": "query" - } ], "responses": { "200": { - "description": "get logo", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/instances/sql_average_execution_time": { - "get": { + "/v2/projects/{project_name}/workflows/complete": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get average execution time of sql", + "description": "this api will directly change the work order status to finished without real online operation", "tags": [ - "statistic" + "workflow" ], - "summary": "获取sql上线平均耗时,按平均耗时降序排列", - "operationId": "getSqlAverageExecutionTimeV1", + "summary": "批量完成工单", + "operationId": "batchCompleteWorkflowsV2", "parameters": [ { - "type": "integer", - "description": "the limit of result item number", - "name": "limit", - "in": "query", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", "required": true + }, + { + "description": "batch complete workflows request", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v2.BatchCompleteWorkflowsReqV2" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlAverageExecutionTimeResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/instances/sql_execution_fail_percent": { + "/v2/projects/{project_name}/workflows/{workflow_id}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql execution fail percent", + "description": "get workflow detail", "tags": [ - "statistic" + "workflow" ], - "summary": "获取SQL上线失败率,按失败率降序排列", - "operationId": "getSqlExecutionFailPercentV1", + "summary": "获取工单详情", + "operationId": "getWorkflowV2", "parameters": [ { - "type": "integer", - "description": "the limit of result item number", - "name": "limit", - "in": "query", + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", "required": true } ], @@ -7446,177 +6904,315 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlExecutionFailPercentResV1" + "$ref": "#/definitions/v2.GetWorkflowResV2" } } } - } - }, - "/v1/statistic/instances/type_percent": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get database instances' types percent", - "tags": [ - "statistic" + "description": "update workflow when it is rejected to creator.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "workflow" + ], + "summary": "更新工单(驳回后才可更新)", + "operationId": "updateWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "description": "update workflow request", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v2.UpdateWorkflowReqV2" + } + } ], - "summary": "获取数据源类型百分比", - "operationId": "getInstancesTypePercentV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstancesTypePercentResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/license/usage": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/cancel": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get usage of license", + "description": "cancel workflow", "tags": [ - "statistic" + "workflow" + ], + "summary": "审批关闭(中止)", + "operationId": "cancelWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + } ], - "summary": "获取License使用情况", - "operationId": "getLicenseUsageV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetLicenseUsageResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/audit_pass_percent": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/approve": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow audit pass percent", + "description": "approve workflow", "tags": [ - "statistic" + "workflow" + ], + "summary": "审批通过", + "operationId": "approveWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "workflow step id", + "name": "workflow_step_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + } ], - "summary": "获取工单审核通过率", - "operationId": "getWorkflowAuditPassPercentV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowAuditPassPercentResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/counts": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/reject": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow counts", + "description": "reject workflow", "tags": [ - "statistic" + "workflow" + ], + "summary": "审批驳回", + "operationId": "rejectWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "workflow step id", + "name": "workflow_step_id", + "in": "path", + "required": true + }, + { + "description": "workflow approve request", + "name": "workflow_approve", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v2.RejectWorkflowReqV2" + } + } ], - "summary": "获取工单数量统计数据", - "operationId": "getWorkflowCountV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowCountsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/duration_of_waiting_for_audit": { + "/v2/projects/{project_name}/workflows/{workflow_id}/tasks": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get duration from workflow being created to audited", + "description": "get summary of workflow instance tasks", "tags": [ - "statistic" + "workflow" + ], + "summary": "获取工单数据源任务概览", + "operationId": "getSummaryOfInstanceTasksV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + } ], - "summary": "获取工单从创建到审核结束的平均时长", - "operationId": "getWorkflowDurationOfWaitingForAuditV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowDurationOfWaitingForAuditResV1" + "$ref": "#/definitions/v2.GetWorkflowTasksResV2" } } } } }, - "/v1/statistic/workflows/duration_of_waiting_for_execution": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/execute": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get duration from workflow being created to executed", + "description": "execute tasks on workflow", "tags": [ - "statistic" + "workflow" + ], + "summary": "多数据源批量上线", + "operationId": "executeTasksOnWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + } ], - "summary": "获取工单各从审核完毕到执行上线的平均时长", - "operationId": "getWorkflowDurationOfWaitingForExecutionV1", - "deprecated": true, "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowDurationOfWaitingForExecutionResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/each_day_counts": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/execute": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get counts of created workflow each day", + "description": "execute one task on workflow", "tags": [ - "statistic" + "workflow" ], - "summary": "获取每天工单创建数量", - "operationId": "getWorkflowCreatedCountEachDayV1", + "summary": "工单提交单个数据源上线", + "operationId": "executeOneTaskOnWorkflowV2", "parameters": [ { "type": "string", - "description": "filter date from.(format:yyyy-mm-dd)", - "name": "filter_date_from", - "in": "query", + "description": "workflow id", + "name": "workflow_id", + "in": "path", "required": true }, { "type": "string", - "description": "filter date to.(format:yyyy-mm-dd)", - "name": "filter_date_to", - "in": "query", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "task id", + "name": "task_id", + "in": "path", "required": true } ], @@ -7624,192 +7220,95 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowCreatedCountsEachDayResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/instance_type_percent": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/schedule": { + "put": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflows percent counted by instance type", - "tags": [ - "statistic" + "description": "update workflow schedule.", + "consumes": [ + "application/json" ], - "summary": "获取按数据源类型统计的工单百分比", - "operationId": "getWorkflowPercentCountedByInstanceTypeV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetWorkflowPercentCountedByInstanceTypeResV1" - } - } - } - } - }, - "/v1/statistic/workflows/pass_percent": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get workflow pass percent", - "tags": [ - "statistic" - ], - "summary": "获取工单通过率", - "operationId": "getWorkflowPassPercentV1", - "deprecated": true, - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetWorkflowPassPercentResV1" - } - } - } - } - }, - "/v1/statistic/workflows/rejected_percent_group_by_creator": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } + "produces": [ + "application/json" ], - "description": "get workflows rejected percent group by creator. The result will be sorted by rejected percent in descending order", "tags": [ - "statistic" + "workflow" ], - "summary": "获取各个用户提交的工单驳回率,按驳回率降序排列", - "operationId": "getWorkflowRejectedPercentGroupByCreatorV1", + "summary": "设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置)", + "operationId": "updateWorkflowScheduleV2", "parameters": [ { - "type": "integer", - "description": "the limit of result item number", - "name": "limit", - "in": "query", + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetWorkflowRejectedPercentGroupByCreatorResV1" - } - } - } - } - }, - "/v1/statistic/workflows/rejected_percent_group_by_instance": { - "get": { - "security": [ + }, { - "ApiKeyAuth": [] - } - ], - "description": "get workflow rejected percent group by instance. The result will be sorted by rejected percent in descending order", - "tags": [ - "statistic" - ], - "summary": "获取各个数据源相关的工单驳回率,按驳回率降序排列", - "operationId": "getWorkflowRejectedPercentGroupByInstanceV1", - "deprecated": true, - "parameters": [ + "type": "string", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, { - "type": "integer", - "description": "the limit of result item number", - "name": "limit", - "in": "query", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "OK", + }, + { + "description": "update workflow schedule request", + "name": "instance", + "in": "body", + "required": true, "schema": { - "$ref": "#/definitions/v1.GetWorkflowRejectedPercentGroupByInstanceResV1" + "$ref": "#/definitions/v2.UpdateWorkflowScheduleReqV2" } } - } - } - }, - "/v1/statistic/workflows/status_count": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get count of workflow status", - "tags": [ - "statistic" ], - "summary": "获取各种状态工单的数量", - "operationId": "getWorkflowStatusCountV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowStatusCountResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/sync_instances": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get sync instance task list", - "tags": [ - "sync_instance" - ], - "summary": "获取同步实例任务列表", - "operationId": "GetSyncInstanceTaskList", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetSyncInstanceTaskListResV1" - } - } - } - }, + "/v2/sql_audit": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create sync instance task", - "consumes": [ - "application/json" - ], + "description": "Direct audit sql", "tags": [ - "sync_instance" + "sql_audit" ], - "summary": "创建同步实例任务", - "operationId": "createSyncInstanceTaskV1", + "summary": "直接审核SQL", + "operationId": "directAuditV2", + "deprecated": true, "parameters": [ { - "description": "create sync instance task request", - "name": "sync_task", + "description": "sqls that should be audited", + "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateSyncInstanceTaskReqV1" + "$ref": "#/definitions/v2.DirectAuditReqV2" } } ], @@ -7817,4745 +7316,496 @@ var doc = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v2.DirectAuditResV2" } } } } }, - "/v1/sync_instances/source_tips": { + "/v2/tasks/audits/{task_id}/sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sync task tips", + "description": "get information of all SQLs belong to the specified audit task", "tags": [ - "sync_instance" + "task" + ], + "summary": "获取指定扫描任务的SQLs信息", + "operationId": "getAuditTaskSQLsV2", + "parameters": [ + { + "type": "string", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "enum": [ + "initialized", + "doing", + "succeeded", + "failed", + "manually_executed", + "terminating", + "terminate_succeeded", + "terminate_failed" + ], + "type": "string", + "description": "filter: exec status of task sql", + "name": "filter_exec_status", + "in": "query" + }, + { + "enum": [ + "initialized", + "doing", + "finished" + ], + "type": "string", + "description": "filter: audit status of task sql", + "name": "filter_audit_status", + "in": "query" + }, + { + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "type": "string", + "description": "filter: audit level of task sql", + "name": "filter_audit_level", + "in": "query" + }, + { + "type": "boolean", + "description": "select unique (fingerprint and audit result) for task sql", + "name": "no_duplicate", + "in": "query" + }, + { + "type": "string", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "page size", + "name": "page_size", + "in": "query", + "required": true + } ], - "summary": "获取同步任务提示", - "operationId": "GetSyncTaskSourceTips", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSyncTaskSourceTipsResV1" + "$ref": "#/definitions/v2.GetAuditTaskSQLsResV2" } } } } }, - "/v1/sync_instances/{task_id}/": { + "/v2/tasks/audits/{task_id}/sqls/{number}/analysis": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sync task detail", + "description": "get SQL explain and related table metadata for analysis", "tags": [ - "sync_instance" + "task" ], - "summary": "获取同步任务详情", - "operationId": "GetSyncInstanceTask", + "summary": "获取task相关的SQL执行计划和表元数据", + "operationId": "getTaskAnalysisDataV2", "parameters": [ { "type": "string", - "description": "sync task id", + "description": "task id", "name": "task_id", "in": "path", "required": true + }, + { + "type": "integer", + "description": "sql number", + "name": "number", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSyncInstanceTaskResV1" + "$ref": "#/definitions/v2.GetTaskAnalysisDataResV2" } } } - }, - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete sync instance task", - "tags": [ - "sync_instance" - ], - "summary": "删除同步实例任务", - "operationId": "deleteSyncInstanceTaskV1", - "parameters": [ - { - "type": "string", - "description": "sync task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update sync instance task", - "tags": [ - "sync_instance" - ], - "summary": "更新同步实例任务", - "operationId": "updateSyncInstanceTaskV1", - "parameters": [ - { - "type": "string", - "description": "sync task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "description": "update sync instance request", - "name": "sync_task", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateSyncInstanceTaskReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/sync_instances/{task_id}/trigger": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "trigger sync instance", - "tags": [ - "sync_instance" - ], - "summary": "触发同步实例", - "operationId": "triggerSyncInstanceV1", - "parameters": [ - { - "type": "string", - "description": "sync task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.TriggerSyncInstanceResV1" - } - } - } - } - }, - "/v1/task_groups/audit": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "audit task group.\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.\n4. file[input_zip_file]: it is zip file, sql will be parsed from it.", - "consumes": [ - "multipart/form-data" - ], - "produces": [ - "application/json" - ], - "tags": [ - "task" - ], - "summary": "审核任务组", - "operationId": "auditTaskGroupIdV1", - "parameters": [ - { - "type": "integer", - "description": "group id of tasks", - "name": "task_group_id", - "in": "formData", - "required": true - }, - { - "type": "string", - "description": "sqls for audit", - "name": "sql", - "in": "formData" - }, - { - "type": "file", - "description": "input SQL file", - "name": "input_sql_file", - "in": "formData" - }, - { - "type": "file", - "description": "input mybatis XML file", - "name": "input_mybatis_xml_file", - "in": "formData" - }, - { - "type": "file", - "description": "input ZIP file", - "name": "input_zip_file", - "in": "formData" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.AuditTaskGroupResV1" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get task", - "tags": [ - "task" - ], - "summary": "获取Sql扫描任务信息", - "operationId": "getAuditTaskV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetAuditTaskResV1" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sql_content": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get SQL content for the audit task", - "tags": [ - "task" - ], - "summary": "获取指定扫描任务的SQL内容", - "operationId": "getAuditTaskSQLContentV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetAuditTaskSQLContentResV1" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sql_file": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "download SQL file for the audit task", - "tags": [ - "task" - ], - "summary": "下载指定扫描任务的SQL文件", - "operationId": "downloadAuditTaskSQLFileV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "sql file", - "schema": { - "type": "file" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sql_report": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "download report file of all SQLs information belong to the specified audit task", - "tags": [ - "task" - ], - "summary": "下载指定扫描任务的SQLs信息报告", - "operationId": "downloadAuditTaskSQLReportV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "boolean", - "description": "select unique (fingerprint and audit result) for task sql", - "name": "no_duplicate", - "in": "query" - } - ], - "responses": { - "200": { - "description": "sql report csv file", - "schema": { - "type": "file" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sqls": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get information of all SQLs belong to the specified audit task", - "tags": [ - "task" - ], - "summary": "获取指定扫描任务的SQLs信息", - "operationId": "getAuditTaskSQLsV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "enum": [ - "initialized", - "doing", - "succeeded", - "failed", - "manually_executed" - ], - "type": "string", - "description": "filter: exec status of task sql", - "name": "filter_exec_status", - "in": "query" - }, - { - "enum": [ - "initialized", - "doing", - "finished" - ], - "type": "string", - "description": "filter: audit status of task sql", - "name": "filter_audit_status", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "filter: audit level of task sql", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "boolean", - "description": "select unique (fingerprint and audit result) for task sql", - "name": "no_duplicate", - "in": "query" - }, - { - "type": "string", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "page size", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetAuditTaskSQLsResV1" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sqls/{number}": { - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "modify the relevant information of a certain SQL in the audit task", - "consumes": [ - "application/json" - ], - "tags": [ - "task" - ], - "summary": "修改扫描任务中某条SQL的相关信息", - "operationId": "updateAuditTaskSQLsV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "sql number", - "name": "number", - "in": "path", - "required": true - }, - { - "description": "modify the relevant information of a certain SQL in the audit task", - "name": "audit_plan", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateAuditTaskSQLsReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sqls/{number}/analysis": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get SQL explain and related table metadata for analysis", - "tags": [ - "task" - ], - "summary": "获取task相关的SQL执行计划和表元数据", - "operationId": "getTaskAnalysisData", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "integer", - "description": "sql number", - "name": "number", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetTaskAnalysisDataResV1" - } - } - } - } - }, - "/v1/user": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get current user info", - "tags": [ - "user" - ], - "summary": "获取当前用户信息", - "operationId": "getCurrentUserV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserDetailResV1" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update current user", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "更新个人信息", - "operationId": "updateCurrentUserV1", - "parameters": [ - { - "description": "update user", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateCurrentUserReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/user/password": { - "put": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update current user's password", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "用户修改密码", - "operationId": "UpdateCurrentUserPasswordV1", - "parameters": [ - { - "description": "update user's password", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateCurrentUserPasswordReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/user_group_tips": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user group tip list", - "tags": [ - "user_group" - ], - "summary": "获取用户组提示列表", - "operationId": "getUserGroupTipListV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "filter_project", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserGroupTipsResV1" - } - } - } - } - }, - "/v1/user_groups": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user group info list", - "produces": [ - "application/json" - ], - "tags": [ - "user_group" - ], - "summary": "获取用户组列表", - "operationId": "getUserGroupListV1", - "parameters": [ - { - "type": "string", - "description": "filter user group name", - "name": "filter_user_group_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserGroupsResV1" - } - } - } - }, - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "create user group", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user_group" - ], - "summary": "创建用户组", - "operationId": "CreateUserGroupV1", - "parameters": [ - { - "description": "create user group", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateUserGroupReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/user_groups/{user_group_name}/": { - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete user group", - "tags": [ - "user_group" - ], - "summary": "删除用户组", - "operationId": "deleteUserGroupV1", - "parameters": [ - { - "type": "string", - "description": "user_group_name", - "name": "user_group_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update user group", - "tags": [ - "user_group" - ], - "summary": "更新用户组", - "operationId": "updateUserGroupV1", - "parameters": [ - { - "type": "string", - "description": "user_group_name", - "name": "user_group_name", - "in": "path", - "required": true - }, - { - "description": "update user group", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.PatchUserGroupReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/user_tips": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user tip list", - "tags": [ - "user" - ], - "summary": "获取用户提示列表", - "operationId": "getUserTipListV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "filter_project", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserTipsResV1" - } - } - } - } - }, - "/v1/users": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user info list", - "tags": [ - "user" - ], - "summary": "获取用户信息列表", - "operationId": "getUserListV1", - "parameters": [ - { - "type": "string", - "description": "filter user name", - "name": "filter_user_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUsersResV1" - } - } - } - }, - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "create user", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "创建用户", - "operationId": "createUserV1", - "parameters": [ - { - "description": "create user", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateUserReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/users/{user_name}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user info", - "tags": [ - "user" - ], - "summary": "获取用户信息", - "operationId": "getUserV1", - "parameters": [ - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserDetailResV1" - } - } - } - }, - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete user", - "tags": [ - "user" - ], - "summary": "删除用户", - "operationId": "deleteUserV1", - "parameters": [ - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update user", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "更新用户信息", - "operationId": "updateUserV1", - "parameters": [ - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - }, - { - "description": "update user", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateUserReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/users/{user_name}/password": { - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "admin modifies the passwords of other users", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "admin修改其他用户密码", - "operationId": "UpdateOtherUserPasswordV1", - "parameters": [ - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - }, - { - "description": "change user's password", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateOtherUserPasswordReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/workflows": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get global workflow list", - "tags": [ - "workflow" - ], - "summary": "获取全局工单列表", - "operationId": "getGlobalWorkflowsV1", - "parameters": [ - { - "type": "string", - "description": "filter subject", - "name": "filter_subject", - "in": "query" - }, - { - "type": "string", - "description": "filter create time from", - "name": "filter_create_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter create time to", - "name": "filter_create_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_from", - "name": "filter_task_execute_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_to", - "name": "filter_task_execute_start_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter create user name", - "name": "filter_create_user_name", - "in": "query" - }, - { - "enum": [ - "wait_for_audit", - "wait_for_execution", - "rejected", - "executing", - "canceled", - "exec_failed", - "finished" - ], - "type": "string", - "description": "filter workflow status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "filter current step assignee user name", - "name": "filter_current_step_assignee_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_task_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetWorkflowsResV1" - } - } - } - } - }, - "/v2/audit_files": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "Direct audit sql from SQL files and MyBatis files", - "tags": [ - "sql_audit" - ], - "summary": "直接从文件内容提取SQL并审核,SQL文件暂时只支持一次解析一个文件", - "operationId": "directAuditFilesV2", - "parameters": [ - { - "description": "files that should be audited", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.DirectAuditFileReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.DirectAuditResV2" - } - } - } - } - }, - "/v2/configurations/drivers": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get drivers", - "tags": [ - "configuration" - ], - "summary": "获取当前 server 支持的审核类型", - "operationId": "getDriversV2", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetDriversRes" - } - } - } - } - }, - "/v2/login": { - "post": { - "description": "user login", - "tags": [ - "user" - ], - "summary": "用户登录", - "operationId": "loginV2", - "parameters": [ - { - "description": "user login request", - "name": "user", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UserLoginReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get audit plan info list", - "tags": [ - "audit_plan" - ], - "summary": "获取扫描任务信息列表", - "operationId": "getAuditPlansV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "filter audit plan db type", - "name": "filter_audit_plan_db_type", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search audit plan name", - "name": "fuzzy_search_audit_plan_name", - "in": "query" - }, - { - "type": "string", - "description": "filter audit plan type", - "name": "filter_audit_plan_type", - "in": "query" - }, - { - "type": "string", - "description": "filter audit plan instance name", - "name": "filter_audit_plan_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetAuditPlansResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get audit plan report SQLs", - "tags": [ - "audit_plan" - ], - "summary": "获取指定扫描任务的SQL扫描详情", - "operationId": "getAuditPlanReportsSQLs", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", - "in": "path", - "required": true - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetAuditPlanReportSQLsResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get SQL explain and related table metadata for analysis", - "tags": [ - "audit_plan" - ], - "summary": "获取task相关的SQL执行计划和表元数据", - "operationId": "getAuditPlantAnalysisDataV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "sql number", - "name": "number", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetAuditPlanAnalysisDataResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "full sync audit plan SQLs", - "tags": [ - "audit_plan" - ], - "summary": "全量同步SQL到扫描任务", - "operationId": "fullSyncAuditPlanSQLsV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "description": "full sync audit plan SQLs request", - "name": "sqls", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.FullSyncAuditPlanSQLsReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "partial sync audit plan SQLs", - "tags": [ - "audit_plan" - ], - "summary": "增量同步SQL到扫描任务", - "operationId": "partialSyncAuditPlanSQLsV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "description": "partial sync audit plan SQLs request", - "name": "sqls", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.PartialSyncAuditPlanSQLsReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/instances": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get instance info list", - "tags": [ - "instance" - ], - "summary": "获取实例信息列表", - "operationId": "getInstanceListV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "type": "string", - "description": "filter db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "filter db host", - "name": "filter_db_host", - "in": "query" - }, - { - "type": "string", - "description": "filter db port", - "name": "filter_db_port", - "in": "query" - }, - { - "type": "string", - "description": "filter db user", - "name": "filter_db_user", - "in": "query" - }, - { - "type": "string", - "description": "filter rule template name", - "name": "filter_rule_template_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetInstancesResV2" - } - } - } - }, - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "create a instance", - "consumes": [ - "application/json" - ], - "tags": [ - "instance" - ], - "summary": "添加实例", - "operationId": "createInstanceV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "add instance", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.CreateInstanceReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/instances/{instance_name}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get instance db", - "tags": [ - "instance" - ], - "summary": "获取实例信息", - "operationId": "getInstanceV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetInstanceResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/sql_manages": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get sql manage list", - "tags": [ - "SqlManage" - ], - "summary": "获取管控sql列表", - "operationId": "GetSqlManageListV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "fuzzy search sql fingerprint", - "name": "fuzzy_search_sql_fingerprint", - "in": "query" - }, - { - "type": "string", - "description": "assignee", - "name": "filter_assignee", - "in": "query" - }, - { - "type": "string", - "description": "instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "enum": [ - "audit_plan", - "sql_audit_record" - ], - "type": "string", - "description": "source", - "name": "filter_source", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "audit level", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time from", - "name": "filter_last_audit_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time to", - "name": "filter_last_audit_start_time_to", - "in": "query" - }, - { - "enum": [ - "unhandled", - "solved", - "ignored", - "manual_audited" - ], - "type": "string", - "description": "status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "rule name", - "name": "filter_rule_name", - "in": "query" - }, - { - "type": "string", - "description": "db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search endpoint", - "name": "fuzzy_search_endpoint", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search schema name", - "name": "fuzzy_search_schema_name", - "in": "query" - }, - { - "enum": [ - "first_appear_timestamp", - "last_receive_timestamp", - "fp_count" - ], - "type": "string", - "description": "sort field", - "name": "sort_field", - "in": "query" - }, - { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "description": "sort order", - "name": "sort_order", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetSqlManageListResp" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "create workflow", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflow" - ], - "summary": "创建工单", - "operationId": "createWorkflowV2", - "parameters": [ - { - "description": "create workflow request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.CreateWorkflowReqV2" - } - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.CreateWorkflowResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/cancel": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "batch cancel workflows", - "tags": [ - "workflow" - ], - "summary": "批量取消工单", - "operationId": "batchCancelWorkflowsV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "batch cancel workflows request", - "name": "BatchCancelWorkflowsReqV2", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.BatchCancelWorkflowsReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/complete": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "this api will directly change the work order status to finished without real online operation", - "tags": [ - "workflow" - ], - "summary": "批量完成工单", - "operationId": "batchCompleteWorkflowsV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "batch complete workflows request", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.BatchCompleteWorkflowsReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get workflow detail", - "tags": [ - "workflow" - ], - "summary": "获取工单详情", - "operationId": "getWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetWorkflowResV2" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update workflow when it is rejected to creator.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflow" - ], - "summary": "更新工单(驳回后才可更新)", - "operationId": "updateWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "update workflow request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.UpdateWorkflowReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/cancel": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "cancel workflow", - "tags": [ - "workflow" - ], - "summary": "审批关闭(中止)", - "operationId": "cancelWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/approve": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "approve workflow", - "tags": [ - "workflow" - ], - "summary": "审批通过", - "operationId": "approveWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow step id", - "name": "workflow_step_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/reject": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "reject workflow", - "tags": [ - "workflow" - ], - "summary": "审批驳回", - "operationId": "rejectWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow step id", - "name": "workflow_step_id", - "in": "path", - "required": true - }, - { - "description": "workflow approve request", - "name": "workflow_approve", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.RejectWorkflowReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/tasks": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get summary of workflow instance tasks", - "tags": [ - "workflow" - ], - "summary": "获取工单数据源任务概览", - "operationId": "getSummaryOfInstanceTasksV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetWorkflowTasksResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/execute": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "execute tasks on workflow", - "tags": [ - "workflow" - ], - "summary": "多数据源批量上线", - "operationId": "executeTasksOnWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/execute": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "execute one task on workflow", - "tags": [ - "workflow" - ], - "summary": "工单提交单个数据源上线", - "operationId": "executeOneTaskOnWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/schedule": { - "put": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update workflow schedule.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflow" - ], - "summary": "设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置)", - "operationId": "updateWorkflowScheduleV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "update workflow schedule request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.UpdateWorkflowScheduleReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/sql_audit": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "Direct audit sql", - "tags": [ - "sql_audit" - ], - "summary": "直接审核SQL", - "operationId": "directAuditV2", - "deprecated": true, - "parameters": [ - { - "description": "sqls that should be audited", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.DirectAuditReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.DirectAuditResV2" - } - } - } - } - }, - "/v2/tasks/audits/{task_id}/sqls": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get information of all SQLs belong to the specified audit task", - "tags": [ - "task" - ], - "summary": "获取指定扫描任务的SQLs信息", - "operationId": "getAuditTaskSQLsV2", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "enum": [ - "initialized", - "doing", - "succeeded", - "failed", - "manually_executed", - "terminating", - "terminate_succeeded", - "terminate_failed" - ], - "type": "string", - "description": "filter: exec status of task sql", - "name": "filter_exec_status", - "in": "query" - }, - { - "enum": [ - "initialized", - "doing", - "finished" - ], - "type": "string", - "description": "filter: audit status of task sql", - "name": "filter_audit_status", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "filter: audit level of task sql", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "boolean", - "description": "select unique (fingerprint and audit result) for task sql", - "name": "no_duplicate", - "in": "query" - }, - { - "type": "string", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "page size", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetAuditTaskSQLsResV2" - } - } - } - } - }, - "/v2/tasks/audits/{task_id}/sqls/{number}/analysis": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get SQL explain and related table metadata for analysis", - "tags": [ - "task" - ], - "summary": "获取task相关的SQL执行计划和表元数据", - "operationId": "getTaskAnalysisDataV2", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "integer", - "description": "sql number", - "name": "number", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetTaskAnalysisDataResV2" - } - } - } - } - } - }, - "definitions": { - "controller.BaseRes": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.AffectRows": { - "type": "object", - "properties": { - "count": { - "type": "integer" - }, - "err_message": { - "type": "string" - } - } - }, - "v1.AuditPlanCount": { - "type": "object", - "properties": { - "audit_plan_count": { - "type": "integer" - }, - "audit_plan_desc": { - "type": "string" - }, - "audit_plan_type": { - "type": "string" - } - } - }, - "v1.AuditPlanMetaV1": { - "type": "object", - "properties": { - "audit_plan_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanParamResV1" - } - }, - "audit_plan_type": { - "type": "string" - }, - "audit_plan_type_desc": { - "type": "string" - }, - "instance_type": { - "type": "string" - } - } - }, - "v1.AuditPlanParamReqV1": { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "v1.AuditPlanParamResV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "key": { - "type": "string" - }, - "type": { - "type": "string", - "enum": [ - "string", - "int", - "bool" - ] - }, - "value": { - "type": "string" - } - } - }, - "v1.AuditPlanReportResV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error", - "" - ] - }, - "audit_plan_report_id": { - "type": "string", - "example": "1" - }, - "audit_plan_report_timestamp": { - "type": "string", - "example": "RFC3339" - }, - "pass_rate": { - "type": "number" - }, - "score": { - "type": "integer" - } - } - }, - "v1.AuditPlanReportSQLResV1": { - "type": "object", - "properties": { - "audit_plan_report_sql": { - "type": "string", - "example": "select * from t1 where id = 1" - }, - "audit_plan_report_sql_audit_result": { - "type": "string", - "example": "same format as task audit result" - }, - "number": { - "type": "integer", - "example": 1 - } - } - }, - "v1.AuditPlanResV1": { - "type": "object", - "properties": { - "audit_plan_cron": { - "type": "string", - "example": "0 */2 * * *" - }, - "audit_plan_db_type": { - "type": "string", - "example": "mysql" - }, - "audit_plan_instance_database": { - "type": "string", - "example": "app1" - }, - "audit_plan_instance_name": { - "type": "string", - "example": "test_mysql" - }, - "audit_plan_meta": { - "type": "object", - "$ref": "#/definitions/v1.AuditPlanMetaV1" - }, - "audit_plan_name": { - "type": "string", - "example": "audit_for_java_app1" - }, - "audit_plan_token": { - "type": "string", - "example": "it's a JWT Token for scanner" - }, - "rule_template_name": { - "type": "string", - "example": "default_MySQL" - } - } - }, - "v1.AuditPlanSQLHeadV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "name": { - "type": "string" - }, - "type": { - "type": "string", - "enum": [ - "sql" - ] - } - } - }, - "v1.AuditPlanSQLReqV1": { - "type": "object", - "properties": { - "audit_plan_sql_counter": { - "type": "string", - "example": "6" - }, - "audit_plan_sql_fingerprint": { - "type": "string", - "example": "select * from t1 where id = ?" - }, - "audit_plan_sql_last_receive_text": { - "type": "string", - "example": "select * from t1 where id = 1" - }, - "audit_plan_sql_last_receive_timestamp": { - "type": "string", - "example": "RFC3339" - }, - "audit_plan_sql_schema": { - "type": "string", - "example": "db1" - }, - "db_user": { - "type": "string", - "example": "database_user001" - }, - "endpoint": { - "type": "string", - "example": "10.186.1.2" - }, - "first_query_at": { - "type": "string", - "example": "2023-09-12T02:48:01.317880Z" - }, - "query_time_avg": { - "type": "number", - "example": 3.22 - }, - "query_time_max": { - "type": "number", - "example": 5.22 - } - } - }, - "v1.AuditPlanSQLResV1": { - "type": "object", - "properties": { - "head": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanSQLHeadV1" - } - }, - "rows": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - }, - "v1.AuditPlanTypesV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "instance_type": { - "type": "string", - "enum": [ - "MySQL", - "Oracle", - "TiDB", - "OceanBase For MySQL", - "" - ] - }, - "type": { - "type": "string" - } - } - }, - "v1.AuditResDataV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error", - "" - ] - }, - "pass_rate": { - "type": "number" - }, - "score": { - "type": "integer" - }, - "sql_results": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditSQLResV1" - } - } - } - }, - "v1.AuditResult": { - "type": "object", - "properties": { - "level": { - "type": "string", - "example": "warn" - }, - "message": { - "type": "string", - "example": "避免使用不必要的内置函数md5()" - }, - "rule_name": { - "type": "string" - } - } - }, - "v1.AuditSQLResV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string" - }, - "audit_result": { - "type": "string" - }, - "exec_sql": { - "type": "string" - }, - "number": { - "type": "integer" - } - } - }, - "v1.AuditTaskGroupRes": { - "type": "object", - "properties": { - "task_group_id": { - "type": "integer" - }, - "tasks": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditTaskResV1" - } - } - } - }, - "v1.AuditTaskGroupResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskGroupRes" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.AuditTaskResV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error", - "" - ] - }, - "exec_end_time": { - "type": "string" - }, - "exec_start_time": { - "type": "string" - }, - "instance_db_type": { - "type": "string" - }, - "instance_name": { - "type": "string" - }, - "instance_schema": { - "type": "string", - "example": "db1" - }, - "pass_rate": { - "type": "number" - }, - "score": { - "type": "integer" - }, - "sql_source": { - "type": "string", - "enum": [ - "form_data", - "sql_file", - "mybatis_xml_file", - "audit_plan" - ] - }, - "status": { - "type": "string", - "enum": [ - "initialized", - "audited", - "executing", - "exec_success", - "exec_failed", - "manually_executed" - ] - }, - "task_id": { - "type": "integer" - } - } - }, - "v1.AuditTaskSQLContentResV1": { - "type": "object", - "properties": { - "sql": { - "type": "string", - "example": "alter table tb1 drop columns c1" - } - } - }, - "v1.AuditTaskSQLResV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string" - }, - "audit_result": { - "type": "string" - }, - "audit_status": { - "type": "string" - }, - "description": { - "type": "string" - }, - "exec_result": { - "type": "string" - }, - "exec_sql": { - "type": "string" - }, - "exec_status": { - "type": "string" - }, - "number": { - "type": "integer" - }, - "rollback_sql": { - "type": "string" - } - } - }, - "v1.AuditTasksGroupResV1": { - "type": "object", - "properties": { - "task_group_id": { - "type": "integer" - } - } - }, - "v1.AuditWhitelistResV1": { - "type": "object", - "properties": { - "audit_whitelist_id": { - "type": "integer" - }, - "desc": { - "type": "string" - }, - "match_type": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "v1.AuditedSQLCount": { - "type": "object", - "properties": { - "risk_sql_count": { - "type": "integer" - }, - "total_sql_count": { - "type": "integer" - } - } - }, - "v1.BatchCancelWorkflowsReqV1": { - "type": "object", - "properties": { - "workflow_names": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.BatchCheckInstanceConnectionsReqV1": { - "type": "object", - "properties": { - "instances": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceForCheckConnection" - } - } - } - }, - "v1.BatchCompleteWorkflowsReqV1": { - "type": "object", - "properties": { - "workflow_names": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.BatchGetInstanceConnectionsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceConnectionResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.BatchUpdateSqlManageReq": { - "type": "object", - "properties": { - "assignees": { - "type": "array", - "items": { - "type": "string" - } - }, - "remark": { - "type": "string" - }, - "sql_manage_id_list": { - "type": "array", - "items": { - "type": "integer" - } - }, - "status": { - "type": "string", - "enum": [ - "solved", - "ignored", - "manual_audited" - ] - } - } - }, - "v1.BindOauth2UserReqV1": { - "type": "object", - "properties": { - "oauth2_token": { - "type": "string" - }, - "pwd": { - "type": "string" - }, - "user_name": { - "type": "string" - } - } - }, - "v1.BindOauth2UserResDataV1": { - "type": "object", - "properties": { - "token": { - "type": "string" - } - } - }, - "v1.BindOauth2UserResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.BindOauth2UserResDataV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.BindRoleReqV1": { - "type": "object", - "properties": { - "instance_name": { - "type": "string" - }, - "role_names": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.CheckLicenseResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "content": { - "type": "string" - }, - "license": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.LicenseItem" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.CloneProjectRuleTemplateReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - } - }, - "new_rule_template_name": { - "type": "string" - } - } - }, - "v1.CloneRuleTemplateReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "new_rule_template_name": { - "type": "string" - } - } - }, - "v1.CompanyNotice": { - "type": "object", - "properties": { - "notice_str": { - "type": "string" - } - } - }, - "v1.CreateAuditPlanReqV1": { - "type": "object", - "properties": { - "audit_plan_cron": { - "type": "string", - "example": "0 */2 * * *" - }, - "audit_plan_instance_database": { - "type": "string", - "example": "app1" - }, - "audit_plan_instance_name": { - "type": "string", - "example": "test_mysql" - }, - "audit_plan_instance_type": { - "type": "string", - "example": "mysql" - }, - "audit_plan_name": { - "type": "string", - "example": "audit_plan_for_java_repo_1" - }, - "audit_plan_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanParamReqV1" - } - }, - "audit_plan_type": { - "type": "string", - "example": "slow log" - }, - "rule_template_name": { - "type": "string", - "example": "default_MySQL" - } - } - }, - "v1.CreateAuditTasksGroupReqV1": { - "type": "object", - "properties": { - "instances": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceForCreatingTask" - } - } - } - }, - "v1.CreateAuditTasksGroupResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditTasksGroupResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.CreateAuditWhitelistReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string", - "example": "used for rapid release" - }, - "match_type": { - "type": "string", - "enum": [ - "exact_match", - "fp_match" - ], - "example": "exact_match" - }, - "value": { - "type": "string", - "example": "create table" - } - } - }, - "v1.CreateCustomRuleReqV1": { - "type": "object", - "properties": { - "annotation": { - "type": "string", - "example": "this is test rule" - }, - "db_type": { - "type": "string", - "example": "MySQL" - }, - "desc": { - "type": "string", - "example": "this is test rule" - }, - "level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "notice" - }, - "rule_script": { - "type": "string" - }, - "type": { - "type": "string", - "example": "DDL规则" - } - } - }, - "v1.CreateInstanceReqV1": { - "type": "object", - "properties": { - "additional_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamReqV1" - } - }, - "db_host": { - "type": "string", - "example": "10.10.10.10" - }, - "db_password": { - "type": "string", - "example": "123456" - }, - "db_port": { - "type": "string", - "example": "3306" - }, - "db_type": { - "type": "string", - "example": "mysql" - }, - "db_user": { - "type": "string", - "example": "root" - }, - "desc": { - "type": "string", - "example": "this is a test instance" - }, - "instance_name": { - "type": "string", - "example": "test" - }, - "maintenance_times": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MaintenanceTimeReqV1" - } - }, - "rule_template_name": { - "type": "string" - }, - "sql_query_config": { - "type": "object", - "$ref": "#/definitions/v1.SQLQueryConfigReqV1" - } - } - }, - "v1.CreateMemberGroupReqV1": { - "type": "object", - "properties": { - "roles": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" - } - }, - "user_group_name": { - "type": "string" - } - } - }, - "v1.CreateMemberReqV1": { - "type": "object", - "properties": { - "is_manager": { - "type": "boolean" - }, - "roles": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" - } - }, - "user_name": { - "type": "string" - } - } - }, - "v1.CreateProjectReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "v1.CreateProjectRuleTemplateReqV1": { - "type": "object", - "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - } - }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleReqV1" - } - }, - "rule_template_name": { - "type": "string" - } - } - }, - "v1.CreateRoleReqV1": { - "type": "object", - "properties": { - "operation_code_list": { - "type": "array", - "items": { - "type": "integer" - } - }, - "role_desc": { - "type": "string" - }, - "role_name": { - "type": "string" - } - } - }, - "v1.CreateRuleTemplateReqV1": { - "type": "object", - "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleReqV1" - } - }, - "rule_template_name": { - "type": "string" - } - } - }, - "v1.CreateSQLAuditRecordResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.SQLAuditRecordResData" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.CreateSyncInstanceTaskReqV1": { - "type": "object", - "required": [ - "db_type", - "global_rule_template", - "source", - "sync_instance_interval", - "url", - "version" - ], - "properties": { - "db_type": { - "type": "string", - "example": "mysql" - }, - "global_rule_template": { - "type": "string", - "example": "default_mysql" - }, - "source": { - "type": "string", - "example": "actiontech-dmp" - }, - "sync_instance_interval": { - "type": "string", - "example": "0 0 * * *" - }, - "url": { - "type": "string", - "example": "http://10.186.62.56:10000" - }, - "version": { - "type": "string", - "example": "5.23.01.0" - } - } - }, - "v1.CreateUserGroupReqV1": { - "type": "object", - "properties": { - "user_group_desc": { - "type": "string", - "example": "this is a group" - }, - "user_group_name": { - "type": "string", - "example": "test" - }, - "user_name_list": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.CreateUserReqV1": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": "test@email.com" - }, - "management_permission_code_list": { - "type": "array", - "items": { - "type": "integer" - } - }, - "phone": { - "type": "string", - "example": "18962136666" - }, - "user_group_name_list": { - "type": "array", - "items": { - "type": "string" - } - }, - "user_name": { - "type": "string", - "example": "test" - }, - "user_password": { - "type": "string", - "example": "123456" - }, - "wechat_id": { - "type": "string", - "example": "UserID" - } - } - }, - "v1.CreateWorkflowReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "task_ids": { - "type": "array", - "items": { - "type": "integer" - } - }, - "workflow_subject": { - "type": "string" - } - } - }, - "v1.CustomRuleResV1": { - "type": "object", - "properties": { - "annotation": { - "type": "string", - "example": "this is test rule" - }, - "db_type": { - "type": "string", - "example": "MySQL" - }, - "desc": { - "type": "string", - "example": "this is test rule" - }, - "level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "notice" - }, - "rule_id": { - "type": "string" - }, - "rule_script": { - "type": "string" - }, - "type": { - "type": "string", - "example": "DDL规则" - } - } - }, - "v1.DBTypeAuditPlan": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanCount" - } - }, - "db_type": { - "type": "string" - } - } - }, - "v1.DBTypeHealth": { - "type": "object", - "properties": { - "db_type": { - "type": "string" - }, - "health_instance_names": { - "type": "array", - "items": { - "type": "string" - } - }, - "unhealth_instance_names": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.DashboardProjectTipV1": { - "type": "object", - "properties": { - "project_name": { - "type": "string" - }, - "unfinished_workflow_count": { - "description": "只统计与当前用户相关的未完成工单", - "type": "integer" - } - } - }, - "v1.DashboardResV1": { - "type": "object", - "properties": { - "workflow_statistics": { - "type": "object", - "$ref": "#/definitions/v1.WorkflowStatisticsResV1" - } - } - }, - "v1.DingTalkConfigurationV1": { - "type": "object", - "properties": { - "app_key": { - "type": "string" - }, - "is_enable_ding_talk_notify": { - "type": "boolean" - } - } - }, - "v1.DirectAuditFileReqV1": { - "type": "object", - "properties": { - "file_contents": { - "description": "调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现\n每个数组元素是一个文件内容", - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "select * from t1; select * from t2;" - ] - }, - "instance_name": { - "type": "string", - "example": "instance1" - }, - "instance_type": { - "type": "string", - "example": "MySQL" - }, - "project_name": { - "type": "string", - "example": "project1" - }, - "schema_name": { - "type": "string", - "example": "schema1" - }, - "sql_type": { - "type": "string", - "enum": [ - "sql", - "mybatis", - "" - ], - "example": "sql" - } - } - }, - "v1.DirectAuditReqV1": { - "type": "object", - "properties": { - "instance_name": { - "type": "string", - "example": "instance1" - }, - "instance_type": { - "type": "string", - "example": "MySQL" - }, - "project_name": { - "type": "string", - "example": "project1" - }, - "schema_name": { - "type": "string", - "example": "schema1" - }, - "sql_content": { - "description": "调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现", - "type": "string", - "example": "select * from t1; select * from t2;" - }, - "sql_type": { - "type": "string", - "enum": [ - "sql", - "mybatis", - "" - ], - "example": "sql" - } - } - }, - "v1.DirectAuditResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditResDataV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.DirectGetSQLAnalysisResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.SqlAnalysisResDataV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.DriversResV1": { - "type": "object", - "properties": { - "driver_name_list": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.ExplainClassicResult": { - "type": "object", - "properties": { - "head": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMetaItemHeadResV1" - } - }, - "rows": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - }, - "v1.FeishuConfigurationV1": { - "type": "object", - "properties": { - "app_id": { - "type": "string" - }, - "is_feishu_notification_enabled": { - "type": "boolean" - } - } - }, - "v1.FullSyncAuditPlanSQLsReqV1": { - "type": "object", - "properties": { - "audit_plan_sql_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanSQLReqV1" - } - } - } - }, - "v1.GetAuditPlanAnalysisDataResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetSQLAnalysisDataResItemV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanMetasResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanMetaV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanNotifyConfigResDataV1": { - "type": "object", - "properties": { - "enable_email_notify": { - "type": "boolean" - }, - "enable_web_hook_notify": { - "type": "boolean" - }, - "notify_interval": { - "type": "integer" - }, - "notify_level": { - "type": "string" - }, - "web_hook_template": { - "type": "string" - }, - "web_hook_url": { - "type": "string" - } - } - }, - "v1.GetAuditPlanNotifyConfigResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetAuditPlanNotifyConfigResDataV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanReportResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditPlanReportResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanReportSQLsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanReportSQLResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditPlanReportsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanReportResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditPlanResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditPlanResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanSQLsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditPlanSQLResV1" - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditPlanTypesResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanTypesV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlansResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditTaskResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditTaskSQLContentResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskSQLContentResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditTaskSQLsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditTaskSQLResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditWhitelistResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditWhitelistResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetCompanyNoticeResp": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.CompanyNotice" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetCustomRuleResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.CustomRuleResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetCustomRulesResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.CustomRuleResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetDashboardProjectTipsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.DashboardProjectTipV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetDashboardResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.DashboardResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetDingTalkConfigurationResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.DingTalkConfigurationV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetDriversResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.DriversResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetFeishuAuditConfigurationResV1": { + } + } + }, + "definitions": { + "controller.BaseRes": { "type": "object", "properties": { "code": { "type": "integer", "example": 0 }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.FeishuConfigurationV1" - }, "message": { "type": "string", "example": "ok" } } }, - "v1.GetFeishuConfigurationResV1": { + "v1.AffectRows": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.FeishuConfigurationV1" + "count": { + "type": "integer" }, - "message": { - "type": "string", - "example": "ok" + "err_message": { + "type": "string" } } }, - "v1.GetInstanceAdditionalMetasResV1": { + "v1.AuditPlanCount": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_plan_count": { + "type": "integer" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalMetaV1" - } + "audit_plan_desc": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "audit_plan_type": { + "type": "string" } } }, - "v1.GetInstanceConnectableReqV1": { + "v1.AuditPlanMetaV1": { "type": "object", "properties": { - "additional_params": { + "audit_plan_params": { "type": "array", "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamReqV1" + "$ref": "#/definitions/v1.AuditPlanParamResV1" } }, - "db_type": { - "type": "string", - "example": "mysql" - }, - "host": { - "type": "string", - "example": "10.10.10.10" - }, - "password": { - "type": "string", - "example": "123456" + "audit_plan_type": { + "type": "string" }, - "port": { - "type": "string", - "example": "3306" + "audit_plan_type_desc": { + "type": "string" }, - "user": { - "type": "string", - "example": "root" + "instance_type": { + "type": "string" } } }, - "v1.GetInstanceConnectableResV1": { + "v1.AuditPlanParamReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstanceConnectableResV1" + "key": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "value": { + "type": "string" } } }, - "v1.GetInstanceHealthResV1": { + "v1.AuditPlanParamResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.DBTypeHealth" - } + "key": { + "type": "string" }, - "message": { + "type": { "type": "string", - "example": "ok" + "enum": [ + "string", + "int", + "bool" + ] + }, + "value": { + "type": "string" } } }, - "v1.GetInstanceResV1": { + "v1.AuditPlanReportResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error", + "" + ] }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstanceResV1" + "audit_plan_report_id": { + "type": "string", + "example": "1" }, - "message": { + "audit_plan_report_timestamp": { "type": "string", - "example": "ok" + "example": "RFC3339" + }, + "pass_rate": { + "type": "number" + }, + "score": { + "type": "integer" } } }, - "v1.GetInstanceSchemaResV1": { + "v1.AuditPlanReportSQLResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstanceSchemaResV1" + "audit_plan_report_sql": { + "type": "string", + "example": "select * from t1 where id = 1" }, - "message": { + "audit_plan_report_sql_audit_result": { "type": "string", - "example": "ok" + "example": "same format as task audit result" + }, + "number": { + "type": "integer", + "example": 1 } } }, - "v1.GetInstanceTipsResV1": { + "v1.AuditPlanResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_plan_cron": { + "type": "string", + "example": "0 */2 * * *" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceTipResV1" - } + "audit_plan_db_type": { + "type": "string", + "example": "mysql" }, - "message": { + "audit_plan_instance_database": { "type": "string", - "example": "ok" - } - } - }, - "v1.GetInstancesResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 + "example": "app1" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceResV1" - } + "audit_plan_instance_name": { + "type": "string", + "example": "test_mysql" }, - "message": { + "audit_plan_meta": { + "type": "object", + "$ref": "#/definitions/v1.AuditPlanMetaV1" + }, + "audit_plan_name": { "type": "string", - "example": "ok" + "example": "audit_for_java_app1" }, - "total_nums": { - "type": "integer" + "audit_plan_token": { + "type": "string", + "example": "it's a JWT Token for scanner" + }, + "rule_template_name": { + "type": "string", + "example": "default_MySQL" } } }, - "v1.GetInstancesTypePercentResV1": { + "v1.AuditPlanSQLHeadV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstancesTypePercentV1" + "name": { + "type": "string" }, - "message": { + "type": { "type": "string", - "example": "ok" + "enum": [ + "sql" + ] } } }, - "v1.GetLDAPConfigurationResV1": { + "v1.AuditPlanSQLReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_plan_sql_counter": { + "type": "string", + "example": "6" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.LDAPConfigurationResV1" + "audit_plan_sql_fingerprint": { + "type": "string", + "example": "select * from t1 where id = ?" + }, + "audit_plan_sql_last_receive_text": { + "type": "string", + "example": "select * from t1 where id = 1" + }, + "audit_plan_sql_last_receive_timestamp": { + "type": "string", + "example": "RFC3339" + }, + "audit_plan_sql_schema": { + "type": "string", + "example": "db1" + }, + "db_user": { + "type": "string", + "example": "database_user001" + }, + "endpoint": { + "type": "string", + "example": "10.186.1.2" }, - "message": { + "first_query_at": { "type": "string", - "example": "ok" + "example": "2023-09-12T02:48:01.317880Z" + }, + "query_time_avg": { + "type": "number", + "example": 3.22 + }, + "query_time_max": { + "type": "number", + "example": 5.22 } } }, - "v1.GetLicenseResV1": { + "v1.AuditPlanSQLResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "content": { - "type": "string" - }, - "license": { + "head": { "type": "array", "items": { - "$ref": "#/definitions/v1.LicenseItem" + "$ref": "#/definitions/v1.AuditPlanSQLHeadV1" } }, - "message": { - "type": "string", - "example": "ok" + "rows": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } } } }, - "v1.GetLicenseUsageResV1": { + "v1.AuditPlanTypesV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.LicenseUsageV1" + "desc": { + "type": "string" }, - "message": { + "instance_type": { "type": "string", - "example": "ok" - } - } - }, - "v1.GetManagementPermissionsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ManagementPermissionResV1" - } + "enum": [ + "MySQL", + "Oracle", + "TiDB", + "OceanBase For MySQL", + "" + ] }, - "message": { - "type": "string", - "example": "ok" + "type": { + "type": "string" } } }, - "v1.GetMemberGroupRespDataV1": { + "v1.AuditResDataV1": { "type": "object", "properties": { - "roles": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" - } + "audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error", + "" + ] }, - "user_group_name": { - "type": "string" + "pass_rate": { + "type": "number" + }, + "score": { + "type": "integer" }, - "users": { + "sql_results": { "type": "array", "items": { - "$ref": "#/definitions/v1.MemberGroupUserItem" + "$ref": "#/definitions/v1.AuditSQLResV1" } } } }, - "v1.GetMemberGroupRespV1": { + "v1.AuditResult": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetMemberGroupRespDataV1" + "level": { + "type": "string", + "example": "warn" }, "message": { "type": "string", - "example": "ok" + "example": "避免使用不必要的内置函数md5()" + }, + "rule_name": { + "type": "string" } } }, - "v1.GetMemberGroupsRespV1": { + "v1.AuditSQLResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_level": { + "type": "string" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.GetMemberGroupRespDataV1" - } + "audit_result": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "exec_sql": { + "type": "string" }, - "total_nums": { + "number": { "type": "integer" } } }, - "v1.GetMemberRespDataV1": { + "v1.AuditTaskGroupRes": { "type": "object", "properties": { - "is_manager": { - "type": "boolean" + "task_group_id": { + "type": "integer" }, - "roles": { + "tasks": { "type": "array", "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" + "$ref": "#/definitions/v1.AuditTaskResV1" } - }, - "user_name": { - "type": "string" } } }, - "v1.GetMemberRespV1": { + "v1.AuditTaskGroupResV1": { "type": "object", "properties": { "code": { @@ -12564,7 +7814,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.GetMemberRespDataV1" + "$ref": "#/definitions/v1.AuditTaskGroupRes" }, "message": { "type": "string", @@ -12572,191 +7822,177 @@ var doc = `{ } } }, - "v1.GetMemberTipsResV1": { + "v1.AuditTaskResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error", + "" + ] }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MemberTipResV1" - } + "exec_end_time": { + "type": "string" }, - "message": { + "exec_start_time": { + "type": "string" + }, + "instance_db_type": { + "type": "string" + }, + "instance_name": { + "type": "string" + }, + "instance_schema": { "type": "string", - "example": "ok" + "example": "db1" + }, + "pass_rate": { + "type": "number" + }, + "score": { + "type": "integer" + }, + "sql_source": { + "type": "string", + "enum": [ + "form_data", + "sql_file", + "mybatis_xml_file", + "audit_plan" + ] + }, + "status": { + "type": "string", + "enum": [ + "initialized", + "audited", + "executing", + "exec_success", + "exec_failed", + "manually_executed" + ] + }, + "task_id": { + "type": "integer" } } }, - "v1.GetMembersRespV1": { + "v1.AuditTaskSQLContentResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.GetMemberRespDataV1" - } - }, - "message": { + "sql": { "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" + "example": "alter table tb1 drop columns c1" } } }, - "v1.GetOauth2ConfigurationResDataV1": { + "v1.AuditTaskSQLResV1": { "type": "object", "properties": { - "access_token_tag": { + "audit_level": { "type": "string" }, - "client_host": { + "audit_result": { "type": "string" }, - "client_id": { + "audit_status": { "type": "string" }, - "enable_oauth2": { - "type": "boolean" - }, - "login_tip": { + "description": { "type": "string" }, - "scopes": { - "type": "array", - "items": { - "type": "string" - } - }, - "server_auth_url": { + "exec_result": { "type": "string" }, - "server_token_url": { + "exec_sql": { "type": "string" }, - "server_user_id_url": { + "exec_status": { "type": "string" }, - "user_id_tag": { + "number": { + "type": "integer" + }, + "rollback_sql": { "type": "string" } } }, - "v1.GetOauth2ConfigurationResV1": { + "v1.AuditTasksGroupResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetOauth2ConfigurationResDataV1" - }, - "message": { - "type": "string", - "example": "ok" + "task_group_id": { + "type": "integer" } } }, - "v1.GetOauth2TipsResDataV1": { + "v1.AuditWhitelistResV1": { "type": "object", "properties": { - "enable_oauth2": { - "type": "boolean" + "audit_whitelist_id": { + "type": "integer" + }, + "desc": { + "type": "string" + }, + "match_type": { + "type": "string" }, - "login_tip": { + "value": { "type": "string" } } }, - "v1.GetOauth2TipsResV1": { + "v1.AuditedSQLCount": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetOauth2TipsResDataV1" + "risk_sql_count": { + "type": "integer" }, - "message": { - "type": "string", - "example": "ok" + "total_sql_count": { + "type": "integer" } } }, - "v1.GetOperationActionListResV1": { + "v1.BatchCancelWorkflowsReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "workflow_names": { "type": "array", "items": { - "$ref": "#/definitions/v1.OperationActionList" + "type": "string" } - }, - "message": { - "type": "string", - "example": "ok" } } }, - "v1.GetOperationRecordListResV1": { + "v1.BatchCheckInstanceConnectionsReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "instances": { "type": "array", "items": { - "$ref": "#/definitions/v1.OperationRecordList" + "$ref": "#/definitions/v1.InstanceForCheckConnection" } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" } } }, - "v1.GetOperationTypeNamesListResV1": { + "v1.BatchCompleteWorkflowsReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "workflow_names": { "type": "array", "items": { - "$ref": "#/definitions/v1.OperationTypeNameList" + "type": "string" } - }, - "message": { - "type": "string", - "example": "ok" } } }, - "v1.GetOperationsResV1": { + "v1.BatchGetInstanceConnectionsResV1": { "type": "object", "properties": { "code": { @@ -12766,7 +8002,7 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.OperationResV1" + "$ref": "#/definitions/v1.InstanceConnectionResV1" } }, "message": { @@ -12775,85 +8011,137 @@ var doc = `{ } } }, - "v1.GetProjectDetailResV1": { + "v1.BatchUpdateSqlManageReq": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "assignees": { + "type": "array", + "items": { + "type": "string" + } }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.ProjectDetailItem" + "remark": { + "type": "string" }, - "message": { + "sql_manage_id_list": { + "type": "array", + "items": { + "type": "integer" + } + }, + "status": { "type": "string", - "example": "ok" + "enum": [ + "solved", + "ignored", + "manual_audited" + ] } } }, - "v1.GetProjectResV1": { + "v1.CheckLicenseResV1": { "type": "object", "properties": { "code": { "type": "integer", "example": 0 }, - "data": { + "content": { + "type": "string" + }, + "license": { "type": "array", "items": { - "$ref": "#/definitions/v1.ProjectListItem" + "$ref": "#/definitions/v1.LicenseItem" } }, "message": { "type": "string", "example": "ok" - }, - "total_nums": { - "type": "integer" } } }, - "v1.GetProjectRuleTemplateResV1": { + "v1.CloneProjectRuleTemplateReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.RuleProjectTemplateDetailResV1" + "new_rule_template_name": { + "type": "string" + } + } + }, + "v1.CloneRuleTemplateReqV1": { + "type": "object", + "properties": { + "desc": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "new_rule_template_name": { + "type": "string" } } }, - "v1.GetProjectRuleTemplatesResV1": { + "v1.CompanyNotice": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "notice_str": { + "type": "string" + } + } + }, + "v1.CreateAuditPlanReqV1": { + "type": "object", + "properties": { + "audit_plan_cron": { + "type": "string", + "example": "0 */2 * * *" }, - "data": { + "audit_plan_instance_database": { + "type": "string", + "example": "app1" + }, + "audit_plan_instance_name": { + "type": "string", + "example": "test_mysql" + }, + "audit_plan_instance_type": { + "type": "string", + "example": "mysql" + }, + "audit_plan_name": { + "type": "string", + "example": "audit_plan_for_java_repo_1" + }, + "audit_plan_params": { "type": "array", "items": { - "$ref": "#/definitions/v1.ProjectRuleTemplateResV1" + "$ref": "#/definitions/v1.AuditPlanParamReqV1" } }, - "message": { + "audit_plan_type": { "type": "string", - "example": "ok" + "example": "slow log" }, - "total_nums": { - "type": "integer" + "rule_template_name": { + "type": "string", + "example": "default_MySQL" } } }, - "v1.GetProjectScoreResV1": { + "v1.CreateAuditTasksGroupReqV1": { + "type": "object", + "properties": { + "instances": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.InstanceForCreatingTask" + } + } + } + }, + "v1.CreateAuditTasksGroupResV1": { "type": "object", "properties": { "code": { @@ -12862,7 +8150,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.ProjectScore" + "$ref": "#/definitions/v1.AuditTasksGroupResV1" }, "message": { "type": "string", @@ -12870,104 +8158,102 @@ var doc = `{ } } }, - "v1.GetProjectStatisticsResDataV1": { + "v1.CreateAuditWhitelistReqV1": { "type": "object", "properties": { - "audit_plan_total": { - "type": "integer" - }, - "instance_total": { - "type": "integer" - }, - "member_total": { - "type": "integer" - }, - "rule_template_total": { - "type": "integer" + "desc": { + "type": "string", + "example": "used for rapid release" }, - "whitelist_total": { - "type": "integer" + "match_type": { + "type": "string", + "enum": [ + "exact_match", + "fp_match" + ], + "example": "exact_match" }, - "workflow_total": { - "type": "integer" + "value": { + "type": "string", + "example": "create table" } } }, - "v1.GetProjectStatisticsResV1": { + "v1.CreateCustomRuleReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "annotation": { + "type": "string", + "example": "this is test rule" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetProjectStatisticsResDataV1" + "db_type": { + "type": "string", + "example": "MySQL" }, - "message": { + "desc": { "type": "string", - "example": "ok" - } - } - }, - "v1.GetProjectTipsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 + "example": "this is test rule" + }, + "level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "example": "notice" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ProjectTipResV1" - } + "rule_script": { + "type": "string" }, - "message": { + "type": { "type": "string", - "example": "ok" + "example": "DDL规则" } } }, - "v1.GetRiskAuditPlanResV1": { + "v1.CreateProjectRuleTemplateReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { + "desc": { + "type": "string" + }, + "rule_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.RiskAuditPlan" + "$ref": "#/definitions/v1.RuleReqV1" } }, - "message": { - "type": "string", - "example": "ok" + "rule_template_name": { + "type": "string" } } }, - "v1.GetRoleTipsResV1": { + "v1.CreateRuleTemplateReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { + "desc": { + "type": "string" + }, + "rule_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.RoleTipResV1" + "$ref": "#/definitions/v1.RuleReqV1" } }, - "message": { - "type": "string", - "example": "ok" + "rule_template_name": { + "type": "string" } } }, - "v1.GetRoleUserCountResV1": { + "v1.CreateSQLAuditRecordResV1": { "type": "object", "properties": { "code": { @@ -12975,10 +8261,8 @@ var doc = `{ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RoleUserCount" - } + "type": "object", + "$ref": "#/definitions/v1.SQLAuditRecordResData" }, "message": { "type": "string", @@ -12986,174 +8270,190 @@ var doc = `{ } } }, - "v1.GetRolesResV1": { + "v1.CreateWorkflowReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { + "task_ids": { "type": "array", "items": { - "$ref": "#/definitions/v1.RoleResV1" + "type": "integer" } }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" + "workflow_subject": { + "type": "string" } } }, - "v1.GetRuleKnowledgeResV1": { + "v1.CustomRuleResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "annotation": { + "type": "string", + "example": "this is test rule" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.RuleKnowledgeResV1" + "db_type": { + "type": "string", + "example": "MySQL" }, - "message": { + "desc": { "type": "string", - "example": "ok" - } - } - }, - "v1.GetRuleTemplateResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 + "example": "this is test rule" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.RuleTemplateDetailResV1" + "level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "example": "notice" }, - "message": { + "rule_id": { + "type": "string" + }, + "rule_script": { + "type": "string" + }, + "type": { "type": "string", - "example": "ok" + "example": "DDL规则" } } }, - "v1.GetRuleTemplateTipsResV1": { + "v1.DBTypeAuditPlan": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleTemplateTipResV1" + "$ref": "#/definitions/v1.AuditPlanCount" } }, - "message": { - "type": "string", - "example": "ok" + "db_type": { + "type": "string" } } }, - "v1.GetRuleTemplatesResV1": { + "v1.DBTypeHealth": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { + "health_instance_names": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleTemplateResV1" + "type": "string" } }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" + "unhealth_instance_names": { + "type": "array", + "items": { + "type": "string" + } } } }, - "v1.GetRuleTypeByDBTypeResV1": { + "v1.DashboardResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleTypeV1" - } - }, - "message": { - "type": "string", - "example": "ok" + "workflow_statistics": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowStatisticsResV1" } } }, - "v1.GetRulesResV1": { + "v1.DingTalkConfigurationV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleResV1" - } + "app_key": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "is_enable_ding_talk_notify": { + "type": "boolean" } } }, - "v1.GetSMTPConfigurationResV1": { + "v1.DirectAuditFileReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "file_contents": { + "description": "调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现\n每个数组元素是一个文件内容", + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "select * from t1; select * from t2;" + ] }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.SMTPConfigurationResV1" + "instance_name": { + "type": "string", + "example": "instance1" }, - "message": { + "instance_type": { "type": "string", - "example": "ok" + "example": "MySQL" + }, + "project_name": { + "type": "string", + "example": "project1" + }, + "schema_name": { + "type": "string", + "example": "schema1" + }, + "sql_type": { + "type": "string", + "enum": [ + "sql", + "mybatis", + "" + ], + "example": "sql" } } }, - "v1.GetSQLAnalysisDataResItemV1": { + "v1.DirectAuditReqV1": { "type": "object", "properties": { - "sql_explain": { - "type": "object", - "$ref": "#/definitions/v1.SQLExplain" + "instance_name": { + "type": "string", + "example": "instance1" + }, + "instance_type": { + "type": "string", + "example": "MySQL" + }, + "project_name": { + "type": "string", + "example": "project1" + }, + "schema_name": { + "type": "string", + "example": "schema1" + }, + "sql_content": { + "description": "调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现", + "type": "string", + "example": "select * from t1; select * from t2;" }, - "table_metas": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMeta" - } + "sql_type": { + "type": "string", + "enum": [ + "sql", + "mybatis", + "" + ], + "example": "sql" } } }, - "v1.GetSQLAuditRecordResV1": { + "v1.DirectAuditResV1": { "type": "object", "properties": { "code": { @@ -13162,7 +8462,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.SQLAuditRecord" + "$ref": "#/definitions/v1.AuditResDataV1" }, "message": { "type": "string", @@ -13170,7 +8470,7 @@ var doc = `{ } } }, - "v1.GetSQLAuditRecordTagTipsResV1": { + "v1.DirectGetSQLAnalysisResV1": { "type": "object", "properties": { "code": { @@ -13180,7 +8480,7 @@ var doc = `{ "data": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.SqlAnalysisResDataV1" } }, "message": { @@ -13189,88 +8489,60 @@ var doc = `{ } } }, - "v1.GetSQLAuditRecordsResV1": { + "v1.DriversResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "driver_name_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.SQLAuditRecord" + "type": "string" } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" } } }, - "v1.GetSQLEInfoResDataV1": { + "v1.ExplainClassicResult": { "type": "object", "properties": { - "logo_url": { - "type": "string" - }, - "title": { - "type": "string" + "head": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMetaItemHeadResV1" + } }, - "version": { - "type": "string" + "rows": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } } } }, - "v1.GetSQLEInfoResV1": { + "v1.FeishuConfigurationV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetSQLEInfoResDataV1" + "app_id": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetSQLQueryConfigurationResDataV1": { - "type": "object", - "properties": { - "enable_sql_query": { + "is_feishu_notification_enabled": { "type": "boolean" - }, - "sql_query_root_uri": { - "type": "string" } } }, - "v1.GetSQLQueryConfigurationResV1": { + "v1.FullSyncAuditPlanSQLsReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetSQLQueryConfigurationResDataV1" - }, - "message": { - "type": "string", - "example": "ok" + "audit_plan_sql_list": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.AuditPlanSQLReqV1" + } } } }, - "v1.GetSqlAverageExecutionTimeResV1": { + "v1.GetAuditPlanAnalysisDataResV1": { "type": "object", "properties": { "code": { @@ -13278,10 +8550,8 @@ var doc = `{ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.SqlAverageExecutionTime" - } + "type": "object", + "$ref": "#/definitions/v1.GetSQLAnalysisDataResItemV1" }, "message": { "type": "string", @@ -13289,7 +8559,7 @@ var doc = `{ } } }, - "v1.GetSqlExecutionFailPercentResV1": { + "v1.GetAuditPlanMetasResV1": { "type": "object", "properties": { "code": { @@ -13299,7 +8569,7 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.SqlExecutionFailPercent" + "$ref": "#/definitions/v1.AuditPlanMetaV1" } }, "message": { @@ -13308,35 +8578,30 @@ var doc = `{ } } }, - "v1.GetSqlManageListResp": { + "v1.GetAuditPlanNotifyConfigResDataV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.SqlManage" - } + "enable_email_notify": { + "type": "boolean" }, - "message": { - "type": "string", - "example": "ok" + "enable_web_hook_notify": { + "type": "boolean" }, - "sql_manage_bad_num": { + "notify_interval": { "type": "integer" }, - "sql_manage_optimized_num": { - "type": "integer" + "notify_level": { + "type": "string" }, - "sql_manage_total_num": { - "type": "integer" + "web_hook_template": { + "type": "string" + }, + "web_hook_url": { + "type": "string" } } }, - "v1.GetSqlManageRuleTipsResp": { + "v1.GetAuditPlanNotifyConfigResV1": { "type": "object", "properties": { "code": { @@ -13344,10 +8609,8 @@ var doc = `{ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleTips" - } + "type": "object", + "$ref": "#/definitions/v1.GetAuditPlanNotifyConfigResDataV1" }, "message": { "type": "string", @@ -13355,7 +8618,7 @@ var doc = `{ } } }, - "v1.GetSqlManageSqlAnalysisResp": { + "v1.GetAuditPlanReportResV1": { "type": "object", "properties": { "code": { @@ -13364,7 +8627,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.SqlAnalysis" + "$ref": "#/definitions/v1.AuditPlanReportResV1" }, "message": { "type": "string", @@ -13372,7 +8635,7 @@ var doc = `{ } } }, - "v1.GetSyncInstanceTaskListResV1": { + "v1.GetAuditPlanReportSQLsResV1": { "type": "object", "properties": { "code": { @@ -13382,33 +8645,19 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.InstanceTaskResV1" + "$ref": "#/definitions/v1.AuditPlanReportSQLResV1" } }, "message": { "type": "string", "example": "ok" - } - } - }, - "v1.GetSyncInstanceTaskResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstanceTaskDetailResV1" }, - "message": { - "type": "string", - "example": "ok" + "total_nums": { + "type": "integer" } } }, - "v1.GetSyncTaskSourceTipsResV1": { + "v1.GetAuditPlanReportsResV1": { "type": "object", "properties": { "code": { @@ -13418,33 +8667,19 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.SyncTaskTipsResV1" + "$ref": "#/definitions/v1.AuditPlanReportResV1" } }, "message": { "type": "string", "example": "ok" - } - } - }, - "v1.GetSystemVariablesResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.SystemVariablesResV1" }, - "message": { - "type": "string", - "example": "ok" + "total_nums": { + "type": "integer" } } }, - "v1.GetTableMetadataResV1": { + "v1.GetAuditPlanResV1": { "type": "object", "properties": { "code": { @@ -13453,7 +8688,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.InstanceTableMeta" + "$ref": "#/definitions/v1.AuditPlanResV1" }, "message": { "type": "string", @@ -13461,22 +8696,7 @@ var doc = `{ } } }, - "v1.GetTaskAnalysisDataResItemV1": { - "type": "object", - "properties": { - "sql_explain": { - "type": "object", - "$ref": "#/definitions/v1.SQLExplain" - }, - "table_metas": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMeta" - } - } - } - }, - "v1.GetTaskAnalysisDataResV1": { + "v1.GetAuditPlanSQLsResV1": { "type": "object", "properties": { "code": { @@ -13485,32 +8705,18 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.GetTaskAnalysisDataResItemV1" + "$ref": "#/definitions/v1.AuditPlanSQLResV1" }, "message": { "type": "string", "example": "ok" - } - } - }, - "v1.GetUserDetailResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.UserDetailResV1" }, - "message": { - "type": "string", - "example": "ok" + "total_nums": { + "type": "integer" } } }, - "v1.GetUserGroupTipsResV1": { + "v1.GetAuditPlanTypesResV1": { "type": "object", "properties": { "code": { @@ -13520,7 +8726,7 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.UserGroupTipListItem" + "$ref": "#/definitions/v1.AuditPlanTypesV1" } }, "message": { @@ -13529,7 +8735,7 @@ var doc = `{ } } }, - "v1.GetUserGroupsResV1": { + "v1.GetAuditPlansResV1": { "type": "object", "properties": { "code": { @@ -13539,7 +8745,7 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.UserGroupListItemResV1" + "$ref": "#/definitions/v1.AuditPlanResV1" } }, "message": { @@ -13551,7 +8757,7 @@ var doc = `{ } } }, - "v1.GetUserLoginResV1": { + "v1.GetAuditTaskResV1": { "type": "object", "properties": { "code": { @@ -13560,7 +8766,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.UserLoginResV1" + "$ref": "#/definitions/v1.AuditTaskResV1" }, "message": { "type": "string", @@ -13568,7 +8774,7 @@ var doc = `{ } } }, - "v1.GetUserTipsResV1": { + "v1.GetAuditTaskSQLContentResV1": { "type": "object", "properties": { "code": { @@ -13576,10 +8782,8 @@ var doc = `{ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.UserTipResV1" - } + "type": "object", + "$ref": "#/definitions/v1.AuditTaskSQLContentResV1" }, "message": { "type": "string", @@ -13587,7 +8791,7 @@ var doc = `{ } } }, - "v1.GetUsersResV1": { + "v1.GetAuditTaskSQLsResV1": { "type": "object", "properties": { "code": { @@ -13597,7 +8801,7 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.UserResV1" + "$ref": "#/definitions/v1.AuditTaskSQLResV1" } }, "message": { @@ -13609,7 +8813,7 @@ var doc = `{ } } }, - "v1.GetWeChatConfigurationResV1": { + "v1.GetAuditWhitelistResV1": { "type": "object", "properties": { "code": { @@ -13617,16 +8821,21 @@ var doc = `{ "example": 0 }, "data": { - "type": "object", - "$ref": "#/definitions/v1.WeChatConfigurationResV1" + "type": "array", + "items": { + "$ref": "#/definitions/v1.AuditWhitelistResV1" + } }, "message": { "type": "string", "example": "ok" + }, + "total_nums": { + "type": "integer" } } }, - "v1.GetWorkflowAuditPassPercentResV1": { + "v1.GetCompanyNoticeResp": { "type": "object", "properties": { "code": { @@ -13635,7 +8844,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowAuditPassPercentV1" + "$ref": "#/definitions/v1.CompanyNotice" }, "message": { "type": "string", @@ -13643,7 +8852,7 @@ var doc = `{ } } }, - "v1.GetWorkflowCountsResV1": { + "v1.GetCustomRuleResV1": { "type": "object", "properties": { "code": { @@ -13652,7 +8861,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowCountsV1" + "$ref": "#/definitions/v1.CustomRuleResV1" }, "message": { "type": "string", @@ -13660,7 +8869,7 @@ var doc = `{ } } }, - "v1.GetWorkflowCreatedCountsEachDayResV1": { + "v1.GetCustomRulesResV1": { "type": "object", "properties": { "code": { @@ -13668,8 +8877,10 @@ var doc = `{ "example": 0 }, "data": { - "type": "object", - "$ref": "#/definitions/v1.WorkflowCreatedCountsEachDayV1" + "type": "array", + "items": { + "$ref": "#/definitions/v1.CustomRuleResV1" + } }, "message": { "type": "string", @@ -13677,7 +8888,7 @@ var doc = `{ } } }, - "v1.GetWorkflowDurationOfWaitingForAuditResV1": { + "v1.GetDashboardResV1": { "type": "object", "properties": { "code": { @@ -13686,7 +8897,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowStageDuration" + "$ref": "#/definitions/v1.DashboardResV1" }, "message": { "type": "string", @@ -13694,7 +8905,7 @@ var doc = `{ } } }, - "v1.GetWorkflowDurationOfWaitingForExecutionResV1": { + "v1.GetDingTalkConfigurationResV1": { "type": "object", "properties": { "code": { @@ -13703,7 +8914,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowStageDuration" + "$ref": "#/definitions/v1.DingTalkConfigurationV1" }, "message": { "type": "string", @@ -13711,7 +8922,7 @@ var doc = `{ } } }, - "v1.GetWorkflowPassPercentResV1": { + "v1.GetDriversResV1": { "type": "object", "properties": { "code": { @@ -13720,7 +8931,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowPassPercentV1" + "$ref": "#/definitions/v1.DriversResV1" }, "message": { "type": "string", @@ -13728,7 +8939,7 @@ var doc = `{ } } }, - "v1.GetWorkflowPercentCountedByInstanceTypeResV1": { + "v1.GetFeishuAuditConfigurationResV1": { "type": "object", "properties": { "code": { @@ -13737,7 +8948,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowPercentCountedByInstanceTypeV1" + "$ref": "#/definitions/v1.FeishuConfigurationV1" }, "message": { "type": "string", @@ -13745,7 +8956,7 @@ var doc = `{ } } }, - "v1.GetWorkflowRejectedPercentGroupByCreatorResV1": { + "v1.GetInstanceConnectableResV1": { "type": "object", "properties": { "code": { @@ -13753,10 +8964,8 @@ var doc = `{ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.WorkflowRejectedPercentGroupByCreator" - } + "type": "object", + "$ref": "#/definitions/v1.InstanceConnectableResV1" }, "message": { "type": "string", @@ -13764,7 +8973,7 @@ var doc = `{ } } }, - "v1.GetWorkflowRejectedPercentGroupByInstanceResV1": { + "v1.GetInstanceHealthResV1": { "type": "object", "properties": { "code": { @@ -13774,7 +8983,7 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.WorkflowRejectedPercentGroupByInstance" + "$ref": "#/definitions/v1.DBTypeHealth" } }, "message": { @@ -13783,7 +8992,7 @@ var doc = `{ } } }, - "v1.GetWorkflowResV1": { + "v1.GetInstanceSchemaResV1": { "type": "object", "properties": { "code": { @@ -13792,7 +9001,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowResV1" + "$ref": "#/definitions/v1.InstanceSchemaResV1" }, "message": { "type": "string", @@ -13800,7 +9009,7 @@ var doc = `{ } } }, - "v1.GetWorkflowStatusCountResV1": { + "v1.GetInstanceTipsResV1": { "type": "object", "properties": { "code": { @@ -13808,8 +9017,10 @@ var doc = `{ "example": 0 }, "data": { - "type": "object", - "$ref": "#/definitions/v1.WorkflowStatusCountV1" + "type": "array", + "items": { + "$ref": "#/definitions/v1.InstanceTipResV1" + } }, "message": { "type": "string", @@ -13817,70 +9028,37 @@ var doc = `{ } } }, - "v1.GetWorkflowTasksItemV1": { + "v1.GetInstancesTypePercentResV1": { "type": "object", "properties": { - "current_step_assignee_user_name_list": { - "type": "array", - "items": { - "type": "string" - } - }, - "exec_end_time": { - "type": "string" - }, - "exec_start_time": { - "type": "string" - }, - "execution_user_name": { - "type": "string" - }, - "instance_maintenance_times": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MaintenanceTimeResV1" - } - }, - "instance_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "schedule_time": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.InstancesTypePercentV1" }, - "status": { + "message": { "type": "string", - "enum": [ - "wait_for_audit", - "wait_for_execution", - "exec_scheduled", - "exec_failed", - "exec_succeeded", - "executing", - "manually_executed" - ] - }, - "task_id": { - "type": "integer" - }, - "task_pass_rate": { - "type": "number" - }, - "task_score": { - "type": "integer" + "example": "ok" } } }, - "v1.GetWorkflowTasksResV1": { + "v1.GetLicenseResV1": { "type": "object", "properties": { "code": { "type": "integer", "example": 0 }, - "data": { + "content": { + "type": "string" + }, + "license": { "type": "array", "items": { - "$ref": "#/definitions/v1.GetWorkflowTasksItemV1" + "$ref": "#/definitions/v1.LicenseItem" } }, "message": { @@ -13889,7 +9067,7 @@ var doc = `{ } } }, - "v1.GetWorkflowTemplateResV1": { + "v1.GetLicenseUsageResV1": { "type": "object", "properties": { "code": { @@ -13898,7 +9076,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowTemplateDetailResV1" + "$ref": "#/definitions/v1.LicenseUsageV1" }, "message": { "type": "string", @@ -13906,7 +9084,7 @@ var doc = `{ } } }, - "v1.GetWorkflowWebHookConfigResV1": { + "v1.GetOperationActionListResV1": { "type": "object", "properties": { "code": { @@ -13914,8 +9092,10 @@ var doc = `{ "example": 0 }, "data": { - "type": "object", - "$ref": "#/definitions/v1.WebHookConfigV1" + "type": "array", + "items": { + "$ref": "#/definitions/v1.OperationActionList" + } }, "message": { "type": "string", @@ -13923,7 +9103,7 @@ var doc = `{ } } }, - "v1.GetWorkflowsResV1": { + "v1.GetOperationRecordListResV1": { "type": "object", "properties": { "code": { @@ -13933,7 +9113,7 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.WorkflowDetailResV1" + "$ref": "#/definitions/v1.OperationRecordList" } }, "message": { @@ -13945,420 +9125,273 @@ var doc = `{ } } }, - "v1.GlobalRuleTemplateInstance": { - "type": "object", - "properties": { - "instance_name": { - "type": "string" - }, - "project_name": { - "type": "string" - } - } - }, - "v1.InstanceAdditionalMetaV1": { - "type": "object", - "properties": { - "db_type": { - "type": "string" - }, - "params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamResV1" - } - } - } - }, - "v1.InstanceAdditionalParamReqV1": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "v1.InstanceAdditionalParamResV1": { - "type": "object", - "properties": { - "description": { - "type": "string", - "example": "参数项中文名" - }, - "name": { - "type": "string", - "example": "param name" - }, - "type": { - "type": "string", - "example": "int" - }, - "value": { - "type": "string", - "example": "0" - } - } - }, - "v1.InstanceConnectableResV1": { - "type": "object", - "properties": { - "connect_error_message": { - "type": "string" - }, - "is_instance_connectable": { - "type": "boolean" - } - } - }, - "v1.InstanceConnectionResV1": { - "type": "object", - "properties": { - "connect_error_message": { - "type": "string" - }, - "instance_name": { - "type": "string" - }, - "is_instance_connectable": { - "type": "boolean" - } - } - }, - "v1.InstanceForCheckConnection": { - "type": "object", - "properties": { - "name": { - "type": "string" - } - } - }, - "v1.InstanceForCreatingTask": { - "type": "object", - "properties": { - "instance_name": { - "type": "string" - }, - "instance_schema": { - "type": "string" - } - } - }, - "v1.InstanceResV1": { + "v1.GetOperationTypeNamesListResV1": { "type": "object", "properties": { - "additional_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamResV1" - } - }, - "db_host": { - "type": "string", - "example": "10.10.10.10" - }, - "db_port": { - "type": "string", - "example": "3306" - }, - "db_type": { - "type": "string", - "example": "mysql" - }, - "db_user": { - "type": "string", - "example": "root" - }, - "desc": { - "type": "string", - "example": "this is a instance" - }, - "instance_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "maintenance_times": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.MaintenanceTimeResV1" + "$ref": "#/definitions/v1.OperationTypeNameList" } }, - "rule_template_name": { - "type": "string" - }, - "source": { + "message": { "type": "string", - "example": "SQLE" - }, - "sql_query_config": { - "type": "object", - "$ref": "#/definitions/v1.SQLQueryConfigResV1" + "example": "ok" } } }, - "v1.InstanceSchemaResV1": { + "v1.GetOperationsResV1": { "type": "object", "properties": { - "schema_name_list": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.OperationResV1" } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.InstanceTableMeta": { + "v1.GetProjectRuleTemplateResV1": { "type": "object", "properties": { - "columns": { - "type": "object", - "$ref": "#/definitions/v1.TableColumns" - }, - "create_table_sql": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "indexes": { + "data": { "type": "object", - "$ref": "#/definitions/v1.TableIndexes" - }, - "name": { - "type": "string" + "$ref": "#/definitions/v1.RuleProjectTemplateDetailResV1" }, - "schema": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.InstanceTaskDetailResV1": { + "v1.GetProjectRuleTemplatesResV1": { "type": "object", "properties": { - "db_type": { - "type": "string", - "example": "mysql" - }, - "id": { + "code": { "type": "integer", - "example": 1 - }, - "rule_template": { - "type": "string", - "example": "default_mysql" - }, - "source": { - "type": "string", - "example": "actiontech-dmp" + "example": 0 }, - "sync_instance_interval": { - "type": "string", - "example": "0 0 * * *" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.ProjectRuleTemplateResV1" + } }, - "url": { + "message": { "type": "string", - "example": "http://10.186.62.56:10000" + "example": "ok" }, - "version": { - "type": "string", - "example": "1.23.1" + "total_nums": { + "type": "integer" } } }, - "v1.InstanceTaskResV1": { + "v1.GetProjectScoreResV1": { "type": "object", "properties": { - "db_type": { - "type": "string", - "example": "mysql" - }, - "id": { + "code": { "type": "integer", - "example": 1 - }, - "last_sync_status": { - "type": "string", - "enum": [ - "succeeded", - "failed" - ], - "example": "succeeded" - }, - "last_sync_success_time": { - "type": "string", - "example": "2021-08-12 12:00:00" - }, - "source": { - "type": "string", - "example": "actiontech-dmp" + "example": 0 }, - "url": { - "type": "string", - "example": "http://10.186.62.56:10000" + "data": { + "type": "object", + "$ref": "#/definitions/v1.ProjectScore" }, - "version": { + "message": { "type": "string", - "example": "1.23.1" + "example": "ok" } } }, - "v1.InstanceTipResV1": { + "v1.GetProjectStatisticsResDataV1": { "type": "object", "properties": { - "host": { - "type": "string" + "audit_plan_total": { + "type": "integer" }, - "instance_name": { - "type": "string" + "instance_total": { + "type": "integer" }, - "instance_type": { - "type": "string" + "member_total": { + "type": "integer" }, - "port": { - "type": "string" + "rule_template_total": { + "type": "integer" }, - "workflow_template_id": { + "whitelist_total": { + "type": "integer" + }, + "workflow_total": { "type": "integer" } } }, - "v1.InstanceTypePercent": { + "v1.GetProjectStatisticsResV1": { "type": "object", "properties": { - "count": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 }, - "percent": { - "type": "number" + "data": { + "type": "object", + "$ref": "#/definitions/v1.GetProjectStatisticsResDataV1" }, - "type": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.InstancesTypePercentV1": { + "v1.GetRiskAuditPlanResV1": { "type": "object", "properties": { - "instance_total_num": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 }, - "instance_type_percents": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.InstanceTypePercent" + "$ref": "#/definitions/v1.RiskAuditPlan" } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.LDAPConfigurationReqV1": { + "v1.GetRoleUserCountResV1": { "type": "object", "properties": { - "enable_ldap": { - "type": "boolean" - }, - "enable_ssl": { - "type": "boolean" - }, - "ldap_connect_dn": { - "type": "string" - }, - "ldap_connect_pwd": { - "type": "string" - }, - "ldap_search_base_dn": { - "type": "string" - }, - "ldap_server_host": { - "type": "string" - }, - "ldap_server_port": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "ldap_user_email_rdn_key": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RoleUserCount" + } }, - "ldap_user_name_rdn_key": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.LDAPConfigurationResV1": { + "v1.GetRuleKnowledgeResV1": { "type": "object", "properties": { - "enable_ldap": { - "type": "boolean" - }, - "enable_ssl": { - "type": "boolean" - }, - "ldap_connect_dn": { - "type": "string" - }, - "ldap_search_base_dn": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "ldap_server_host": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.RuleKnowledgeResV1" }, - "ldap_server_port": { - "type": "string" + "message": { + "type": "string", + "example": "ok" + } + } + }, + "v1.GetRuleTemplateResV1": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 0 }, - "ldap_user_email_rdn_key": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.RuleTemplateDetailResV1" }, - "ldap_user_name_rdn_key": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.LicenseItem": { + "v1.GetRuleTemplateTipsResV1": { "type": "object", "properties": { - "description": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "limit": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleTemplateTipResV1" + } }, - "name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.LicenseUsageItem": { + "v1.GetRuleTemplatesResV1": { "type": "object", "properties": { - "is_limited": { - "type": "boolean" - }, - "limit": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 }, - "resource_type": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleTemplateResV1" + } }, - "resource_type_desc": { - "type": "string" + "message": { + "type": "string", + "example": "ok" }, - "used": { + "total_nums": { "type": "integer" } } }, - "v1.LicenseUsageV1": { + "v1.GetRuleTypeByDBTypeResV1": { "type": "object", "properties": { - "instances_usage": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.LicenseUsageItem" + "$ref": "#/definitions/v1.RuleTypeV1" } }, - "users_usage": { - "type": "object", - "$ref": "#/definitions/v1.LicenseUsageItem" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ListTableBySchemaResV1": { + "v1.GetRulesResV1": { "type": "object", "properties": { "code": { @@ -14368,7 +9401,7 @@ var doc = `{ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.Table" + "$ref": "#/definitions/v1.RuleResV1" } }, "message": { @@ -14377,213 +9410,183 @@ var doc = `{ } } }, - "v1.MaintenanceTimeReqV1": { + "v1.GetSQLAnalysisDataResItemV1": { "type": "object", "properties": { - "maintenance_start_time": { + "sql_explain": { "type": "object", - "$ref": "#/definitions/v1.TimeReqV1" + "$ref": "#/definitions/v1.SQLExplain" }, - "maintenance_stop_time": { - "type": "object", - "$ref": "#/definitions/v1.TimeReqV1" + "table_metas": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMeta" + } } } }, - "v1.MaintenanceTimeResV1": { + "v1.GetSQLAuditRecordResV1": { "type": "object", "properties": { - "maintenance_start_time": { - "type": "object", - "$ref": "#/definitions/v1.TimeResV1" + "code": { + "type": "integer", + "example": 0 }, - "maintenance_stop_time": { + "data": { "type": "object", - "$ref": "#/definitions/v1.TimeResV1" + "$ref": "#/definitions/v1.SQLAuditRecord" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ManagementPermissionResV1": { + "v1.GetSQLAuditRecordTagTipsResV1": { "type": "object", "properties": { "code": { - "type": "integer" + "type": "integer", + "example": 0 }, - "desc": { - "type": "string" - } - } - }, - "v1.MemberGroupUserItem": { - "type": "object", - "properties": { - "name": { - "type": "string" - } - } - }, - "v1.MemberTipResV1": { - "type": "object", - "properties": { - "user_name": { - "type": "string" + "data": { + "type": "array", + "items": { + "type": "string" + } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.Oauth2ConfigurationReqV1": { + "v1.GetSQLAuditRecordsResV1": { "type": "object", "properties": { - "access_token_tag": { - "type": "string" - }, - "client_host": { - "type": "string" - }, - "client_id": { - "type": "string" - }, - "client_key": { - "type": "string" - }, - "enable_oauth2": { - "type": "boolean" - }, - "login_tip": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "scopes": { + "data": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.SQLAuditRecord" } }, - "server_auth_url": { - "type": "string" - }, - "server_token_url": { - "type": "string" - }, - "server_user_id_url": { - "type": "string" + "message": { + "type": "string", + "example": "ok" }, - "user_id_tag": { - "type": "string" + "total_nums": { + "type": "integer" } } }, - "v1.Operation": { + "v1.GetSqlAverageExecutionTimeResV1": { "type": "object", "properties": { - "op_code": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 }, - "op_desc": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.SqlAverageExecutionTime" + } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.OperationActionList": { + "v1.GetSqlExecutionFailPercentResV1": { "type": "object", "properties": { - "desc": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "operation_action": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.SqlExecutionFailPercent" + } }, - "operation_type": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.OperationRecordList": { + "v1.GetSqlManageListResp": { "type": "object", "properties": { - "id": { - "type": "integer" - }, - "operation_action": { - "type": "string" - }, - "operation_content": { - "type": "string" - }, - "operation_time": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "operation_type_name": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.SqlManage" + } }, - "operation_user": { - "type": "object", - "$ref": "#/definitions/v1.OperationUser" + "message": { + "type": "string", + "example": "ok" }, - "project_name": { - "type": "string" + "sql_manage_bad_num": { + "type": "integer" }, - "status": { - "type": "string", - "enum": [ - "succeeded", - "failed" - ] - } - } - }, - "v1.OperationResV1": { - "type": "object", - "properties": { - "op_code": { + "sql_manage_optimized_num": { "type": "integer" }, - "op_desc": { - "type": "string" + "sql_manage_total_num": { + "type": "integer" } } }, - "v1.OperationTypeNameList": { + "v1.GetSqlManageRuleTipsResp": { "type": "object", "properties": { - "desc": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "operation_type_name": { - "type": "string" - } - } - }, - "v1.OperationUser": { - "type": "object", - "properties": { - "ip": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleTips" + } }, - "user_name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ParseProjectRuleTemplateFileResDataV1": { + "v1.GetSqlManageSqlAnalysisResp": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "name": { - "type": "string" + "data": { + "description": "V1版本不能引用V2版本的结构体,所以只能复制一份", + "type": "object", + "$ref": "#/definitions/v1.SqlAnalysis" }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleResV1" - } + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ParseProjectRuleTemplateFileResV1": { + "v1.GetSystemVariablesResV1": { "type": "object", "properties": { "code": { @@ -14592,7 +9595,7 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.ParseProjectRuleTemplateFileResDataV1" + "$ref": "#/definitions/v1.SystemVariablesResV1" }, "message": { "type": "string", @@ -14600,795 +9603,708 @@ var doc = `{ } } }, - "v1.PartialSyncAuditPlanSQLsReqV1": { + "v1.GetTableMetadataResV1": { "type": "object", "properties": { - "audit_plan_sql_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanSQLReqV1" - } + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.InstanceTableMeta" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.PatchUserGroupReqV1": { + "v1.GetTaskAnalysisDataResItemV1": { "type": "object", "properties": { - "is_disabled": { - "type": "boolean" - }, - "user_group_desc": { - "type": "string", - "example": "this is a group" + "sql_explain": { + "type": "object", + "$ref": "#/definitions/v1.SQLExplain" }, - "user_name_list": { + "table_metas": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.TableMeta" } } } }, - "v1.PerformanceStatistics": { + "v1.GetTaskAnalysisDataResV1": { "type": "object", "properties": { - "affect_rows": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "object", - "$ref": "#/definitions/v1.AffectRows" - } - } - }, - "v1.PersonaliseReqV1": { - "type": "object", - "properties": { - "title": { - "type": "string" + "$ref": "#/definitions/v1.GetTaskAnalysisDataResItemV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectDetailItem": { + "v1.GetUserTipsResV1": { "type": "object", "properties": { - "archived": { - "type": "boolean" - }, - "create_time": { - "type": "string" - }, - "create_user_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "desc": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.UserTipResV1" + } }, - "name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectListItem": { + "v1.GetWorkflowAuditPassPercentResV1": { "type": "object", "properties": { - "archived": { - "type": "boolean" - }, - "create_time": { - "type": "string" - }, - "create_user_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "desc": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowAuditPassPercentV1" }, - "name": { - "type": "string" - } - } - }, - "v1.ProjectRuleTemplateInstance": { - "type": "object", - "properties": { - "name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectRuleTemplateResV1": { + "v1.GetWorkflowCountsResV1": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "instance_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ProjectRuleTemplateInstance" - } + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowCountsV1" }, - "rule_template_name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectScore": { + "v1.GetWorkflowCreatedCountsEachDayResV1": { "type": "object", "properties": { - "score": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowCreatedCountsEachDayV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectTipResV1": { + "v1.GetWorkflowDurationOfWaitingForAuditResV1": { "type": "object", "properties": { - "project_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowStageDuration" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RejectWorkflowReqV1": { + "v1.GetWorkflowDurationOfWaitingForExecutionResV1": { "type": "object", "properties": { - "reason": { - "type": "string" + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowStageDuration" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RiskAuditPlan": { + "v1.GetWorkflowPassPercentResV1": { "type": "object", "properties": { - "audit_plan_name": { - "type": "string" - }, - "audit_plan_report_id": { - "type": "integer" - }, - "audit_plan_report_timestamp": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "risk_sql_count": { - "type": "integer" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowPassPercentV1" }, - "trigger_audit_plan_time": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RiskWorkflow": { + "v1.GetWorkflowPercentCountedByInstanceTypeResV1": { "type": "object", "properties": { - "create_user_name": { - "type": "string" - }, - "update_time": { - "type": "string" - }, - "workflow_id": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "workflow_name": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowPercentCountedByInstanceTypeV1" }, - "workflow_status": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RoleResV1": { + "v1.GetWorkflowRejectedPercentGroupByCreatorResV1": { "type": "object", "properties": { - "is_disabled": { - "type": "boolean" + "code": { + "type": "integer", + "example": 0 }, - "operation_list": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.Operation" + "$ref": "#/definitions/v1.WorkflowRejectedPercentGroupByCreator" } }, - "role_desc": { - "type": "string" - }, - "role_name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RoleTipResV1": { + "v1.GetWorkflowRejectedPercentGroupByInstanceResV1": { "type": "object", "properties": { - "operations": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.Operation" + "$ref": "#/definitions/v1.WorkflowRejectedPercentGroupByInstance" } }, - "role_name": { - "type": "string" - } - } - }, - "v1.RoleUserCount": { - "type": "object", - "properties": { - "count": { - "type": "integer" - }, - "role": { - "type": "string" - } - } - }, - "v1.RuleInfo": { - "type": "object", - "properties": { - "annotation": { - "type": "string", - "example": "this is test rule" - }, - "desc": { + "message": { "type": "string", - "example": "this is test rule" + "example": "ok" } } }, - "v1.RuleKnowledgeResV1": { + "v1.GetWorkflowResV1": { "type": "object", "properties": { - "knowledge_content": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "rule": { + "data": { "type": "object", - "$ref": "#/definitions/v1.RuleInfo" + "$ref": "#/definitions/v1.WorkflowResV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RuleParamReqV1": { + "v1.GetWorkflowStatusCountResV1": { "type": "object", "properties": { - "key": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "value": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowStatusCountV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RuleParamResV1": { + "v1.GetWorkflowTasksItemV1": { "type": "object", "properties": { - "desc": { + "current_step_assignee_user_name_list": { + "type": "array", + "items": { + "type": "string" + } + }, + "exec_end_time": { "type": "string" }, - "key": { + "exec_start_time": { "type": "string" }, - "type": { + "execution_user_name": { + "type": "string" + }, + "instance_maintenance_times": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.MaintenanceTimeResV1" + } + }, + "instance_name": { + "type": "string" + }, + "schedule_time": { + "type": "string" + }, + "status": { "type": "string", "enum": [ - "string", - "int", - "bool" + "wait_for_audit", + "wait_for_execution", + "exec_scheduled", + "exec_failed", + "exec_succeeded", + "executing", + "manually_executed" ] }, - "value": { - "type": "string" + "task_id": { + "type": "integer" + }, + "task_pass_rate": { + "type": "number" + }, + "task_score": { + "type": "integer" } } }, - "v1.RuleProjectTemplateDetailResV1": { + "v1.GetWorkflowTasksResV1": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "instance_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ProjectRuleTemplateInstance" - } + "code": { + "type": "integer", + "example": 0 }, - "rule_list": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleResV1" + "$ref": "#/definitions/v1.GetWorkflowTasksItemV1" } }, - "rule_template_name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RuleReqV1": { + "v1.GetWorkflowTemplateResV1": { "type": "object", "properties": { - "is_custom_rule": { - "type": "boolean" + "code": { + "type": "integer", + "example": 0 }, - "level": { - "type": "string", - "example": "error" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowTemplateDetailResV1" }, - "name": { + "message": { "type": "string", - "example": "ddl_check_index_count" + "example": "ok" + } + } + }, + "v1.GetWorkflowsResV1": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 0 }, - "params": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleParamReqV1" + "$ref": "#/definitions/v1.WorkflowDetailResV1" } + }, + "message": { + "type": "string", + "example": "ok" + }, + "total_nums": { + "type": "integer" } } }, - "v1.RuleResV1": { + "v1.InstanceAdditionalParamResV1": { "type": "object", "properties": { - "annotation": { + "description": { "type": "string", - "example": "避免多次 table rebuild 带来的消耗、以及对线上业务的影响" + "example": "参数项中文名" }, - "db_type": { + "name": { "type": "string", - "example": "mysql" - }, - "desc": { - "type": "string" - }, - "is_custom_rule": { - "type": "boolean" + "example": "param name" }, - "level": { + "type": { "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "error" - }, - "params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleParamResV1" - } - }, - "rule_name": { - "type": "string" + "example": "int" }, - "type": { + "value": { "type": "string", - "example": "全局配置" + "example": "0" } } }, - "v1.RuleRespV1": { + "v1.InstanceConnectableResV1": { "type": "object", "properties": { - "desc": { + "connect_error_message": { "type": "string" }, - "rule_name": { - "type": "string" + "is_instance_connectable": { + "type": "boolean" } } }, - "v1.RuleTemplateDetailResV1": { + "v1.InstanceConnectionResV1": { "type": "object", "properties": { - "db_type": { + "connect_error_message": { "type": "string" }, - "desc": { + "instance_name": { "type": "string" }, - "instance_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.GlobalRuleTemplateInstance" - } - }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleResV1" - } - }, - "rule_template_name": { - "type": "string" + "is_instance_connectable": { + "type": "boolean" } } }, - "v1.RuleTemplateResV1": { + "v1.InstanceForCheckConnection": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "instance_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.GlobalRuleTemplateInstance" - } - }, - "rule_template_name": { + "name": { "type": "string" } } }, - "v1.RuleTemplateTipResV1": { + "v1.InstanceForCreatingTask": { "type": "object", "properties": { - "db_type": { + "instance_name": { "type": "string" }, - "rule_template_name": { + "instance_schema": { "type": "string" } } }, - "v1.RuleTips": { + "v1.InstanceSchemaResV1": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "rule": { + "schema_name_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleRespV1" + "type": "string" } } } }, - "v1.RuleTypeV1": { - "type": "object", - "properties": { - "is_custom_rule_type": { - "type": "boolean" - }, - "rule_count": { - "type": "integer" - }, - "rule_type": { - "type": "string" - } - } - }, - "v1.SMTPConfigurationResV1": { + "v1.InstanceTableMeta": { "type": "object", "properties": { - "enable_smtp_notify": { - "type": "boolean" - }, - "is_skip_verify": { - "type": "boolean" + "columns": { + "type": "object", + "$ref": "#/definitions/v1.TableColumns" }, - "smtp_host": { + "create_table_sql": { "type": "string" }, - "smtp_port": { + "indexes": { + "type": "object", + "$ref": "#/definitions/v1.TableIndexes" + }, + "name": { "type": "string" }, - "smtp_username": { + "schema": { "type": "string" } } }, - "v1.SQLAuditRecord": { + "v1.InstanceTipResV1": { "type": "object", "properties": { - "created_at": { + "host": { "type": "string" }, - "creator": { + "instance_id": { "type": "string" }, - "instance": { - "type": "object", - "$ref": "#/definitions/v1.SQLAuditRecordInstance" - }, - "sql_audit_record_id": { + "instance_name": { "type": "string" }, - "sql_audit_status": { + "instance_type": { "type": "string" }, - "tags": { - "type": "array", - "items": { - "type": "string" - } + "port": { + "type": "string" }, - "task": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskResV1" + "workflow_template_id": { + "type": "integer" } } }, - "v1.SQLAuditRecordInstance": { + "v1.InstanceTypePercent": { "type": "object", "properties": { - "db_host": { - "type": "string", - "example": "10.10.10.10" + "count": { + "type": "integer" }, - "db_port": { - "type": "string", - "example": "3306" + "percent": { + "type": "number" + }, + "type": { + "type": "string" } } }, - "v1.SQLAuditRecordResData": { + "v1.InstancesTypePercentV1": { "type": "object", "properties": { - "sql_audit_record_id": { - "type": "string" + "instance_total_num": { + "type": "integer" }, - "task": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskResV1" + "instance_type_percents": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.InstanceTypePercent" + } } } }, - "v1.SQLExplain": { + "v1.LicenseItem": { "type": "object", "properties": { - "classic_result": { - "description": "explain result in table format", - "type": "object", - "$ref": "#/definitions/v1.ExplainClassicResult" - }, - "message": { + "description": { "type": "string" }, - "sql": { + "limit": { "type": "string" - } - } - }, - "v1.SQLQueryConfigReqV1": { - "type": "object", - "properties": { - "allow_query_when_less_than_audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "error" - }, - "audit_enabled": { - "type": "boolean", - "example": false - }, - "max_pre_query_rows": { - "type": "integer", - "example": 100 }, - "query_timeout_second": { - "type": "integer", - "example": 10 + "name": { + "type": "string" } } }, - "v1.SQLQueryConfigResV1": { + "v1.LicenseUsageItem": { "type": "object", "properties": { - "allow_query_when_less_than_audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ] - }, - "audit_enabled": { + "is_limited": { "type": "boolean" }, - "max_pre_query_rows": { + "limit": { "type": "integer" }, - "query_timeout_second": { + "resource_type": { + "type": "string" + }, + "resource_type_desc": { + "type": "string" + }, + "used": { "type": "integer" } } }, - "v1.Source": { + "v1.LicenseUsageV1": { "type": "object", "properties": { - "audit_plan_name": { - "type": "string" - }, - "sql_audit_record_ids": { + "instances_usage": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.LicenseUsageItem" } }, - "type": { - "type": "string", - "enum": [ - "audit_plan", - "sql_audit_record" - ] - } - } - }, - "v1.SqlAnalysis": { - "type": "object", - "properties": { - "performance_statistics": { - "type": "object", - "$ref": "#/definitions/v1.PerformanceStatistics" - }, - "sql_explain": { - "type": "object", - "$ref": "#/definitions/v1.SQLExplain" - }, - "table_metas": { + "users_usage": { "type": "object", - "$ref": "#/definitions/v1.TableMetas" + "$ref": "#/definitions/v1.LicenseUsageItem" } } }, - "v1.SqlAnalysisResDataV1": { + "v1.ListTableBySchemaResV1": { "type": "object", "properties": { - "sql_explain": { - "type": "object", - "$ref": "#/definitions/v1.SQLExplain" + "code": { + "type": "integer", + "example": 0 }, - "table_metas": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.TableMeta" + "$ref": "#/definitions/v1.Table" } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.SqlAverageExecutionTime": { + "v1.MaintenanceTimeResV1": { "type": "object", "properties": { - "average_execution_seconds": { - "type": "integer" - }, - "instance_name": { - "type": "string" - }, - "max_execution_seconds": { - "type": "integer" + "maintenance_start_time": { + "type": "object", + "$ref": "#/definitions/v1.TimeResV1" }, - "min_execution_seconds": { - "type": "integer" + "maintenance_stop_time": { + "type": "object", + "$ref": "#/definitions/v1.TimeResV1" } } }, - "v1.SqlExecutionFailPercent": { + "v1.OperationActionList": { "type": "object", "properties": { - "instance_name": { + "desc": { "type": "string" }, - "percent": { - "type": "number" + "operation_action": { + "type": "string" + }, + "operation_type": { + "type": "string" } } }, - "v1.SqlManage": { + "v1.OperationRecordList": { "type": "object", "properties": { - "appear_num": { + "id": { "type": "integer" }, - "assignees": { - "type": "array", - "items": { - "type": "string" - } - }, - "audit_result": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditResult" - } - }, - "endpoint": { + "operation_action": { "type": "string" }, - "first_appear_time": { + "operation_content": { "type": "string" }, - "id": { - "type": "integer" - }, - "instance_name": { + "operation_time": { "type": "string" }, - "last_appear_time": { + "operation_type_name": { "type": "string" }, - "remark": { - "type": "string" + "operation_user": { + "type": "object", + "$ref": "#/definitions/v1.OperationUser" }, - "schema_name": { + "project_name": { "type": "string" }, - "source": { - "type": "object", - "$ref": "#/definitions/v1.Source" + "status": { + "type": "string", + "enum": [ + "succeeded", + "failed" + ] + } + } + }, + "v1.OperationResV1": { + "type": "object", + "properties": { + "op_code": { + "type": "integer" }, - "sql": { + "op_desc": { + "type": "string" + } + } + }, + "v1.OperationTypeNameList": { + "type": "object", + "properties": { + "desc": { "type": "string" }, - "sql_fingerprint": { + "operation_type_name": { "type": "string" - }, - "status": { - "type": "string", - "enum": [ - "unhandled", - "solved", - "ignored", - "manual_audited" - ] } } }, - "v1.StatisticAuditPlanResV1": { + "v1.OperationUser": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.DBTypeAuditPlan" - } + "ip": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "user_name": { + "type": "string" } } }, - "v1.StatisticRiskWorkflowResV1": { + "v1.ParseProjectRuleTemplateFileResDataV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { + "desc": { + "type": "string" + }, + "name": { + "type": "string" + }, + "rule_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.RiskWorkflow" + "$ref": "#/definitions/v1.RuleResV1" } - }, - "message": { - "type": "string", - "example": "ok" } } }, - "v1.StatisticsAuditedSQLResV1": { + "v1.ParseProjectRuleTemplateFileResV1": { "type": "object", "properties": { "code": { @@ -15397,424 +10313,421 @@ var doc = `{ }, "data": { "type": "object", - "$ref": "#/definitions/v1.AuditedSQLCount" + "$ref": "#/definitions/v1.ParseProjectRuleTemplateFileResDataV1" }, "message": { "type": "string", "example": "ok" - }, - "risk_rate": { - "type": "integer" - } - } - }, - "v1.SyncInstanceResV1": { - "type": "object", - "properties": { - "is_sync_instance_success": { - "type": "boolean", - "example": true - }, - "sync_error_message": { - "type": "string" } } }, - "v1.SyncTaskTipsResV1": { + "v1.PartialSyncAuditPlanSQLsReqV1": { "type": "object", "properties": { - "db_types": { + "audit_plan_sql_list": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.AuditPlanSQLReqV1" } - }, - "source": { - "type": "string", - "example": "actiontech-dmp" } } }, - "v1.SystemVariablesResV1": { + "v1.PerformanceStatistics": { "type": "object", "properties": { - "operation_record_expired_hours": { - "type": "integer" - }, - "url": { - "type": "string" - }, - "workflow_expired_hours": { - "type": "integer" + "affect_rows": { + "type": "object", + "$ref": "#/definitions/v1.AffectRows" } } }, - "v1.Table": { + "v1.ProjectRuleTemplateResV1": { "type": "object", "properties": { - "name": { + "db_type": { + "type": "string" + }, + "desc": { + "type": "string" + }, + "rule_template_name": { "type": "string" } } }, - "v1.TableColumns": { + "v1.ProjectScore": { "type": "object", "properties": { - "head": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMetaItemHeadResV1" - } - }, - "rows": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } + "score": { + "type": "integer" } } }, - "v1.TableIndexes": { + "v1.RejectWorkflowReqV1": { "type": "object", "properties": { - "head": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMetaItemHeadResV1" - } - }, - "rows": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } + "reason": { + "type": "string" } } }, - "v1.TableMeta": { + "v1.RiskAuditPlan": { "type": "object", "properties": { - "columns": { - "type": "object", - "$ref": "#/definitions/v1.TableColumns" - }, - "create_table_sql": { + "audit_plan_name": { "type": "string" }, - "indexes": { - "type": "object", - "$ref": "#/definitions/v1.TableIndexes" + "audit_plan_report_id": { + "type": "integer" }, - "message": { + "audit_plan_report_timestamp": { "type": "string" }, - "name": { - "type": "string" + "risk_sql_count": { + "type": "integer" }, - "schema": { + "trigger_audit_plan_time": { "type": "string" } } }, - "v1.TableMetaItemHeadResV1": { + "v1.RiskWorkflow": { "type": "object", "properties": { - "desc": { + "create_user_name": { "type": "string" }, - "field_name": { + "update_time": { + "type": "string" + }, + "workflow_id": { + "type": "string" + }, + "workflow_name": { + "type": "string" + }, + "workflow_status": { "type": "string" } } }, - "v1.TableMetas": { + "v1.RoleUserCount": { "type": "object", "properties": { - "err_message": { - "type": "string" + "count": { + "type": "integer" }, - "table_meta_items": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMeta" - } + "role": { + "type": "string" } } }, - "v1.TestAuditPlanNotifyConfigResDataV1": { + "v1.RuleInfo": { "type": "object", "properties": { - "is_notify_send_normal": { - "type": "boolean" + "annotation": { + "type": "string", + "example": "this is test rule" }, - "send_error_message": { - "type": "string" + "desc": { + "type": "string", + "example": "this is test rule" } } }, - "v1.TestAuditPlanNotifyConfigResV1": { + "v1.RuleKnowledgeResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "knowledge_content": { + "type": "string" }, - "data": { + "rule": { "type": "object", - "$ref": "#/definitions/v1.TestAuditPlanNotifyConfigResDataV1" - }, - "message": { - "type": "string", - "example": "ok" + "$ref": "#/definitions/v1.RuleInfo" } } }, - "v1.TestDingTalkConfigResDataV1": { + "v1.RuleParamReqV1": { "type": "object", "properties": { - "is_ding_talk_send_normal": { - "type": "boolean" + "key": { + "type": "string" }, - "send_error_message": { + "value": { "type": "string" } } }, - "v1.TestDingTalkConfigResV1": { + "v1.RuleParamResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestDingTalkConfigResDataV1" + "key": { + "type": "string" }, - "message": { + "type": { "type": "string", - "example": "ok" + "enum": [ + "string", + "int", + "bool" + ] + }, + "value": { + "type": "string" } } }, - "v1.TestFeishuConfigResDataV1": { + "v1.RuleProjectTemplateDetailResV1": { "type": "object", "properties": { - "error_message": { + "db_type": { "type": "string" }, - "is_message_sent_normally": { - "type": "boolean" + "desc": { + "type": "string" + }, + "rule_list": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleResV1" + } + }, + "rule_template_name": { + "type": "string" } } }, - "v1.TestFeishuConfigResV1": { + "v1.RuleReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "is_custom_rule": { + "type": "boolean" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestFeishuConfigResDataV1" + "level": { + "type": "string", + "example": "error" }, - "message": { + "name": { "type": "string", - "example": "ok" + "example": "ddl_check_index_count" + }, + "params": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleParamReqV1" + } } } }, - "v1.TestFeishuConfigurationReqV1": { + "v1.RuleResV1": { "type": "object", "properties": { - "account": { + "annotation": { + "type": "string", + "example": "避免多次 table rebuild 带来的消耗、以及对线上业务的影响" + }, + "db_type": { + "type": "string", + "example": "mysql" + }, + "desc": { "type": "string" }, - "account_type": { + "is_custom_rule": { + "type": "boolean" + }, + "level": { "type": "string", "enum": [ - "email", - "phone" - ] - } - } - }, - "v1.TestSMTPConfigurationReqV1": { - "type": "object", - "properties": { - "recipient_addr": { + "normal", + "notice", + "warn", + "error" + ], + "example": "error" + }, + "params": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleParamResV1" + } + }, + "rule_name": { "type": "string" + }, + "type": { + "type": "string", + "example": "全局配置" } } }, - "v1.TestSMTPConfigurationResDataV1": { + "v1.RuleRespV1": { "type": "object", "properties": { - "is_smtp_send_normal": { - "type": "boolean" + "desc": { + "type": "string" }, - "send_error_message": { + "rule_name": { "type": "string" } } }, - "v1.TestSMTPConfigurationResV1": { + "v1.RuleTemplateDetailResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestSMTPConfigurationResDataV1" + "desc": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.TestWeChatConfigurationReqV1": { - "type": "object", - "properties": { - "recipient_id": { + "rule_list": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleResV1" + } + }, + "rule_template_name": { "type": "string" } } }, - "v1.TestWeChatConfigurationResDataV1": { + "v1.RuleTemplateResV1": { "type": "object", "properties": { - "is_wechat_send_normal": { - "type": "boolean" + "db_type": { + "type": "string" }, - "send_error_message": { + "desc": { + "type": "string" + }, + "rule_template_name": { "type": "string" } } }, - "v1.TestWeChatConfigurationResV1": { + "v1.RuleTemplateTipResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestWeChatConfigurationResDataV1" + "rule_template_id": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "rule_template_name": { + "type": "string" } } }, - "v1.TestWorkflowWebHookConfigResDataV1": { + "v1.RuleTips": { "type": "object", "properties": { - "send_error_message": { + "db_type": { "type": "string" + }, + "rule": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleRespV1" + } } } }, - "v1.TestWorkflowWebHookConfigResV1": { + "v1.RuleTypeV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "is_custom_rule_type": { + "type": "boolean" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestWorkflowWebHookConfigResDataV1" + "rule_count": { + "type": "integer" }, - "message": { - "type": "string", - "example": "ok" + "rule_type": { + "type": "string" } } }, - "v1.TimeReqV1": { + "v1.SQLAuditRecord": { "type": "object", "properties": { - "hour": { - "type": "integer" + "created_at": { + "type": "string" }, - "minute": { - "type": "integer" + "creator": { + "type": "string" + }, + "instance": { + "type": "object", + "$ref": "#/definitions/v1.SQLAuditRecordInstance" + }, + "sql_audit_record_id": { + "type": "string" + }, + "sql_audit_status": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "task": { + "type": "object", + "$ref": "#/definitions/v1.AuditTaskResV1" } } }, - "v1.TimeResV1": { + "v1.SQLAuditRecordInstance": { "type": "object", "properties": { - "hour": { - "type": "integer" + "db_host": { + "type": "string", + "example": "10.10.10.10" }, - "minute": { - "type": "integer" + "db_port": { + "type": "string", + "example": "3306" } } }, - "v1.TriggerAuditPlanResV1": { + "v1.SQLAuditRecordResData": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "sql_audit_record_id": { + "type": "string" }, - "data": { + "task": { "type": "object", - "$ref": "#/definitions/v1.AuditPlanReportResV1" - }, - "message": { - "type": "string", - "example": "ok" + "$ref": "#/definitions/v1.AuditTaskResV1" } } }, - "v1.TriggerSyncInstanceResV1": { + "v1.SQLExplain": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "classic_result": { + "description": "explain result in table format", "type": "object", - "$ref": "#/definitions/v1.SyncInstanceResV1" + "$ref": "#/definitions/v1.ExplainClassicResult" }, "message": { - "type": "string", - "example": "ok" + "type": "string" + }, + "sql": { + "type": "string" } } }, - "v1.UpdateAuditPlanNotifyConfigReqV1": { + "v1.SQLQueryConfigResV1": { "type": "object", "properties": { - "enable_email_notify": { - "type": "boolean" - }, - "enable_web_hook_notify": { - "type": "boolean" - }, - "notify_interval": { - "type": "integer", - "default": 10 - }, - "notify_level": { + "allow_query_when_less_than_audit_level": { "type": "string", - "default": "warn", "enum": [ "normal", "notice", @@ -15822,715 +10735,731 @@ var doc = `{ "error" ] }, - "web_hook_template": { - "type": "string" + "audit_enabled": { + "type": "boolean" }, - "web_hook_url": { - "type": "string" + "max_pre_query_rows": { + "type": "integer" + }, + "query_timeout_second": { + "type": "integer" } } }, - "v1.UpdateAuditPlanReqV1": { + "v1.Source": { "type": "object", "properties": { - "audit_plan_cron": { - "type": "string", - "example": "0 */2 * * *" - }, - "audit_plan_instance_database": { - "type": "string", - "example": "app1" - }, - "audit_plan_instance_name": { - "type": "string", - "example": "test_mysql" + "audit_plan_name": { + "type": "string" }, - "audit_plan_params": { + "sql_audit_record_ids": { "type": "array", "items": { - "$ref": "#/definitions/v1.AuditPlanParamReqV1" + "type": "string" } }, - "rule_template_name": { + "type": { "type": "string", - "example": "default_MySQL" + "enum": [ + "audit_plan", + "sql_audit_record" + ] } } }, - "v1.UpdateAuditTaskSQLsReqV1": { + "v1.SqlAnalysis": { "type": "object", "properties": { - "description": { - "type": "string" + "performance_statistics": { + "type": "object", + "$ref": "#/definitions/v1.PerformanceStatistics" + }, + "sql_explain": { + "type": "object", + "$ref": "#/definitions/v1.SQLExplain" + }, + "table_metas": { + "type": "object", + "$ref": "#/definitions/v1.TableMetas" } } }, - "v1.UpdateAuditWhitelistReqV1": { + "v1.SqlAnalysisResDataV1": { "type": "object", "properties": { - "desc": { - "type": "string", - "example": "used for rapid release" - }, - "match_type": { - "type": "string", - "enum": [ - "exact_match", - "fp_match" - ], - "example": "exact_match" + "sql_explain": { + "type": "object", + "$ref": "#/definitions/v1.SQLExplain" }, - "value": { - "type": "string", - "example": "create table" + "table_metas": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMeta" + } } } }, - "v1.UpdateCompanyNoticeReq": { + "v1.SqlAverageExecutionTime": { "type": "object", "properties": { - "notice_str": { + "average_execution_seconds": { + "type": "integer" + }, + "instance_name": { "type": "string" + }, + "max_execution_seconds": { + "type": "integer" + }, + "min_execution_seconds": { + "type": "integer" } } }, - "v1.UpdateCurrentUserPasswordReqV1": { + "v1.SqlExecutionFailPercent": { "type": "object", "properties": { - "new_password": { + "instance_name": { "type": "string" }, - "password": { - "type": "string" + "percent": { + "type": "number" } } }, - "v1.UpdateCurrentUserReqV1": { + "v1.SqlManage": { "type": "object", "properties": { - "email": { + "appear_num": { + "type": "integer" + }, + "assignees": { + "type": "array", + "items": { + "type": "string" + } + }, + "audit_result": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.AuditResult" + } + }, + "endpoint": { "type": "string" }, - "phone": { + "first_appear_time": { "type": "string" }, - "wechat_id": { - "type": "string", - "example": "UserID" - } - } - }, - "v1.UpdateCustomRuleReqV1": { - "type": "object", - "properties": { - "annotation": { - "type": "string", - "example": "this is test rule" + "id": { + "type": "integer" }, - "desc": { - "type": "string", - "example": "this is test rule" + "instance_name": { + "type": "string" }, - "level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "notice" + "last_appear_time": { + "type": "string" }, - "rule_script": { + "remark": { "type": "string" }, - "type": { - "type": "string", - "example": "DDL规则" - } - } - }, - "v1.UpdateDingTalkConfigurationReqV1": { - "type": "object", - "required": [ - "app_key", - "app_secret", - "is_enable_ding_talk_notify" - ], - "properties": { - "app_key": { + "schema_name": { "type": "string" }, - "app_secret": { + "source": { + "type": "object", + "$ref": "#/definitions/v1.Source" + }, + "sql": { "type": "string" }, - "is_enable_ding_talk_notify": { - "type": "boolean" + "sql_fingerprint": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "unhandled", + "solved", + "ignored", + "manual_audited" + ] } } }, - "v1.UpdateFeishuConfigurationReqV1": { + "v1.StatisticAuditPlanResV1": { "type": "object", - "required": [ - "app_id", - "app_secret", - "is_feishu_notification_enabled" - ], "properties": { - "app_id": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "app_secret": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.DBTypeAuditPlan" + } }, - "is_feishu_notification_enabled": { - "type": "boolean" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.UpdateInstanceReqV1": { + "v1.StatisticRiskWorkflowResV1": { "type": "object", "properties": { - "additional_params": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamReqV1" + "$ref": "#/definitions/v1.RiskWorkflow" } }, - "db_host": { - "type": "string", - "example": "10.10.10.10" - }, - "db_password": { - "type": "string", - "example": "123456" - }, - "db_port": { - "type": "string", - "example": "3306" - }, - "db_type": { + "message": { "type": "string", - "example": "mysql" + "example": "ok" + } + } + }, + "v1.StatisticsAuditedSQLResV1": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 0 }, - "db_user": { - "type": "string", - "example": "root" + "data": { + "type": "object", + "$ref": "#/definitions/v1.AuditedSQLCount" }, - "desc": { + "message": { "type": "string", - "example": "this is a test instance" + "example": "ok" }, - "maintenance_times": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MaintenanceTimeReqV1" - } + "risk_rate": { + "type": "integer" + } + } + }, + "v1.SystemVariablesResV1": { + "type": "object", + "properties": { + "operation_record_expired_hours": { + "type": "integer" }, - "rule_template_name": { + "url": { "type": "string" }, - "sql_query_config": { - "type": "object", - "$ref": "#/definitions/v1.SQLQueryConfigReqV1" + "workflow_expired_hours": { + "type": "integer" + } + } + }, + "v1.Table": { + "type": "object", + "properties": { + "name": { + "type": "string" } } }, - "v1.UpdateMemberGroupReqV1": { + "v1.TableColumns": { "type": "object", "properties": { - "roles": { + "head": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMetaItemHeadResV1" + } + }, + "rows": { "type": "array", "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" + "type": "object", + "additionalProperties": { + "type": "string" + } } } } }, - "v1.UpdateMemberReqV1": { + "v1.TableIndexes": { "type": "object", "properties": { - "is_manager": { - "type": "boolean" + "head": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMetaItemHeadResV1" + } }, - "roles": { + "rows": { "type": "array", "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" + "type": "object", + "additionalProperties": { + "type": "string" + } } } } }, - "v1.UpdateOtherUserPasswordReqV1": { + "v1.TableMeta": { "type": "object", "properties": { - "password": { + "columns": { + "type": "object", + "$ref": "#/definitions/v1.TableColumns" + }, + "create_table_sql": { + "type": "string" + }, + "indexes": { + "type": "object", + "$ref": "#/definitions/v1.TableIndexes" + }, + "message": { + "type": "string" + }, + "name": { + "type": "string" + }, + "schema": { "type": "string" } } }, - "v1.UpdateProjectReqV1": { + "v1.TableMetaItemHeadResV1": { "type": "object", "properties": { "desc": { "type": "string" + }, + "field_name": { + "type": "string" } } }, - "v1.UpdateProjectRuleTemplateReqV1": { + "v1.TableMetas": { "type": "object", "properties": { - "desc": { + "err_message": { "type": "string" }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "mysql-xxx" - ] - }, - "rule_list": { + "table_meta_items": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleReqV1" + "$ref": "#/definitions/v1.TableMeta" } } } }, - "v1.UpdateRoleReqV1": { + "v1.TestAuditPlanNotifyConfigResDataV1": { "type": "object", "properties": { - "is_disabled": { + "is_notify_send_normal": { "type": "boolean" }, - "operation_code_list": { - "type": "array", - "items": { - "type": "integer" - } - }, - "role_desc": { + "send_error_message": { "type": "string" } } }, - "v1.UpdateRuleKnowledgeReq": { + "v1.TestAuditPlanNotifyConfigResV1": { "type": "object", "properties": { - "knowledge_content": { - "type": "string" + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.TestAuditPlanNotifyConfigResDataV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.UpdateRuleTemplateReqV1": { + "v1.TestDingTalkConfigResDataV1": { "type": "object", "properties": { - "desc": { - "type": "string" + "is_ding_talk_send_normal": { + "type": "boolean" }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleReqV1" - } + "send_error_message": { + "type": "string" } } }, - "v1.UpdateSMTPConfigurationReqV1": { + "v1.TestDingTalkConfigResV1": { "type": "object", "properties": { - "enable_smtp_notify": { - "type": "boolean" - }, - "is_skip_verify": { - "type": "boolean" - }, - "smtp_host": { - "type": "string", - "example": "smtp.email.qq.com" - }, - "smtp_password": { - "type": "string", - "example": "123" + "code": { + "type": "integer", + "example": 0 }, - "smtp_port": { - "type": "string", - "example": "465" + "data": { + "type": "object", + "$ref": "#/definitions/v1.TestDingTalkConfigResDataV1" }, - "smtp_username": { + "message": { "type": "string", - "example": "test@qq.com" + "example": "ok" } } }, - "v1.UpdateSQLAuditRecordReqV1": { + "v1.TestFeishuConfigResDataV1": { "type": "object", "properties": { - "tags": { - "type": "array", - "items": { - "type": "string" - } + "error_message": { + "type": "string" + }, + "is_message_sent_normally": { + "type": "boolean" } } }, - "v1.UpdateSyncInstanceTaskReqV1": { + "v1.TestFeishuConfigResV1": { "type": "object", "properties": { - "global_rule_template": { - "type": "string", - "example": "default_mysql" - }, - "sync_instance_interval": { - "type": "string", - "example": "0 0 * * *" + "code": { + "type": "integer", + "example": 0 }, - "url": { - "type": "string", - "example": "http://10.186.62.56:10000" + "data": { + "type": "object", + "$ref": "#/definitions/v1.TestFeishuConfigResDataV1" }, - "version": { + "message": { "type": "string", - "example": "5.23.01.0" + "example": "ok" } } }, - "v1.UpdateSystemVariablesReqV1": { + "v1.TestFeishuConfigurationReqV1": { "type": "object", "properties": { - "operation_record_expired_hours": { - "type": "integer", - "example": 2160 + "account": { + "type": "string" }, - "url": { + "account_type": { "type": "string", - "example": "http://10.186.61.32:8080" - }, - "workflow_expired_hours": { - "type": "integer", - "example": 720 + "enum": [ + "email", + "phone" + ] } } }, - "v1.UpdateUserReqV1": { + "v1.TimeResV1": { "type": "object", "properties": { - "email": { - "type": "string" - }, - "is_disabled": { - "type": "boolean" - }, - "management_permission_code_list": { - "type": "array", - "items": { - "type": "integer" - } + "hour": { + "type": "integer" }, - "phone": { - "type": "string" + "minute": { + "type": "integer" + } + } + }, + "v1.TriggerAuditPlanResV1": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 0 }, - "user_group_name_list": { - "type": "array", - "items": { - "type": "string" - } + "data": { + "type": "object", + "$ref": "#/definitions/v1.AuditPlanReportResV1" }, - "wechat_id": { + "message": { "type": "string", - "example": "UserID" + "example": "ok" } } }, - "v1.UpdateWeChatConfigurationReqV1": { + "v1.UpdateAuditPlanNotifyConfigReqV1": { "type": "object", "properties": { - "agent_id": { - "type": "integer" + "enable_email_notify": { + "type": "boolean" }, - "corp_id": { - "type": "string" + "enable_web_hook_notify": { + "type": "boolean" }, - "corp_secret": { - "type": "string" + "notify_interval": { + "type": "integer", + "default": 10 }, - "enable_wechat_notify": { - "type": "boolean" + "notify_level": { + "type": "string", + "default": "warn", + "enum": [ + "normal", + "notice", + "warn", + "error" + ] }, - "proxy_ip": { + "web_hook_template": { "type": "string" }, - "safe_enabled": { - "type": "boolean" + "web_hook_url": { + "type": "string" } } }, - "v1.UpdateWorkflowReqV1": { + "v1.UpdateAuditPlanReqV1": { "type": "object", "properties": { - "task_ids": { + "audit_plan_cron": { + "type": "string", + "example": "0 */2 * * *" + }, + "audit_plan_instance_database": { + "type": "string", + "example": "app1" + }, + "audit_plan_instance_name": { + "type": "string", + "example": "test_mysql" + }, + "audit_plan_params": { "type": "array", "items": { - "type": "integer" + "$ref": "#/definitions/v1.AuditPlanParamReqV1" } + }, + "rule_template_name": { + "type": "string", + "example": "default_MySQL" } } }, - "v1.UpdateWorkflowScheduleReqV1": { + "v1.UpdateAuditTaskSQLsReqV1": { "type": "object", "properties": { - "schedule_time": { + "description": { "type": "string" } } }, - "v1.UpdateWorkflowTemplateReqV1": { + "v1.UpdateAuditWhitelistReqV1": { "type": "object", "properties": { - "allow_submit_when_less_audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ] - }, "desc": { - "type": "string" + "type": "string", + "example": "used for rapid release" }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - } + "match_type": { + "type": "string", + "enum": [ + "exact_match", + "fp_match" + ], + "example": "exact_match" }, - "workflow_step_template_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.WorkFlowStepTemplateReqV1" - } + "value": { + "type": "string", + "example": "create table" } } }, - "v1.UploadLogoResDataV1": { + "v1.UpdateCompanyNoticeReq": { "type": "object", "properties": { - "logo_url": { + "notice_str": { "type": "string" } } }, - "v1.UploadLogoResV1": { + "v1.UpdateCustomRuleReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "annotation": { + "type": "string", + "example": "this is test rule" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.UploadLogoResDataV1" + "desc": { + "type": "string", + "example": "this is test rule" }, - "message": { + "level": { "type": "string", - "example": "ok" + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "example": "notice" + }, + "rule_script": { + "type": "string" + }, + "type": { + "type": "string", + "example": "DDL规则" } } }, - "v1.UserBindProjectResV1": { + "v1.UpdateDingTalkConfigurationReqV1": { "type": "object", + "required": [ + "app_key", + "app_secret", + "is_enable_ding_talk_notify" + ], "properties": { - "is_manager": { - "type": "boolean" + "app_key": { + "type": "string" }, - "project_name": { + "app_secret": { "type": "string" + }, + "is_enable_ding_talk_notify": { + "type": "boolean" } } }, - "v1.UserDetailResV1": { + "v1.UpdateFeishuConfigurationReqV1": { "type": "object", + "required": [ + "app_id", + "app_secret", + "is_feishu_notification_enabled" + ], "properties": { - "bind_projects": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.UserBindProjectResV1" - } - }, - "email": { + "app_id": { "type": "string" }, - "is_admin": { - "type": "boolean" - }, - "is_disabled": { - "type": "boolean" - }, - "login_type": { + "app_secret": { "type": "string" }, - "management_permission_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ManagementPermissionResV1" - } - }, - "phone": { + "is_feishu_notification_enabled": { + "type": "boolean" + } + } + }, + "v1.UpdateProjectRuleTemplateReqV1": { + "type": "object", + "properties": { + "desc": { "type": "string" }, - "user_group_name_list": { + "rule_list": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.RuleReqV1" } - }, - "user_name": { - "type": "string" - }, - "wechat_id": { - "type": "string" } } }, - "v1.UserGroupListItemResV1": { + "v1.UpdateRuleKnowledgeReq": { "type": "object", "properties": { - "is_disabled": { - "type": "boolean" - }, - "user_group_desc": { - "type": "string" - }, - "user_group_name": { + "knowledge_content": { "type": "string" - }, - "user_name_list": { - "type": "array", - "items": { - "type": "string" - } } } }, - "v1.UserGroupTipListItem": { + "v1.UpdateRuleTemplateReqV1": { "type": "object", "properties": { - "user_group_name": { + "desc": { "type": "string" }, - "user_names": { + "rule_list": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.RuleReqV1" } } } }, - "v1.UserLoginReqV1": { + "v1.UpdateSQLAuditRecordReqV1": { "type": "object", "properties": { - "password": { - "type": "string", - "example": "123456" - }, - "username": { - "type": "string", - "example": "test" + "tags": { + "type": "array", + "items": { + "type": "string" + } } } }, - "v1.UserLoginResV1": { + "v1.UpdateSystemVariablesReqV1": { "type": "object", "properties": { - "token": { + "operation_record_expired_hours": { + "type": "integer", + "example": 2160 + }, + "url": { "type": "string", - "example": "this is a jwt token string" + "example": "http://10.186.61.32:8080" + }, + "workflow_expired_hours": { + "type": "integer", + "example": 720 } } }, - "v1.UserResV1": { + "v1.UpdateWorkflowReqV1": { "type": "object", "properties": { - "email": { - "type": "string" - }, - "is_disabled": { - "type": "boolean" - }, - "login_type": { - "type": "string" - }, - "management_permission_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ManagementPermissionResV1" - } - }, - "phone": { - "type": "string" - }, - "user_group_name_list": { + "task_ids": { "type": "array", "items": { - "type": "string" + "type": "integer" } - }, - "user_name": { - "type": "string" - }, - "wechat_id": { - "type": "string" } } }, - "v1.UserTipResV1": { + "v1.UpdateWorkflowScheduleReqV1": { "type": "object", "properties": { - "user_name": { + "schedule_time": { "type": "string" } } }, - "v1.WeChatConfigurationResV1": { + "v1.UpdateWorkflowTemplateReqV1": { "type": "object", "properties": { - "agent_id": { - "type": "integer" - }, - "corp_id": { - "type": "string" - }, - "enable_wechat_notify": { - "type": "boolean" + "allow_submit_when_less_audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error" + ] }, - "proxy_ip": { + "desc": { "type": "string" }, - "safe_enabled": { - "type": "boolean" + "workflow_step_template_list": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.WorkFlowStepTemplateReqV1" + } } } }, - "v1.WebHookConfigV1": { + "v1.UserTipResV1": { "type": "object", "properties": { - "enable": { - "type": "boolean" - }, - "max_retry_times": { - "type": "integer" - }, - "retry_interval_seconds": { - "type": "integer" - }, - "token": { + "user_id": { "type": "string" }, - "url": { + "user_name": { "type": "string" } } @@ -16541,7 +11470,7 @@ var doc = `{ "approved_by_authorized": { "type": "boolean" }, - "assignee_user_name_list": { + "assignee_user_id_list": { "type": "array", "items": { "type": "string" @@ -16568,7 +11497,7 @@ var doc = `{ "approved_by_authorized": { "type": "boolean" }, - "assignee_user_name_list": { + "assignee_user_id_list": { "type": "array", "items": { "type": "string" @@ -16937,11 +11866,8 @@ var doc = `{ "desc": { "type": "string" }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - } + "update_time": { + "type": "string" }, "workflow_step_template_list": { "type": "array", @@ -17166,6 +12092,9 @@ var doc = `{ }, "rollback_sql": { "type": "string" + }, + "sql_source_file": { + "type": "string" } } }, @@ -17191,58 +12120,6 @@ var doc = `{ } } }, - "v2.CreateInstanceReqV2": { - "type": "object", - "properties": { - "additional_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamReqV1" - } - }, - "db_host": { - "type": "string", - "example": "10.10.10.10" - }, - "db_password": { - "type": "string", - "example": "123456" - }, - "db_port": { - "type": "string", - "example": "3306" - }, - "db_type": { - "type": "string", - "example": "mysql" - }, - "db_user": { - "type": "string", - "example": "root" - }, - "desc": { - "type": "string", - "example": "this is a test instance" - }, - "instance_name": { - "type": "string", - "example": "test" - }, - "maintenance_times": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MaintenanceTimeReqV1" - } - }, - "rule_template_name": { - "type": "string" - }, - "sql_query_config": { - "type": "object", - "$ref": "#/definitions/v1.SQLQueryConfigReqV1" - } - } - }, "v2.CreateWorkflowReqV2": { "type": "object", "properties": { @@ -17509,28 +12386,6 @@ var doc = `{ } } }, - "v2.GetInstancesResV2": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v2.InstanceResV2" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, "v2.GetSqlManageListResp": { "type": "object", "properties": { diff --git a/sqle/docs/swagger.json b/sqle/docs/swagger.json index f0be473df1..8faa815a76 100644 --- a/sqle/docs/swagger.json +++ b/sqle/docs/swagger.json @@ -97,24 +97,6 @@ } } }, - "/v1/basic_info": { - "get": { - "description": "get sqle basic info", - "tags": [ - "global" - ], - "summary": "获取 sqle 基本信息", - "operationId": "getSQLEInfoV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetSQLEInfoResV1" - } - } - } - } - }, "/v1/company_notice": { "get": { "security": [ @@ -283,101 +265,6 @@ } } }, - "/v1/configurations/feishu": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get feishu configuration", - "tags": [ - "configuration" - ], - "summary": "获取飞书配置", - "operationId": "getFeishuConfigurationV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetFeishuConfigurationResV1" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update feishu configuration", - "consumes": [ - "application/json" - ], - "tags": [ - "configuration" - ], - "summary": "添加或更新飞书配置", - "operationId": "updateFeishuConfigurationV1", - "parameters": [ - { - "description": "update feishu configuration req", - "name": "param", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateFeishuConfigurationReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/configurations/feishu/test": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "test feishu configuration", - "consumes": [ - "application/json" - ], - "tags": [ - "configuration" - ], - "summary": "测试飞书配置", - "operationId": "testFeishuConfigV1", - "parameters": [ - { - "description": "test feishu configuration req", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.TestFeishuConfigurationReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.TestFeishuConfigResV1" - } - } - } - } - }, "/v1/configurations/feishu_audit": { "get": { "security": [ @@ -473,64 +360,6 @@ } } }, - "/v1/configurations/ldap": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get LDAP configuration", - "tags": [ - "configuration" - ], - "summary": "获取 LDAP 配置", - "operationId": "getLDAPConfigurationV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetLDAPConfigurationResV1" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update LDAP configuration", - "consumes": [ - "application/json" - ], - "tags": [ - "configuration" - ], - "summary": "添加 LDAP 配置", - "operationId": "updateLDAPConfigurationV1", - "parameters": [ - { - "description": "update LDAP configuration req", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.LDAPConfigurationReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, "/v1/configurations/license": { "get": { "security": [ @@ -645,24 +474,24 @@ } } }, - "/v1/configurations/oauth2": { + "/v1/configurations/system_variables": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get Oauth2 configuration", + "description": "get system variables", "tags": [ "configuration" ], - "summary": "获取 Oauth2 配置", - "operationId": "getOauth2ConfigurationV1", + "summary": "获取系统变量", + "operationId": "getSystemVariablesV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetOauth2ConfigurationResV1" + "$ref": "#/definitions/v1.GetSystemVariablesResV1" } } } @@ -673,23 +502,23 @@ "ApiKeyAuth": [] } ], - "description": "update Oauth2 configuration", + "description": "update system variables", "consumes": [ "application/json" ], "tags": [ "configuration" ], - "summary": "修改 Oauth2 配置", - "operationId": "updateOauth2ConfigurationV1", + "summary": "修改系统变量", + "operationId": "updateSystemVariablesV1", "parameters": [ { - "description": "update Oauth2 configuration req", - "name": "conf", + "description": "update system variables request", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.Oauth2ConfigurationReqV1" + "$ref": "#/definitions/v1.UpdateSystemVariablesReqV1" } } ], @@ -703,45 +532,62 @@ } } }, - "/v1/configurations/oauth2/tips": { + "/v1/custom_rules": { "get": { - "description": "get Oauth2 tips", + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "get all custom rule template", "tags": [ - "configuration" + "rule_template" + ], + "summary": "自定义规则列表", + "operationId": "getCustomRulesV1", + "parameters": [ + { + "type": "string", + "description": "filter db type", + "name": "filter_db_type", + "in": "query" + }, + { + "type": "string", + "description": "filter desc", + "name": "filter_desc", + "in": "query" + } ], - "summary": "获取 Oauth2 基本信息", - "operationId": "getOauth2Tips", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetOauth2TipsResV1" + "$ref": "#/definitions/v1.GetCustomRulesResV1" } } } - } - }, - "/v1/configurations/personalise": { - "patch": { + }, + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update personalise config", + "description": "create custom rule", "tags": [ - "configuration" + "rule_template" ], - "summary": "更新个性化设置", - "operationId": "personalise", + "summary": "添加自定义规则", + "operationId": "createCustomRuleV1", "parameters": [ { - "description": "personalise req", - "name": "conf", + "description": "add custom rule", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.PersonaliseReqV1" + "$ref": "#/definitions/v1.CreateCustomRuleReqV1" } } ], @@ -755,28 +601,25 @@ } } }, - "/v1/configurations/personalise/logo": { - "post": { + "/v1/custom_rules/{db_type}/rule_types": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "upload logo", - "consumes": [ - "multipart/form-data" - ], + "description": "get rule type by db type", "tags": [ - "configuration" + "rule_template" ], - "summary": "上传Logo", - "operationId": "uploadLogo", + "summary": "获取规则分类", + "operationId": "getRuleTypeByDBTypeV1", "parameters": [ { - "type": "file", - "description": "logo file", - "name": "logo", - "in": "formData", + "type": "string", + "description": "db type", + "name": "db_type", + "in": "query", "required": true } ], @@ -784,58 +627,62 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.UploadLogoResV1" + "$ref": "#/definitions/v1.GetRuleTypeByDBTypeResV1" } } } } }, - "/v1/configurations/smtp": { + "/v1/custom_rules/{rule_id}": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get SMTP configuration", + "description": "get custom rule by rule_id", "tags": [ - "configuration" + "rule_template" + ], + "summary": "获取自定义规则", + "operationId": "getCustomRuleV1", + "parameters": [ + { + "type": "string", + "description": "rule id", + "name": "rule_id", + "in": "path", + "required": true + } ], - "summary": "获取 SMTP 配置", - "operationId": "getSMTPConfigurationV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSMTPConfigurationResV1" + "$ref": "#/definitions/v1.GetCustomRuleResV1" } } } }, - "patch": { + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update SMTP configuration", - "consumes": [ - "application/json" - ], + "description": "delete custom rule", "tags": [ - "configuration" + "rule_template" ], - "summary": "添加 SMTP 配置", - "operationId": "updateSMTPConfigurationV1", + "summary": "删除自定义规则", + "operationId": "deleteCustomRuleV1", "parameters": [ { - "description": "update SMTP configuration req", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateSMTPConfigurationReqV1" - } + "type": "string", + "description": "rule id", + "name": "rule_id", + "in": "path", + "required": true } ], "responses": { @@ -846,32 +693,34 @@ } } } - } - }, - "/v1/configurations/smtp/test": { - "post": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test SMTP configuration", - "consumes": [ - "application/json" - ], + "description": "update custom rule", "tags": [ - "configuration" + "rule_template" ], - "summary": "测试 邮箱 配置", - "operationId": "testSMTPConfigurationV1", + "summary": "更新自定义规则", + "operationId": "updateCustomRuleV1", "parameters": [ { - "description": "test SMTP configuration req", - "name": "req", + "type": "string", + "description": "rule id", + "name": "rule_id", + "in": "path", + "required": true + }, + { + "description": "update custom rule", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.TestSMTPConfigurationReqV1" + "$ref": "#/definitions/v1.UpdateCustomRuleReqV1" } } ], @@ -879,216 +728,350 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TestSMTPConfigurationResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/configurations/sql_query": { + "/v1/dashboard": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sqle query configuration", + "description": "get dashboard info", + "produces": [ + "application/json" + ], "tags": [ - "configuration" + "dashboard" + ], + "summary": "获取 dashboard 信息", + "operationId": "getDashboardV1", + "parameters": [ + { + "type": "string", + "description": "filter project name", + "name": "filter_project_name", + "in": "query" + } ], - "summary": "获取SQL查询配置信息", - "operationId": "getSQLQueryConfiguration", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSQLQueryConfigurationResV1" + "$ref": "#/definitions/v1.GetDashboardResV1" } } } } }, - "/v1/configurations/system_variables": { + "/v1/operation_records": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get system variables", + "description": "Get operation record list", "tags": [ - "configuration" + "OperationRecord" + ], + "summary": "获取操作记录列表", + "operationId": "getOperationRecordListV1", + "parameters": [ + { + "type": "string", + "description": "filter_operate_time_from", + "name": "filter_operate_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_time_to", + "name": "filter_operate_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_project_name", + "name": "filter_operate_project_name", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy_search_operate_user_name", + "name": "fuzzy_search_operate_user_name", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_type_name", + "name": "filter_operate_type_name", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_action", + "name": "filter_operate_action", + "in": "query" + }, + { + "type": "integer", + "description": "page_index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "page_size", + "name": "page_size", + "in": "query", + "required": true + } ], - "summary": "获取系统变量", - "operationId": "getSystemVariablesV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSystemVariablesResV1" + "$ref": "#/definitions/v1.GetOperationRecordListResV1" } } } - }, - "patch": { + } + }, + "/v1/operation_records/exports": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update system variables", - "consumes": [ - "application/json" - ], + "description": "Export operation record list", "tags": [ - "configuration" + "OperationRecord" ], - "summary": "修改系统变量", - "operationId": "updateSystemVariablesV1", + "summary": "导出操作记录列表", + "operationId": "getExportOperationRecordListV1", "parameters": [ { - "description": "update system variables request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateSystemVariablesReqV1" - } + "type": "string", + "description": "filter_operate_time_from", + "name": "filter_operate_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_time_to", + "name": "filter_operate_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_project_name", + "name": "filter_operate_project_name", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy_search_operate_user_name", + "name": "fuzzy_search_operate_user_name", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_type_name", + "name": "filter_operate_type_name", + "in": "query" + }, + { + "type": "string", + "description": "filter_operate_action", + "name": "filter_operate_action", + "in": "query" } ], "responses": { "200": { - "description": "OK", + "description": "get export operation record list", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/configurations/webhook": { + "/v1/operation_records/operation_actions": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow webhook config", + "description": "Get operation action list", "tags": [ - "configuration" + "OperationRecord" ], - "summary": "获取全局工单 WebHook 配置", - "operationId": "getGlobalWorkflowWebHookConfig", + "summary": "获取操作内容列表", + "operationId": "getOperationActionList", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowWebHookConfigResV1" + "$ref": "#/definitions/v1.GetOperationActionListResV1" } } } - }, - "patch": { + } + }, + "/v1/operation_records/operation_type_names": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update webhook config", + "description": "Get operation type name list", "tags": [ - "configuration" - ], - "summary": "更新工单 WebHook 配置", - "operationId": "updateGlobalWebHookConfig", - "parameters": [ - { - "description": "update webhook config", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.WebHookConfigV1" - } - } + "OperationRecord" ], + "summary": "获取操作类型名列表", + "operationId": "GetOperationTypeNameList", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetOperationTypeNamesListResV1" } } } } }, - "/v1/configurations/webhook/test": { - "post": { + "/v1/operations": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test workflow webhook config", + "description": "get permission operations", "tags": [ - "configuration" + "operation" ], - "summary": "测试全局工单 WebHook 配置", - "operationId": "testGlobalWorkflowWebHookConfig", + "summary": "获取权限动作列表", + "operationId": "GetOperationsV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TestWorkflowWebHookConfigResV1" + "$ref": "#/definitions/v1.GetOperationsResV1" } } } } }, - "/v1/configurations/wechat": { + "/v1/projects/{project_name}/audit_plans": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get WeChat configuration", + "description": "get audit plan info list", "tags": [ - "configuration" + "audit_plan" + ], + "summary": "获取扫描任务信息列表", + "operationId": "getAuditPlansV1", + "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "filter audit plan db type", + "name": "filter_audit_plan_db_type", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search audit plan name", + "name": "fuzzy_search_audit_plan_name", + "in": "query" + }, + { + "type": "string", + "description": "filter audit plan type", + "name": "filter_audit_plan_type", + "in": "query" + }, + { + "type": "string", + "description": "filter audit plan instance name", + "name": "filter_audit_plan_instance_name", + "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true + } ], - "summary": "获取 企业微信 配置", - "operationId": "getWeChatConfigurationV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWeChatConfigurationResV1" + "$ref": "#/definitions/v1.GetAuditPlansResV1" } } } }, - "patch": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update WeChat configuration", + "description": "create audit plan", "consumes": [ "application/json" ], "tags": [ - "configuration" + "audit_plan" ], - "summary": "添加 企业微信 配置", - "operationId": "updateWeChatConfigurationV1", + "summary": "添加扫描任务", + "operationId": "createAuditPlanV1", "parameters": [ { - "description": "update WeChat configuration req", - "name": "instance", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "description": "create audit plan", + "name": "audit_plan", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateWeChatConfigurationReqV1" + "$ref": "#/definitions/v1.CreateAuditPlanReqV1" } } ], @@ -1102,99 +1085,115 @@ } } }, - "/v1/configurations/wechat/test": { - "post": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test WeChat configuration", - "consumes": [ - "application/json" - ], + "description": "get audit plan", "tags": [ - "configuration" + "audit_plan" ], - "summary": "测试 企业微信 配置", - "operationId": "testWeChatConfigurationV1", + "summary": "获取指定扫描任务", + "operationId": "getAuditPlanV1", "parameters": [ { - "description": "test WeChat configuration req", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.TestWeChatConfigurationReqV1" - } + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TestWeChatConfigurationResV1" + "$ref": "#/definitions/v1.GetAuditPlanResV1" } } } - } - }, - "/v1/custom_rules": { - "get": { + }, + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get all custom rule template", + "description": "delete audit plan", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "自定义规则列表", - "operationId": "getCustomRulesV1", + "summary": "删除扫描任务", + "operationId": "deleteAuditPlanV1", "parameters": [ { "type": "string", - "description": "filter db type", - "name": "filter_db_type", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { "type": "string", - "description": "filter desc", - "name": "filter_desc", - "in": "query" + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetCustomRulesResV1" + "$ref": "#/definitions/controller.BaseRes" } } } }, - "post": { + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create custom rule", + "description": "update audit plan", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "添加自定义规则", - "operationId": "createCustomRuleV1", + "summary": "更新扫描任务", + "operationId": "updateAuditPlanV1", "parameters": [ { - "description": "add custom rule", - "name": "instance", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "description": "update audit plan", + "name": "audit_plan", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateCustomRuleReqV1" + "$ref": "#/definitions/v1.UpdateAuditPlanReqV1" } } ], @@ -1208,25 +1207,32 @@ } } }, - "/v1/custom_rules/{db_type}/rule_types": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get rule type by db type", + "description": "get audit plan notify config", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "获取规则分类", - "operationId": "getRuleTypeByDBTypeV1", + "summary": "获取扫描任务消息推送设置", + "operationId": "getAuditPlanNotifyConfigV1", "parameters": [ { "type": "string", - "description": "db type", - "name": "db_type", - "in": "query", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", "required": true } ], @@ -1234,60 +1240,83 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleTypeByDBTypeResV1" + "$ref": "#/definitions/v1.GetAuditPlanNotifyConfigResV1" } } } - } - }, - "/v1/custom_rules/{rule_id}": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get custom rule by rule_id", + "description": "update audit plan notify config", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "获取自定义规则", - "operationId": "getCustomRuleV1", + "summary": "更新扫描任务通知设置", + "operationId": "updateAuditPlanNotifyConfigV1", "parameters": [ { "type": "string", - "description": "rule id", - "name": "rule_id", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", "in": "path", "required": true + }, + { + "description": "update audit plan notify config", + "name": "config", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateAuditPlanNotifyConfigReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetCustomRuleResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - }, - "delete": { + } + }, + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config/test": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete custom rule", + "description": "Test audit task message push", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "删除自定义规则", - "operationId": "deleteCustomRuleV1", + "summary": "测试扫描任务消息推送", + "operationId": "testAuditPlanNotifyConfigV1", "parameters": [ { "type": "string", - "description": "rule id", - "name": "rule_id", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", "in": "path", "required": true } @@ -1296,267 +1325,359 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.TestAuditPlanNotifyConfigResV1" } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update custom rule", + "description": "get audit plan report list", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "更新自定义规则", - "operationId": "updateCustomRuleV1", + "summary": "获取指定扫描任务的报告列表", + "operationId": "getAuditPlanReportsV1", "parameters": [ { "type": "string", - "description": "rule id", - "name": "rule_id", + "description": "project name", + "name": "project_name", "in": "path", "required": true }, { - "description": "update custom rule", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateCustomRuleReqV1" - } + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetAuditPlanReportsResV1" } } } } }, - "/v1/dashboard": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get dashboard info", - "produces": [ - "application/json" - ], + "description": "get audit plan report", "tags": [ - "dashboard" + "audit_plan" ], - "summary": "获取 dashboard 信息", - "operationId": "getDashboardV1", + "summary": "获取指定扫描任务的SQL扫描记录统计信息", + "operationId": "getAuditPlanReportV1", "parameters": [ { "type": "string", - "description": "filter project name", - "name": "filter_project_name", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetDashboardResV1" - } - } - } - } - }, - "/v1/dashboard/project_tips": { - "get": { - "security": [ + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, { - "ApiKeyAuth": [] + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true } ], - "description": "get dashboard project tips", - "produces": [ - "application/json" - ], - "tags": [ - "dashboard" - ], - "summary": "获取dashboard项目提示列表", - "operationId": "getDashboardProjectTipsV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetDashboardProjectTipsResV1" + "$ref": "#/definitions/v1.GetAuditPlanReportResV1" } } } } }, - "/v1/instance_additional_metas": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/export": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance additional metas", + "description": "export audit plan report as csv", "tags": [ - "instance" + "audit_plan" + ], + "summary": "以csv的形式导出扫描报告", + "operationId": "exportAuditPlanReportV1", + "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + } ], - "summary": "获取实例的额外属性列表", - "operationId": "getInstanceAdditionalMetas", "responses": { "200": { - "description": "OK", + "description": "get export audit plan report", "schema": { - "$ref": "#/definitions/v1.GetInstanceAdditionalMetasResV1" + "type": "file" } } } } }, - "/v1/instance_connection": { - "post": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test instance db connection 注:可直接提交创建实例接口的body,该接口的json 内容是创建实例的 json 的子集", - "consumes": [ - "application/json" - ], + "description": "get audit plan report SQLs", "tags": [ - "instance" + "audit_plan" ], - "summary": "实例连通性测试(实例提交前)", - "operationId": "checkInstanceIsConnectableV1", + "summary": "获取指定扫描任务的SQL扫描详情", + "operationId": "getAuditPlanReportsSQLsV1", "parameters": [ { - "description": "instance info", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.GetInstanceConnectableReqV1" - } + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstanceConnectableResV1" + "$ref": "#/definitions/v1.GetAuditPlanReportSQLsResV1" } } } } }, - "/v1/login": { - "post": { - "description": "user login", + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "get SQL explain and related table metadata for analysis", "tags": [ - "user" + "audit_plan" ], - "summary": "用户登录", - "operationId": "loginV1", + "summary": "获取task相关的SQL执行计划和表元数据", + "operationId": "getTaskAnalysisData", "parameters": [ { - "description": "user login request", - "name": "user", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UserLoginReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserLoginResV1" - } + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "sql number", + "name": "number", + "in": "path", + "required": true } - } - } - }, - "/v1/logout": { - "post": { - "description": "user logout", - "tags": [ - "user" ], - "summary": "用户登出", - "operationId": "logoutV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetAuditPlanAnalysisDataResV1" } } } } }, - "/v1/management_permissions": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get platform management permissions", + "description": "get audit plan SQLs", "tags": [ - "management_permission" + "audit_plan" + ], + "summary": "获取指定扫描任务的SQLs信息(不包括扫描结果)", + "operationId": "getAuditPlanSQLsV1", + "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true + } ], - "summary": "获取平台管理权限列表", - "operationId": "GetManagementPermissionsV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetManagementPermissionsResV1" + "$ref": "#/definitions/v1.GetAuditPlanSQLsResV1" } } } } }, - "/v1/oauth2/link": { - "get": { - "description": "oauth2 link", - "tags": [ - "oauth2" - ], - "summary": "oauth2通过此链接跳转到第三方登录网址", - "operationId": "Oauth2Link" - } - }, - "/v1/oauth2/user/bind": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full": { "post": { - "description": "bind Oauth2 user to sqle", + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "full sync audit plan SQLs", "tags": [ - "oauth2" + "audit_plan" ], - "summary": "绑定 Oauth2 和 sqle用户", - "operationId": "bindOauth2User", + "summary": "全量同步SQL到扫描任务", + "operationId": "fullSyncAuditPlanSQLsV1", + "deprecated": true, "parameters": [ { - "description": "bind oauth2 user req", - "name": "conf", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "description": "full sync audit plan SQLs request", + "name": "sqls", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.BindOauth2UserReqV1" + "$ref": "#/definitions/v1.FullSyncAuditPlanSQLsReqV1" } } ], @@ -1564,276 +1685,131 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.BindOauth2UserResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/operation_records": { - "get": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Get operation record list", + "description": "partial sync audit plan SQLs", "tags": [ - "OperationRecord" + "audit_plan" ], - "summary": "获取操作记录列表", - "operationId": "getOperationRecordListV1", + "summary": "增量同步SQL到扫描任务", + "operationId": "partialSyncAuditPlanSQLsV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "filter_operate_time_from", - "name": "filter_operate_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_time_to", - "name": "filter_operate_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_project_name", - "name": "filter_operate_project_name", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy_search_operate_user_name", - "name": "fuzzy_search_operate_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_type_name", - "name": "filter_operate_type_name", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { "type": "string", - "description": "filter_operate_action", - "name": "filter_operate_action", - "in": "query" - }, - { - "type": "integer", - "description": "page_index", - "name": "page_index", - "in": "query", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", "required": true }, { - "type": "integer", - "description": "page_size", - "name": "page_size", - "in": "query", - "required": true + "description": "partial sync audit plan SQLs request", + "name": "sqls", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.PartialSyncAuditPlanSQLsReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetOperationRecordListResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/operation_records/exports": { - "get": { + "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/trigger": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Export operation record list", + "description": "trigger audit plan", "tags": [ - "OperationRecord" + "audit_plan" ], - "summary": "导出操作记录列表", - "operationId": "getExportOperationRecordListV1", + "summary": "触发扫描任务", + "operationId": "triggerAuditPlanV1", "parameters": [ { "type": "string", - "description": "filter_operate_time_from", - "name": "filter_operate_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_time_to", - "name": "filter_operate_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_project_name", - "name": "filter_operate_project_name", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy_search_operate_user_name", - "name": "fuzzy_search_operate_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter_operate_type_name", - "name": "filter_operate_type_name", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { "type": "string", - "description": "filter_operate_action", - "name": "filter_operate_action", - "in": "query" - } - ], - "responses": { - "200": { - "description": "get export operation record list", - "schema": { - "type": "file" - } - } - } - } - }, - "/v1/operation_records/operation_actions": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "Get operation action list", - "tags": [ - "OperationRecord" - ], - "summary": "获取操作内容列表", - "operationId": "getOperationActionList", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetOperationActionListResV1" - } - } - } - } - }, - "/v1/operation_records/operation_type_names": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "Get operation type name list", - "tags": [ - "OperationRecord" - ], - "summary": "获取操作类型名列表", - "operationId": "GetOperationTypeNameList", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetOperationTypeNamesListResV1" - } - } - } - } - }, - "/v1/operations": { - "get": { - "security": [ - { - "ApiKeyAuth": [] + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true } ], - "description": "get permission operations", - "tags": [ - "operation" - ], - "summary": "获取权限动作列表", - "operationId": "GetOperationsV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetOperationsResV1" + "$ref": "#/definitions/v1.TriggerAuditPlanResV1" } } } } }, - "/v1/project_tips": { + "/v1/projects/{project_name}/audit_whitelist": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get project tip list", + "description": "get all whitelist", "tags": [ - "project" + "audit_whitelist" ], - "summary": "获取项目提示列表", - "operationId": "getProjectTipsV1", + "summary": "获取Sql审核白名单", + "operationId": "getAuditWhitelistV1", "parameters": [ { - "enum": [ - "operation_record" - ], "type": "string", - "description": "functional module", - "name": "functional_module", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetProjectTipsResV1" - } - } - } - } - }, - "/v1/projects": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get project list", - "tags": [ - "project" - ], - "summary": "获取项目列表", - "operationId": "getProjectListV1", - "parameters": [ + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, { - "type": "integer", + "type": "string", "description": "page index", "name": "page_index", "in": "query", "required": true }, { - "type": "integer", - "default": 50, - "description": "size of per page", + "type": "string", + "description": "page size", "name": "page_size", "in": "query", "required": true @@ -1843,7 +1819,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectResV1" + "$ref": "#/definitions/v1.GetAuditWhitelistResV1" } } } @@ -1854,26 +1830,30 @@ "ApiKeyAuth": [] } ], - "description": "create project", + "description": "create a sql whitelist", "consumes": [ "application/json" ], - "produces": [ - "application/json" - ], "tags": [ - "project" + "audit_whitelist" ], - "summary": "创建项目", - "operationId": "createProjectV1", + "summary": "添加SQL白名单", + "operationId": "createAuditWhitelistV1", "parameters": [ { - "description": "create project request", - "name": "project", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "description": "add sql whitelist req", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateProjectReqV1" + "$ref": "#/definitions/v1.CreateAuditWhitelistReqV1" } } ], @@ -1887,19 +1867,19 @@ } } }, - "/v1/projects/{project_name}/": { - "get": { + "/v1/projects/{project_name}/audit_whitelist/{audit_whitelist_id}/": { + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get project detail", + "description": "remove sql white", "tags": [ - "project" + "audit_whitelist" ], - "summary": "获取项目详情", - "operationId": "getProjectDetailV1", + "summary": "删除SQL白名单信息", + "operationId": "deleteAuditWhitelistByIdV1", "parameters": [ { "type": "string", @@ -1907,43 +1887,20 @@ "name": "project_name", "in": "path", "required": true + }, + { + "type": "string", + "description": "audit whitelist id", + "name": "audit_whitelist_id", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectDetailResV1" - } - } - } - }, - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete project", - "tags": [ - "project" - ], - "summary": "删除项目", - "operationId": "deleteProjectV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/controller.BaseRes" } } } @@ -1954,18 +1911,15 @@ "ApiKeyAuth": [] } ], - "description": "update project", + "description": "update sql whitelist by id", "consumes": [ "application/json" ], - "produces": [ - "application/json" - ], "tags": [ - "project" + "audit_whitelist" ], - "summary": "更新项目", - "operationId": "updateProjectV1", + "summary": "更新SQL白名单", + "operationId": "UpdateAuditWhitelistByIdV1", "parameters": [ { "type": "string", @@ -1975,52 +1929,21 @@ "required": true }, { - "description": "create project request", - "name": "project", + "type": "string", + "description": "sql audit whitelist id", + "name": "audit_whitelist_id", + "in": "path", + "required": true + }, + { + "description": "update sql whitelist req", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateProjectReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.UpdateAuditWhitelistReqV1" } } - } - } - }, - "/v1/projects/{project_name}/archive": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "archive project", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "project" - ], - "summary": "归档项目", - "operationId": "archiveProjectV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } ], "responses": { "200": { @@ -2032,19 +1955,19 @@ } } }, - "/v1/projects/{project_name}/audit_plans": { + "/v1/projects/{project_name}/instance_tips": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan info list", + "description": "get instance tip list", "tags": [ - "audit_plan" + "instance" ], - "summary": "获取扫描任务信息列表", - "operationId": "getAuditPlansV1", + "summary": "获取实例提示列表", + "operationId": "getInstanceTipListV1", "parameters": [ { "type": "string", @@ -2055,67 +1978,51 @@ }, { "type": "string", - "description": "filter audit plan db type", - "name": "filter_audit_plan_db_type", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search audit plan name", - "name": "fuzzy_search_audit_plan_name", + "description": "filter db type", + "name": "filter_db_type", "in": "query" }, { "type": "string", - "description": "filter audit plan type", - "name": "filter_audit_plan_type", + "description": "filter workflow template id", + "name": "filter_workflow_template_id", "in": "query" }, { + "enum": [ + "create_audit_plan", + "create_workflow", + "sql_manage" + ], "type": "string", - "description": "filter audit plan instance name", - "name": "filter_audit_plan_instance_name", + "description": "functional module", + "name": "functional_module", "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlansResV1" + "$ref": "#/definitions/v1.GetInstanceTipsResV1" } } } - }, + } + }, + "/v1/projects/{project_name}/instances/connections": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create audit plan", - "consumes": [ - "application/json" - ], + "description": "batch test instance db connections", "tags": [ - "audit_plan" + "instance" ], - "summary": "添加扫描任务", - "operationId": "createAuditPlanV1", + "summary": "批量测试实例连通性(实例提交后)", + "operationId": "batchCheckInstanceIsConnectableByName", "parameters": [ { "type": "string", @@ -2125,12 +2032,12 @@ "required": true }, { - "description": "create audit plan", - "name": "audit_plan", + "description": "instances", + "name": "instances", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateAuditPlanReqV1" + "$ref": "#/definitions/v1.BatchCheckInstanceConnectionsReqV1" } } ], @@ -2138,25 +2045,25 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.BatchGetInstanceConnectionsResV1" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/": { + "/v1/projects/{project_name}/instances/{instance_name}/connection": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan", + "description": "test instance db connection", "tags": [ - "audit_plan" + "instance" ], - "summary": "获取指定扫描任务", - "operationId": "getAuditPlanV1", + "summary": "实例连通性测试(实例提交后)", + "operationId": "checkInstanceIsConnectableByNameV1", "parameters": [ { "type": "string", @@ -2167,8 +2074,8 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", "in": "path", "required": true } @@ -2177,23 +2084,25 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanResV1" + "$ref": "#/definitions/v1.GetInstanceConnectableResV1" } } } - }, - "delete": { + } + }, + "/v1/projects/{project_name}/instances/{instance_name}/rules": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete audit plan", + "description": "get instance all rule", "tags": [ - "audit_plan" + "instance" ], - "summary": "删除扫描任务", - "operationId": "deleteAuditPlanV1", + "summary": "获取实例应用的规则列表", + "operationId": "getInstanceRuleListV1", "parameters": [ { "type": "string", @@ -2204,8 +2113,8 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", "in": "path", "required": true } @@ -2214,23 +2123,25 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetRulesResV1" } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/instances/{instance_name}/schemas": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update audit plan", + "description": "instance schema list", "tags": [ - "audit_plan" + "instance" ], - "summary": "更新扫描任务", - "operationId": "updateAuditPlanV1", + "summary": "实例 Schema 列表", + "operationId": "getInstanceSchemasV1", "parameters": [ { "type": "string", @@ -2241,44 +2152,35 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", "in": "path", "required": true - }, - { - "description": "update audit plan", - "name": "audit_plan", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateAuditPlanReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetInstanceSchemaResV1" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config": { + "/v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan notify config", + "description": "list table by schema", "tags": [ - "audit_plan" + "instance" ], - "summary": "获取扫描任务消息推送设置", - "operationId": "getAuditPlanNotifyConfigV1", + "summary": "获取数据库下的所有表", + "operationId": "listTableBySchema", "parameters": [ { "type": "string", @@ -2289,8 +2191,15 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "schema name", + "name": "schema_name", "in": "path", "required": true } @@ -2299,23 +2208,25 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanNotifyConfigResV1" + "$ref": "#/definitions/v1.ListTableBySchemaResV1" } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables/{table_name}/metadata": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update audit plan notify config", + "description": "get table metadata", "tags": [ - "audit_plan" + "instance" ], - "summary": "更新扫描任务通知设置", - "operationId": "updateAuditPlanNotifyConfigV1", + "summary": "获取表元数据", + "operationId": "getTableMetadata", "parameters": [ { "type": "string", @@ -2326,44 +2237,49 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "instance name", + "name": "instance_name", "in": "path", "required": true }, { - "description": "update audit plan notify config", - "name": "config", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateAuditPlanNotifyConfigReqV1" - } + "type": "string", + "description": "schema name", + "name": "schema_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "table name", + "name": "table_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetTableMetadataResV1" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config/test": { + "/v1/projects/{project_name}/rule_template_tips": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Test audit task message push", + "description": "get rule template tips in project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "测试扫描任务消息推送", - "operationId": "testAuditPlanNotifyConfigV1", + "summary": "获取项目规则模板提示", + "operationId": "getProjectRuleTemplateTipsV1", "parameters": [ { "type": "string", @@ -2374,35 +2290,34 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true + "description": "filter db type", + "name": "filter_db_type", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TestAuditPlanNotifyConfigResV1" + "$ref": "#/definitions/v1.GetRuleTemplateTipsResV1" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports": { + "/v1/projects/{project_name}/rule_templates": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan report list", + "description": "get all rule template in a project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取指定扫描任务的报告列表", - "operationId": "getAuditPlanReportsV1", + "summary": "项目规则模板列表", + "operationId": "getProjectRuleTemplateListV1", "parameters": [ { "type": "string", @@ -2411,13 +2326,6 @@ "in": "path", "required": true }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, { "type": "integer", "description": "page index", @@ -2437,25 +2345,26 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanReportsResV1" + "$ref": "#/definitions/v1.GetProjectRuleTemplatesResV1" } } } - } - }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/": { - "get": { + }, + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan report", + "description": "create a rule template in project", + "consumes": [ + "application/json" + ], "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取指定扫描任务的SQL扫描记录统计信息", - "operationId": "getAuditPlanReportV1", + "summary": "添加项目规则模板", + "operationId": "createProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2465,43 +2374,38 @@ "required": true }, { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", - "in": "path", - "required": true + "description": "add rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.CreateProjectRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanReportResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/export": { + "/v1/projects/{project_name}/rule_templates/{rule_template_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export audit plan report as csv", + "description": "get rule template detail in project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "以csv的形式导出扫描报告", - "operationId": "exportAuditPlanReportV1", + "summary": "获取项目规则模板信息", + "operationId": "getProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2512,42 +2416,39 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true }, { "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", - "in": "path", - "required": true + "description": "fuzzy rule,keyword for desc and annotation", + "name": "fuzzy_keyword_rule", + "in": "query" } ], "responses": { "200": { - "description": "get export audit plan report", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/v1.GetProjectRuleTemplateResV1" } } } - } - }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls": { - "get": { + }, + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan report SQLs", + "description": "delete rule template in project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取指定扫描任务的SQL扫描详情", - "operationId": "getAuditPlanReportsSQLsV1", + "summary": "删除项目规则模板", + "operationId": "deleteProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2558,56 +2459,33 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanReportSQLsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - } - }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get SQL explain and related table metadata for analysis", + "description": "update rule template in project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取task相关的SQL执行计划和表元数据", - "operationId": "getTaskAnalysisData", + "summary": "更新项目规则模板", + "operationId": "updateProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2618,49 +2496,47 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true }, { - "type": "string", - "description": "sql number", - "name": "number", - "in": "path", - "required": true + "description": "update rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateProjectRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanAnalysisDataResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls": { - "get": { + "/v1/projects/{project_name}/rule_templates/{rule_template_name}/clone": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get audit plan SQLs", + "description": "clone a rule template in project", + "consumes": [ + "application/json" + ], "tags": [ - "audit_plan" + "rule_template" ], - "summary": "获取指定扫描任务的SQLs信息(不包括扫描结果)", - "operationId": "getAuditPlanSQLsV1", + "summary": "克隆项目规则模板", + "operationId": "cloneProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2671,50 +2547,44 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true }, { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true + "description": "clone rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.CloneProjectRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditPlanSQLsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full": { - "post": { + "/v1/projects/{project_name}/rule_templates/{rule_template_name}/export": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "full sync audit plan SQLs", + "description": "export rule template in a project", "tags": [ - "audit_plan" + "rule_template" ], - "summary": "全量同步SQL到扫描任务", - "operationId": "fullSyncAuditPlanSQLsV1", - "deprecated": true, + "summary": "导出项目规则模板", + "operationId": "exportProjectRuleTemplateV1", "parameters": [ { "type": "string", @@ -2725,105 +2595,94 @@ }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true - }, - { - "description": "full sync audit plan SQLs request", - "name": "sqls", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.FullSyncAuditPlanSQLsReqV1" - } } ], "responses": { "200": { - "description": "OK", + "description": "sqle rule template file", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial": { - "post": { + "/v1/projects/{project_name}/sql_audit_records": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "partial sync audit plan SQLs", + "description": "get sql audit records", "tags": [ - "audit_plan" + "sql_audit_record" ], - "summary": "增量同步SQL到扫描任务", - "operationId": "partialSyncAuditPlanSQLsV1", - "deprecated": true, + "summary": "获取SQL审核记录列表", + "operationId": "getSQLAuditRecordsV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "fuzzy search tags", + "name": "fuzzy_search_tags", + "in": "query" }, { + "enum": [ + "auditing", + "successfully" + ], "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true + "description": "filter sql audit status", + "name": "filter_sql_audit_status", + "in": "query" }, { - "description": "partial sync audit plan SQLs request", - "name": "sqls", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.PartialSyncAuditPlanSQLsReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/projects/{project_name}/audit_plans/{audit_plan_name}/trigger": { - "post": { - "security": [ + "type": "integer", + "description": "filter instance id", + "name": "filter_instance_id", + "in": "query" + }, { - "ApiKeyAuth": [] - } - ], - "description": "trigger audit plan", - "tags": [ - "audit_plan" - ], - "summary": "触发扫描任务", - "operationId": "triggerAuditPlanV1", - "parameters": [ + "type": "string", + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "description": "filter create time to", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter sql audit record ids", + "name": "filter_sql_audit_record_ids", + "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", "required": true }, { "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true } @@ -2832,25 +2691,29 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.TriggerAuditPlanResV1" + "$ref": "#/definitions/v1.GetSQLAuditRecordsResV1" } } } - } - }, - "/v1/projects/{project_name}/audit_whitelist": { - "get": { + }, + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get all whitelist", + "description": "SQL audit\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.\n4. file[input_zip_file]: it is ZIP file that sql will be parsed from xml or sql file inside it.\n5. formData[git_http_url]:the url which scheme is http(s) and end with .git.\n6. formData[git_user_name]:The name of the user who owns the repository read access.\n7. formData[git_user_password]:The password corresponding to git_user_name.", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], "tags": [ - "audit_whitelist" + "sql_audit_record" ], - "summary": "获取Sql审核白名单", - "operationId": "getAuditWhitelistV1", + "summary": "SQL审核", + "operationId": "CreateSQLAuditRecordV1", "parameters": [ { "type": "string", @@ -2861,43 +2724,88 @@ }, { "type": "string", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true + "description": "instance name", + "name": "instance_name", + "in": "formData" }, { "type": "string", - "description": "page size", - "name": "page_size", - "in": "query", - "required": true + "description": "schema of instance", + "name": "instance_schema", + "in": "formData" + }, + { + "type": "string", + "description": "db type of instance", + "name": "db_type", + "in": "formData" + }, + { + "type": "string", + "description": "sqls for audit", + "name": "sqls", + "in": "formData" + }, + { + "type": "file", + "description": "input SQL file", + "name": "input_sql_file", + "in": "formData" + }, + { + "type": "file", + "description": "input mybatis XML file", + "name": "input_mybatis_xml_file", + "in": "formData" + }, + { + "type": "file", + "description": "input ZIP file", + "name": "input_zip_file", + "in": "formData" + }, + { + "type": "string", + "description": "git repository url", + "name": "git_http_url", + "in": "formData" + }, + { + "type": "string", + "description": "the name of user to clone the repository", + "name": "git_user_name", + "in": "formData" + }, + { + "type": "string", + "description": "the password corresponding to git_user_name", + "name": "git_user_password", + "in": "formData" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetAuditWhitelistResV1" + "$ref": "#/definitions/v1.CreateSQLAuditRecordResV1" } } } - }, - "post": { + } + }, + "/v1/projects/{project_name}/sql_audit_records/tag_tips": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create a sql whitelist", - "consumes": [ - "application/json" - ], + "description": "get sql audit record tag tips", "tags": [ - "audit_whitelist" + "sql_audit_record" ], - "summary": "添加SQL白名单", - "operationId": "createAuditWhitelistV1", + "summary": "获取SQL审核记录标签列表", + "operationId": "GetSQLAuditRecordTagTipsV1", "parameters": [ { "type": "string", @@ -2905,40 +2813,31 @@ "name": "project_name", "in": "path", "required": true - }, - { - "description": "add sql whitelist req", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateAuditWhitelistReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetSQLAuditRecordTagTipsResV1" } } } } }, - "/v1/projects/{project_name}/audit_whitelist/{audit_whitelist_id}/": { - "delete": { + "/v1/projects/{project_name}/sql_audit_records/{sql_audit_record_id}/": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "remove sql white", + "description": "get sql audit record info", "tags": [ - "audit_whitelist" + "sql_audit_record" ], - "summary": "删除SQL白名单信息", - "operationId": "deleteAuditWhitelistByIdV1", + "summary": "获取SQL审核记录信息", + "operationId": "getSQLAuditRecordV1", "parameters": [ { "type": "string", @@ -2949,8 +2848,8 @@ }, { "type": "string", - "description": "audit whitelist id", - "name": "audit_whitelist_id", + "description": "sql audit record id", + "name": "sql_audit_record_id", "in": "path", "required": true } @@ -2959,7 +2858,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetSQLAuditRecordResV1" } } } @@ -2970,15 +2869,15 @@ "ApiKeyAuth": [] } ], - "description": "update sql whitelist by id", + "description": "update SQL audit record", "consumes": [ "application/json" ], "tags": [ - "audit_whitelist" + "sql_audit_record" ], - "summary": "更新SQL白名单", - "operationId": "UpdateAuditWhitelistByIdV1", + "summary": "更新SQL审核记录", + "operationId": "updateSQLAuditRecordV1", "parameters": [ { "type": "string", @@ -2989,18 +2888,18 @@ }, { "type": "string", - "description": "sql audit whitelist id", - "name": "audit_whitelist_id", + "description": "sql audit record id", + "name": "sql_audit_record_id", "in": "path", "required": true }, { - "description": "update sql whitelist req", - "name": "instance", + "description": "update SQL audit record", + "name": "param", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateAuditWhitelistReqV1" + "$ref": "#/definitions/v1.UpdateSQLAuditRecordReqV1" } } ], @@ -3014,19 +2913,20 @@ } } }, - "/v1/projects/{project_name}/instance_tips": { + "/v1/projects/{project_name}/sql_manages": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance tip list", + "description": "get sql manage list", "tags": [ - "instance" + "SqlManage" ], - "summary": "获取实例提示列表", - "operationId": "getInstanceTipListV1", + "summary": "获取管控sql列表", + "operationId": "GetSqlManageList", + "deprecated": true, "parameters": [ { "type": "string", @@ -3037,93 +2937,111 @@ }, { "type": "string", - "description": "filter db type", - "name": "filter_db_type", + "description": "fuzzy search sql fingerprint", + "name": "fuzzy_search_sql_fingerprint", "in": "query" }, { "type": "string", - "description": "filter workflow template id", - "name": "filter_workflow_template_id", + "description": "assignee", + "name": "filter_assignee", + "in": "query" + }, + { + "type": "string", + "description": "instance name", + "name": "filter_instance_name", "in": "query" }, { "enum": [ - "create_audit_plan", - "create_workflow", - "sql_manage" + "audit_plan", + "sql_audit_record" ], "type": "string", - "description": "functional module", - "name": "functional_module", + "description": "source", + "name": "filter_source", "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetInstanceTipsResV1" - } - } - } - } - }, - "/v1/projects/{project_name}/instances": { - "get": { - "security": [ + }, { - "ApiKeyAuth": [] - } - ], - "description": "get instance info list", - "tags": [ - "instance" - ], - "summary": "获取实例信息列表", - "operationId": "getInstanceListV1", - "parameters": [ + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "type": "string", + "description": "audit level", + "name": "filter_audit_level", + "in": "query" + }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "last audit start time from", + "name": "filter_last_audit_start_time_from", + "in": "query" }, { "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", + "description": "last audit start time to", + "name": "filter_last_audit_start_time_to", + "in": "query" + }, + { + "enum": [ + "unhandled", + "solved", + "ignored", + "manual_audited" + ], + "type": "string", + "description": "status", + "name": "filter_status", "in": "query" }, { "type": "string", - "description": "filter db type", + "description": "rule name", + "name": "filter_rule_name", + "in": "query" + }, + { + "type": "string", + "description": "db type", "name": "filter_db_type", "in": "query" }, { "type": "string", - "description": "filter db host", - "name": "filter_db_host", + "description": "fuzzy search endpoint", + "name": "fuzzy_search_endpoint", "in": "query" }, { "type": "string", - "description": "filter db port", - "name": "filter_db_port", + "description": "fuzzy search schema name", + "name": "fuzzy_search_schema_name", "in": "query" }, { + "enum": [ + "first_appear_timestamp", + "last_receive_timestamp", + "fp_count" + ], "type": "string", - "description": "filter db user", - "name": "filter_db_user", + "description": "sort field", + "name": "sort_field", "in": "query" }, { + "enum": [ + "asc", + "desc" + ], "type": "string", - "description": "filter rule template name", - "name": "filter_rule_template_name", + "description": "sort order", + "name": "sort_order", "in": "query" }, { @@ -3145,27 +3063,25 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstancesResV1" + "$ref": "#/definitions/v1.GetSqlManageListResp" } } } - }, - "post": { + } + }, + "/v1/projects/{project_name}/sql_manages/batch": { + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create a instance", - "consumes": [ - "application/json" - ], + "description": "batch update sql manage", "tags": [ - "instance" + "SqlManage" ], - "summary": "添加实例", - "operationId": "createInstanceV1", - "deprecated": true, + "summary": "批量更新SQL管控", + "operationId": "BatchUpdateSqlManage", "parameters": [ { "type": "string", @@ -3175,12 +3091,12 @@ "required": true }, { - "description": "add instance", - "name": "instance", + "description": "batch update sql manage request", + "name": "BatchUpdateSqlManageReq", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateInstanceReqV1" + "$ref": "#/definitions/v1.BatchUpdateSqlManageReq" } } ], @@ -3194,19 +3110,19 @@ } } }, - "/v1/projects/{project_name}/instances/connections": { - "post": { + "/v1/projects/{project_name}/sql_manages/exports": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "batch test instance db connections", + "description": "export sql manage", "tags": [ - "instance" + "SqlManage" ], - "summary": "批量测试实例连通性(实例提交后)", - "operationId": "batchCheckInstanceIsConnectableByName", + "summary": "导出SQL管控", + "operationId": "exportSqlManageV1", "parameters": [ { "type": "string", @@ -3216,160 +3132,138 @@ "required": true }, { - "description": "instances", - "name": "instances", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.BatchCheckInstanceConnectionsReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.BatchGetInstanceConnectionsResV1" - } - } - } - } - }, - "/v1/projects/{project_name}/instances/{instance_name}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get instance db", - "tags": [ - "instance" - ], - "summary": "获取实例信息", - "operationId": "getInstanceV1", - "parameters": [ + "type": "string", + "description": "fuzzy search sql fingerprint", + "name": "fuzzy_search_sql_fingerprint", + "in": "query" + }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "assignee", + "name": "filter_assignee", + "in": "query" }, { "type": "string", "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetInstanceResV1" - } - } - } - }, - "delete": { - "security": [ + "name": "filter_instance_name", + "in": "query" + }, { - "ApiKeyAuth": [] - } - ], - "description": "delete instance db", - "tags": [ - "instance" - ], - "summary": "删除实例", - "operationId": "deleteInstanceV1", - "parameters": [ + "enum": [ + "audit_plan", + "sql_audit_record" + ], + "type": "string", + "description": "source", + "name": "filter_source", + "in": "query" + }, { + "enum": [ + "normal", + "notice", + "warn", + "error" + ], "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "audit level", + "name": "filter_audit_level", + "in": "query" }, { "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ + "description": "last audit start time from", + "name": "filter_last_audit_start_time_from", + "in": "query" + }, { - "ApiKeyAuth": [] - } - ], - "description": "update instance", - "tags": [ - "instance" - ], - "summary": "更新实例", - "operationId": "updateInstanceV1", - "parameters": [ + "type": "string", + "description": "last audit start time to", + "name": "filter_last_audit_start_time_to", + "in": "query" + }, { + "enum": [ + "unhandled", + "solved", + "ignored", + "manual_audited" + ], "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "status", + "name": "filter_status", + "in": "query" }, { "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true + "description": "db type", + "name": "filter_db_type", + "in": "query" }, { - "description": "update instance request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateInstanceReqV1" - } + "type": "string", + "description": "rule name", + "name": "filter_rule_name", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search endpoint", + "name": "fuzzy_search_endpoint", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search schema name", + "name": "fuzzy_search_schema_name", + "in": "query" + }, + { + "enum": [ + "first_appear_timestamp", + "last_receive_timestamp", + "fp_count" + ], + "type": "string", + "description": "sort field", + "name": "sort_field", + "in": "query" + }, + { + "enum": [ + "asc", + "desc" + ], + "type": "string", + "description": "sort order", + "name": "sort_order", + "in": "query" } ], "responses": { "200": { - "description": "OK", + "description": "export sql manage", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/connection": { + "/v1/projects/{project_name}/sql_manages/rule_tips": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "test instance db connection", + "description": "get sql manage rule tips", "tags": [ - "instance" + "SqlManage" ], - "summary": "实例连通性测试(实例提交后)", - "operationId": "checkInstanceIsConnectableByNameV1", + "summary": "获取管控规则tips", + "operationId": "GetSqlManageRuleTips", "parameters": [ { "type": "string", @@ -3377,38 +3271,31 @@ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstanceConnectableResV1" + "$ref": "#/definitions/v1.GetSqlManageRuleTipsResp" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/rules": { + "/v1/projects/{project_name}/sql_manages/{sql_manage_id}/sql_analysis": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance all rule", + "description": "get sql manage analysis", "tags": [ - "instance" + "SqlManage" ], - "summary": "获取实例应用的规则列表", - "operationId": "getInstanceRuleListV1", + "summary": "获取SQL管控SQL分析", + "operationId": "GetSqlManageSqlAnalysisV1", "parameters": [ { "type": "string", @@ -3419,8 +3306,8 @@ }, { "type": "string", - "description": "instance name", - "name": "instance_name", + "description": "sql manage id", + "name": "sql_manage_id", "in": "path", "required": true } @@ -3429,25 +3316,25 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRulesResV1" + "$ref": "#/definitions/v1.GetSqlManageSqlAnalysisResp" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/schemas": { + "/v1/projects/{project_name}/statistic/audit_plans": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "instance schema list", + "description": "statistic audit plan", "tags": [ - "instance" + "statistic" ], - "summary": "实例 Schema 列表", - "operationId": "getInstanceSchemasV1", + "summary": "获取各类型数据源上的扫描任务数量", + "operationId": "statisticAuditPlanV1", "parameters": [ { "type": "string", @@ -3455,38 +3342,31 @@ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstanceSchemaResV1" + "$ref": "#/definitions/v1.StatisticAuditPlanResV1" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables": { + "/v1/projects/{project_name}/statistic/audited_sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "list table by schema", + "description": "statistics audited sql", "tags": [ - "instance" + "statistic" ], - "summary": "获取数据库下的所有表", - "operationId": "listTableBySchema", + "summary": "获取审核SQL总数,以及触发审核规则的SQL数量", + "operationId": "statisticsAuditedSQLV1", "parameters": [ { "type": "string", @@ -3494,45 +3374,31 @@ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "schema name", - "name": "schema_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.ListTableBySchemaResV1" + "$ref": "#/definitions/v1.StatisticsAuditedSQLResV1" } } } } }, - "/v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables/{table_name}/metadata": { + "/v1/projects/{project_name}/statistic/instance_health": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get table metadata", + "description": "get instance health", "tags": [ - "instance" + "statistic" ], - "summary": "获取表元数据", - "operationId": "getTableMetadata", + "summary": "获取各类型数据源的健康情况", + "operationId": "GetInstanceHealthV1", "parameters": [ { "type": "string", @@ -3540,79 +3406,32 @@ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "schema name", - "name": "schema_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "table name", - "name": "table_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetTableMetadataResV1" + "$ref": "#/definitions/v1.GetInstanceHealthResV1" } } } } }, - "/v1/projects/{project_name}/member_groups": { + "/v1/projects/{project_name}/statistic/project_score": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get member groups", + "description": "get project score", "tags": [ - "user_group" + "statistic" ], - "summary": "获取成员组列表", - "operationId": "getMemberGroupsV1", + "summary": "获取项目分数", + "operationId": "GetProjectScoreV1", "parameters": [ - { - "type": "string", - "description": "filter user group name", - "name": "filter_user_group_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - }, { "type": "string", "description": "project name", @@ -3625,29 +3444,25 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetMemberGroupsRespV1" + "$ref": "#/definitions/v1.GetProjectScoreResV1" } } } - }, - "post": { + } + }, + "/v1/projects/{project_name}/statistic/risk_audit_plans": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "add member group", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get risk audit plan", "tags": [ - "user_group" + "statistic" ], - "summary": "添加成员组", - "operationId": "addMemberGroupV1", + "summary": "获取扫描任务报告评分低于60的扫描任务", + "operationId": "getRiskAuditPlanV1", "parameters": [ { "type": "string", @@ -3655,77 +3470,31 @@ "name": "project_name", "in": "path", "required": true - }, - { - "description": "add member group", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateMemberGroupReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetRiskAuditPlanResV1" } } } } }, - "/v1/projects/{project_name}/member_groups/{user_group_name}/": { + "/v1/projects/{project_name}/statistic/risk_workflow": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get member group", + "description": "statistic risk workflow", "tags": [ - "user_group" + "statistic" ], - "summary": "获取成员组信息", - "operationId": "getMemberGroupV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "user group name", - "name": "user_group_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetMemberGroupRespV1" - } - } - } - }, - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete member group", - "tags": [ - "user_group" - ], - "summary": "删除成员组", - "operationId": "deleteMemberGroupV1", + "summary": "获取存在风险的工单", + "operationId": "statisticRiskWorkflowV1", "parameters": [ { "type": "string", @@ -3733,42 +3502,31 @@ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "user group name", - "name": "user_group_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.StatisticRiskWorkflowResV1" } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/statistic/role_user": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update member group", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get role user count", "tags": [ - "user_group" + "statistic" ], - "summary": "修改成员组", - "operationId": "updateMemberGroupV1", + "summary": "获取各角色类型对应的成员数量", + "operationId": "getRoleUserCountV1", "parameters": [ { "type": "string", @@ -3776,47 +3534,31 @@ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "user group name", - "name": "user_group_name", - "in": "path", - "required": true - }, - { - "description": "update member_group", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateMemberGroupReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetRoleUserCountResV1" } } } } }, - "/v1/projects/{project_name}/member_tips": { + "/v1/projects/{project_name}/statistic/workflow_status": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get member tip list", + "description": "statistic workflow status", "tags": [ - "user" + "statistic" ], - "summary": "获取成员提示列表", - "operationId": "getMemberTipListV1", + "summary": "获取项目下工单各个状态的数量", + "operationId": "statisticWorkflowStatusV1", "parameters": [ { "type": "string", @@ -3830,52 +3572,26 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetMemberTipsResV1" + "$ref": "#/definitions/v1.GetWorkflowStatusCountResV1" } } } } }, - "/v1/projects/{project_name}/members": { + "/v1/projects/{project_name}/statistics": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get members", + "description": "get project statistics", "tags": [ - "user" + "statistic" ], - "summary": "获取成员列表", - "operationId": "getMembersV1", + "summary": "获取项目统计信息", + "operationId": "getProjectStatisticsV1", "parameters": [ - { - "type": "string", - "description": "filter user name", - "name": "filter_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - }, { "type": "string", "description": "project name", @@ -3888,18 +3604,20 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetMembersRespV1" + "$ref": "#/definitions/v1.GetProjectStatisticsResV1" } } } - }, + } + }, + "/v1/projects/{project_name}/task_groups": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "add member", + "description": "create tasks group.", "consumes": [ "application/json" ], @@ -3907,10 +3625,10 @@ "application/json" ], "tags": [ - "user" + "task" ], - "summary": "添加成员", - "operationId": "addMemberV1", + "summary": "创建审核任务组", + "operationId": "createAuditTasksV1", "parameters": [ { "type": "string", @@ -3920,12 +3638,12 @@ "required": true }, { - "description": "add member", - "name": "data", + "description": "parameters for creating audit tasks group", + "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateMemberReqV1" + "$ref": "#/definitions/v1.CreateAuditTasksGroupReqV1" } } ], @@ -3933,25 +3651,31 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.CreateAuditTasksGroupResV1" } } } } }, - "/v1/projects/{project_name}/members/{user_name}/": { - "get": { + "/v1/projects/{project_name}/tasks/audits": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get member", + "description": "create and audit a task, you can upload sql content in three ways, any one can be used, but only one is effective.\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], "tags": [ - "user" + "task" ], - "summary": "获取成员信息", - "operationId": "getMemberV1", + "summary": "创建Sql扫描任务并提交审核", + "operationId": "createAndAuditTaskV1", "parameters": [ { "type": "string", @@ -3962,33 +3686,65 @@ }, { "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", + "description": "instance name", + "name": "instance_name", + "in": "formData", "required": true + }, + { + "type": "string", + "description": "schema of instance", + "name": "instance_schema", + "in": "formData" + }, + { + "type": "string", + "description": "sqls for audit", + "name": "sql", + "in": "formData" + }, + { + "type": "file", + "description": "input SQL file", + "name": "input_sql_file", + "in": "formData" + }, + { + "type": "file", + "description": "input mybatis XML file", + "name": "input_mybatis_xml_file", + "in": "formData" + }, + { + "type": "file", + "description": "input ZIP file", + "name": "input_zip_file", + "in": "formData" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetMemberRespV1" + "$ref": "#/definitions/v1.GetAuditTaskResV1" } } } - }, - "delete": { + } + }, + "/v1/projects/{project_name}/workflow_template": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete member", + "description": "get workflow template detail", "tags": [ - "user" + "workflow" ], - "summary": "删除成员", - "operationId": "deleteMemberV1", + "summary": "获取审批流程模板详情", + "operationId": "getWorkflowTemplateV1", "parameters": [ { "type": "string", @@ -3996,20 +3752,13 @@ "name": "project_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowTemplateResV1" } } } @@ -4020,7 +3769,7 @@ "ApiKeyAuth": [] } ], - "description": "update member", + "description": "update the workflow template", "consumes": [ "application/json" ], @@ -4028,10 +3777,10 @@ "application/json" ], "tags": [ - "user" + "workflow" ], - "summary": "修改成员", - "operationId": "updateMemberV1", + "summary": "更新Sql审批流程模板", + "operationId": "updateWorkflowTemplateV1", "parameters": [ { "type": "string", @@ -4041,19 +3790,12 @@ "required": true }, { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - }, - { - "description": "update member", - "name": "data", + "description": "create workflow template", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateMemberReqV1" + "$ref": "#/definitions/v1.UpdateWorkflowTemplateReqV1" } } ], @@ -4067,64 +3809,94 @@ } } }, - "/v1/projects/{project_name}/rule_template_tips": { + "/v1/projects/{project_name}/workflows": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get rule template tips in project", + "description": "get workflow list", "tags": [ - "rule_template" + "workflow" ], - "summary": "获取项目规则模板提示", - "operationId": "getProjectRuleTemplateTipsV1", + "summary": "获取工单列表", + "operationId": "getWorkflowsV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "filter subject", + "name": "filter_subject", + "in": "query" }, { "type": "string", - "description": "filter db type", - "name": "filter_db_type", + "description": "filter by workflow_id", + "name": "filter_workflow_id", "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetRuleTemplateTipsResV1" - } - } - } - } - }, - "/v1/projects/{project_name}/rule_templates": { - "get": { - "security": [ + }, { - "ApiKeyAuth": [] - } - ], - "description": "get all rule template in a project", - "tags": [ - "rule_template" - ], - "summary": "项目规则模板列表", - "operationId": "getProjectRuleTemplateListV1", - "parameters": [ + "type": "string", + "description": "fuzzy search by workflow description", + "name": "fuzzy_search_workflow_desc", + "in": "query" + }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter create time to", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_from", + "name": "filter_task_execute_start_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_to", + "name": "filter_task_execute_start_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter create user id", + "name": "filter_create_user_id", + "in": "query" + }, + { + "enum": [ + "wait_for_audit", + "wait_for_execution", + "rejected", + "executing", + "canceled", + "exec_failed", + "finished" + ], + "type": "string", + "description": "filter workflow status", + "name": "filter_status", + "in": "query" + }, + { + "type": "string", + "description": "filter current step assignee user id", + "name": "filter_current_step_assignee_user_id", + "in": "query" + }, + { + "type": "string", + "description": "filter instance name", + "name": "filter_task_instance_name", + "in": "query" }, { "type": "integer", @@ -4139,13 +3911,26 @@ "name": "page_size", "in": "query", "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "fuzzy matching subject/workflow_id", + "name": "fuzzy_keyword", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectRuleTemplatesResV1" + "$ref": "#/definitions/v1.GetWorkflowsResV1" } } } @@ -4156,31 +3941,35 @@ "ApiKeyAuth": [] } ], - "description": "create a rule template in project", + "description": "create workflow", "consumes": [ "application/json" ], + "produces": [ + "application/json" + ], "tags": [ - "rule_template" + "workflow" ], - "summary": "添加项目规则模板", - "operationId": "createProjectRuleTemplateV1", + "summary": "创建工单", + "operationId": "createWorkflowV1", + "deprecated": true, "parameters": [ + { + "description": "create workflow request", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.CreateWorkflowReqV1" + } + }, { "type": "string", "description": "project name", "name": "project_name", "in": "path", "required": true - }, - { - "description": "add rule template request", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateProjectRuleTemplateReqV1" - } } ], "responses": { @@ -4193,19 +3982,20 @@ } } }, - "/v1/projects/{project_name}/rule_templates/{rule_template_name}/": { - "get": { + "/v1/projects/{project_name}/workflows/cancel": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get rule template detail in project", + "description": "batch cancel workflows", "tags": [ - "rule_template" + "workflow" ], - "summary": "获取项目规则模板信息", - "operationId": "getProjectRuleTemplateV1", + "summary": "批量取消工单", + "operationId": "batchCancelWorkflowsV1", + "deprecated": true, "parameters": [ { "type": "string", @@ -4215,34 +4005,39 @@ "required": true }, { - "type": "string", - "description": "rule template name", - "name": "rule_template_name", - "in": "path", - "required": true + "description": "batch cancel workflows request", + "name": "BatchCancelWorkflowsReqV1", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.BatchCancelWorkflowsReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectRuleTemplateResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - }, - "delete": { + } + }, + "/v1/projects/{project_name}/workflows/complete": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete rule template in project", + "description": "this api will directly change the work order status to finished without real online operation", "tags": [ - "rule_template" + "workflow" ], - "summary": "删除项目规则模板", - "operationId": "deleteProjectRuleTemplateV1", + "summary": "批量完成工单", + "operationId": "batchCompleteWorkflowsV1", + "deprecated": true, "parameters": [ { "type": "string", @@ -4252,11 +4047,13 @@ "required": true }, { - "type": "string", - "description": "rule template name", - "name": "rule_template_name", - "in": "path", - "required": true + "description": "batch complete workflows request", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.BatchCompleteWorkflowsReqV1" + } } ], "responses": { @@ -4267,93 +4064,142 @@ } } } - }, - "patch": { + } + }, + "/v1/projects/{project_name}/workflows/exports": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update rule template in project", + "description": "export workflow", "tags": [ - "rule_template" + "workflow" ], - "summary": "更新项目规则模板", - "operationId": "updateProjectRuleTemplateV1", + "summary": "导出工单", + "operationId": "exportWorkflowV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "filter subject", + "name": "filter_subject", + "in": "query" }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "fuzzy search by workflow description", + "name": "fuzzy_search_workflow_desc", + "in": "query" + }, + { + "type": "string", + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter create time to", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_from", + "name": "filter_task_execute_start_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_to", + "name": "filter_task_execute_start_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter create user id", + "name": "filter_create_user_id", + "in": "query" + }, + { + "enum": [ + "wait_for_audit", + "wait_for_execution", + "rejected", + "executing", + "canceled", + "exec_failed", + "finished" + ], + "type": "string", + "description": "filter workflow status", + "name": "filter_status", + "in": "query" + }, + { + "type": "string", + "description": "filter current step assignee user id", + "name": "filter_current_step_assignee_user_id", + "in": "query" + }, + { + "type": "string", + "description": "filter instance name", + "name": "filter_task_instance_name", + "in": "query" + }, + { + "type": "string", + "description": "project name", + "name": "project_name", "in": "path", "required": true }, { - "description": "update rule template request", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateProjectRuleTemplateReqV1" - } + "type": "string", + "description": "fuzzy matching subject/workflow_id/desc", + "name": "fuzzy_keyword", + "in": "query" } ], "responses": { "200": { - "description": "OK", + "description": "export workflow", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/projects/{project_name}/rule_templates/{rule_template_name}/clone": { + "/v1/projects/{project_name}/workflows/{workflow_id}/tasks/terminate": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "clone a rule template in project", - "consumes": [ - "application/json" - ], + "description": "terminate multiple task by project and workflow", "tags": [ - "rule_template" + "workflow" ], - "summary": "克隆项目规则模板", - "operationId": "cloneProjectRuleTemplateV1", + "summary": "终止工单下多个上线任务", + "operationId": "terminateMultipleTaskByWorkflowV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow id", + "name": "workflow_id", "in": "path", "required": true }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true - }, - { - "description": "clone rule template request", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CloneProjectRuleTemplateReqV1" - } } ], "responses": { @@ -4366,20 +4212,27 @@ } } }, - "/v1/projects/{project_name}/rule_templates/{rule_template_name}/export": { - "get": { + "/v1/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/terminate": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export rule template in a project", + "description": "execute one task on workflow", "tags": [ - "rule_template" + "workflow" ], - "summary": "导出项目规则模板", - "operationId": "exportProjectRuleTemplateV1", + "summary": "终止单个上线任务", + "operationId": "terminateSingleTaskByWorkflowV1", "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, { "type": "string", "description": "project name", @@ -4389,88 +4242,42 @@ }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "task id", + "name": "task_id", "in": "path", "required": true } ], "responses": { "200": { - "description": "sqle rule template file", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/sql_audit_records": { + "/v1/projects/{project_name}/workflows/{workflow_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql audit records", + "description": "get workflow detail", "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "获取SQL审核记录列表", - "operationId": "getSQLAuditRecordsV1", + "summary": "获取工单详情", + "operationId": "getWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "fuzzy search tags", - "name": "fuzzy_search_tags", - "in": "query" - }, - { - "enum": [ - "auditing", - "successfully" - ], - "type": "string", - "description": "filter sql audit status", - "name": "filter_sql_audit_status", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "type": "string", - "description": "filter create time from", - "name": "filter_create_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter create time to", - "name": "filter_create_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter sql audit record ids", - "name": "filter_sql_audit_record_ids", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", + "description": "workflow name", + "name": "workflow_name", + "in": "path", "required": true }, { @@ -4485,121 +4292,79 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSQLAuditRecordsResV1" + "$ref": "#/definitions/v1.GetWorkflowResV1" } } } }, - "post": { + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "SQL audit\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.\n4. file[input_zip_file]: it is ZIP file that sql will be parsed from xml or sql file inside it.\n5. formData[git_http_url]:the url which scheme is http(s) and end with .git.\n6. formData[git_user_name]:The name of the user who owns the repository read access.\n7. formData[git_user_password]:The password corresponding to git_user_name.", + "description": "update workflow when it is rejected to creator.", "consumes": [ - "multipart/form-data" + "application/json" ], "produces": [ "application/json" ], "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "SQL审核", - "operationId": "CreateSQLAuditRecordV1", + "summary": "更新工单(驳回后才可更新)", + "operationId": "updateWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "formData" - }, - { - "type": "string", - "description": "schema of instance", - "name": "instance_schema", - "in": "formData" - }, - { - "type": "string", - "description": "db type of instance", - "name": "db_type", - "in": "formData" - }, - { - "type": "string", - "description": "sqls for audit", - "name": "sqls", - "in": "formData" - }, - { - "type": "file", - "description": "input SQL file", - "name": "input_sql_file", - "in": "formData" - }, - { - "type": "file", - "description": "input mybatis XML file", - "name": "input_mybatis_xml_file", - "in": "formData" - }, - { - "type": "file", - "description": "input ZIP file", - "name": "input_zip_file", - "in": "formData" - }, - { - "type": "string", - "description": "git repository url", - "name": "git_http_url", - "in": "formData" - }, - { - "type": "string", - "description": "the name of user to clone the repository", - "name": "git_user_name", - "in": "formData" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { - "type": "string", - "description": "the password corresponding to git_user_name", - "name": "git_user_password", - "in": "formData" + "description": "update workflow request", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateWorkflowReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.CreateSQLAuditRecordResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/sql_audit_records/tag_tips": { - "get": { + "/v1/projects/{project_name}/workflows/{workflow_name}/cancel": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql audit record tag tips", + "description": "cancel workflow", "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "获取SQL审核记录标签列表", - "operationId": "GetSQLAuditRecordTagTipsV1", + "summary": "审批关闭(中止)", + "operationId": "cancelWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", @@ -4607,43 +4372,58 @@ "name": "project_name", "in": "path", "required": true + }, + { + "type": "string", + "description": "workflow name", + "name": "workflow_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSQLAuditRecordTagTipsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/sql_audit_records/{sql_audit_record_id}/": { - "get": { + "/v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/approve": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql audit record info", + "description": "approve workflow", "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "获取SQL审核记录信息", - "operationId": "getSQLAuditRecordV1", + "summary": "审批通过", + "operationId": "approveWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { "type": "string", - "description": "sql audit record id", - "name": "sql_audit_record_id", + "description": "workflow step id", + "name": "workflow_step_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", "in": "path", "required": true } @@ -4652,27 +4432,34 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSQLAuditRecordResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] + } + }, + "/v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/reject": { + "post": { + "security": [ + { + "ApiKeyAuth": [] } ], - "description": "update SQL audit record", - "consumes": [ - "application/json" - ], + "description": "reject workflow", "tags": [ - "sql_audit_record" + "workflow" ], - "summary": "更新SQL审核记录", - "operationId": "updateSQLAuditRecordV1", + "summary": "审批驳回", + "operationId": "rejectWorkflowV1", + "deprecated": true, "parameters": [ + { + "type": "string", + "description": "workflow name", + "name": "workflow_name", + "in": "path", + "required": true + }, { "type": "string", "description": "project name", @@ -4682,18 +4469,18 @@ }, { "type": "string", - "description": "sql audit record id", - "name": "sql_audit_record_id", + "description": "workflow step id", + "name": "workflow_step_id", "in": "path", "required": true }, { - "description": "update SQL audit record", - "name": "param", + "description": "workflow approve request", + "name": "workflow_approve", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateSQLAuditRecordReqV1" + "$ref": "#/definitions/v1.RejectWorkflowReqV1" } } ], @@ -4707,149 +4494,33 @@ } } }, - "/v1/projects/{project_name}/sql_manages": { + "/v1/projects/{project_name}/workflows/{workflow_name}/tasks": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql manage list", + "description": "get summary of workflow instance tasks", "tags": [ - "SqlManage" + "workflow" ], - "summary": "获取管控sql列表", - "operationId": "GetSqlManageList", + "summary": "获取工单数据源任务概览", + "operationId": "getSummaryOfInstanceTasksV1", "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { "type": "string", - "description": "fuzzy search sql fingerprint", - "name": "fuzzy_search_sql_fingerprint", - "in": "query" - }, - { - "type": "string", - "description": "assignee", - "name": "filter_assignee", - "in": "query" - }, - { - "type": "string", - "description": "instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "enum": [ - "audit_plan", - "sql_audit_record" - ], - "type": "string", - "description": "source", - "name": "filter_source", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "audit level", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time from", - "name": "filter_last_audit_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time to", - "name": "filter_last_audit_start_time_to", - "in": "query" - }, - { - "enum": [ - "unhandled", - "solved", - "ignored", - "manual_audited" - ], - "type": "string", - "description": "status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "rule name", - "name": "filter_rule_name", - "in": "query" - }, - { - "type": "string", - "description": "db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search endpoint", - "name": "fuzzy_search_endpoint", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search schema name", - "name": "fuzzy_search_schema_name", - "in": "query" - }, - { - "enum": [ - "first_appear_timestamp", - "last_receive_timestamp", - "fp_count" - ], - "type": "string", - "description": "sort field", - "name": "sort_field", - "in": "query" - }, - { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "description": "sort order", - "name": "sort_order", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", + "description": "project name", + "name": "project_name", + "in": "path", "required": true } ], @@ -4857,41 +4528,40 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlManageListResp" + "$ref": "#/definitions/v1.GetWorkflowTasksResV1" } } } } }, - "/v1/projects/{project_name}/sql_manages/batch": { - "patch": { + "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/execute": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "batch update sql manage", + "description": "execute tasks on workflow", "tags": [ - "SqlManage" + "workflow" ], - "summary": "批量更新SQL管控", - "operationId": "BatchUpdateSqlManage", + "summary": "多数据源批量上线", + "operationId": "executeTasksOnWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { - "description": "batch update sql manage request", - "name": "BatchUpdateSqlManageReq", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.BatchUpdateSqlManageReq" - } + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true } ], "responses": { @@ -4904,165 +4574,140 @@ } } }, - "/v1/projects/{project_name}/sql_manages/exports": { - "get": { + "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/execute": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export sql manage", + "description": "execute one task on workflow", "tags": [ - "SqlManage" + "workflow" ], - "summary": "导出SQL管控", - "operationId": "exportSqlManageV1", + "summary": "工单提交单个数据源上线", + "operationId": "executeOneTaskOnWorkflowV1", + "deprecated": true, "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "workflow name", + "name": "workflow_name", "in": "path", "required": true }, { "type": "string", - "description": "fuzzy search sql fingerprint", - "name": "fuzzy_search_sql_fingerprint", - "in": "query" - }, - { - "type": "string", - "description": "assignee", - "name": "filter_assignee", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { "type": "string", - "description": "instance name", - "name": "filter_instance_name", - "in": "query" - }, + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/controller.BaseRes" + } + } + } + } + }, + "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/schedule": { + "put": { + "security": [ { - "enum": [ - "audit_plan", - "sql_audit_record" - ], - "type": "string", - "description": "source", - "name": "filter_source", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "audit level", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time from", - "name": "filter_last_audit_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time to", - "name": "filter_last_audit_start_time_to", - "in": "query" - }, - { - "enum": [ - "unhandled", - "solved", - "ignored", - "manual_audited" - ], - "type": "string", - "description": "status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "rule name", - "name": "filter_rule_name", - "in": "query" - }, + "ApiKeyAuth": [] + } + ], + "description": "update workflow schedule.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "workflow" + ], + "summary": "设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置)", + "operationId": "updateWorkflowScheduleV1", + "deprecated": true, + "parameters": [ { "type": "string", - "description": "fuzzy search endpoint", - "name": "fuzzy_search_endpoint", - "in": "query" + "description": "workflow name", + "name": "workflow_name", + "in": "path", + "required": true }, { "type": "string", - "description": "fuzzy search schema name", - "name": "fuzzy_search_schema_name", - "in": "query" + "description": "task id", + "name": "task_id", + "in": "path", + "required": true }, { - "enum": [ - "first_appear_timestamp", - "last_receive_timestamp", - "fp_count" - ], "type": "string", - "description": "sort field", - "name": "sort_field", - "in": "query" + "description": "project name", + "name": "project_name", + "in": "path", + "required": true }, { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "description": "sort order", - "name": "sort_order", - "in": "query" + "description": "update workflow schedule request", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateWorkflowScheduleReqV1" + } } ], "responses": { "200": { - "description": "export sql manage", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/sql_manages/rule_tips": { + "/v1/rule_knowledge/db_types/{db_type}/custom_rules/{rule_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql manage rule tips", + "description": "get custom rule knowledge", "tags": [ - "SqlManage" + "rule_template" ], - "summary": "获取管控规则tips", - "operationId": "GetSqlManageRuleTips", + "summary": "查看自定义规则知识库", + "operationId": "getCustomRuleKnowledgeV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule name", + "name": "rule_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "db type of rule", + "name": "db_type", "in": "path", "required": true } @@ -5071,69 +4716,83 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlManageRuleTipsResp" + "$ref": "#/definitions/v1.GetRuleKnowledgeResV1" } } } - } - }, - "/v1/projects/{project_name}/sql_manages/{sql_manage_id}/sql_analysis": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql manage analysis", + "description": "update custom rule knowledge", "tags": [ - "SqlManage" + "rule_template" ], - "summary": "获取SQL管控SQL分析", - "operationId": "GetSqlManageSqlAnalysisV1", + "summary": "更新自定义规则知识库", + "operationId": "updateCustomRuleKnowledge", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule name", + "name": "rule_name", "in": "path", "required": true }, { "type": "string", - "description": "sql manage id", - "name": "sql_manage_id", + "description": "db type of rule", + "name": "db_type", "in": "path", "required": true + }, + { + "description": "update rule knowledge", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateRuleKnowledgeReq" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlManageSqlAnalysisResp" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/statistic/audit_plans": { + "/v1/rule_knowledge/db_types/{db_type}/rules/{rule_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "statistic audit plan", + "description": "get rule knowledge", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取各类型数据源上的扫描任务数量", - "operationId": "statisticAuditPlanV1", + "summary": "查看规则知识库", + "operationId": "getRuleKnowledgeV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule name", + "name": "rule_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "db type of rule", + "name": "db_type", "in": "path", "required": true } @@ -5142,95 +4801,115 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.StatisticAuditPlanResV1" + "$ref": "#/definitions/v1.GetRuleKnowledgeResV1" } } } - } - }, - "/v1/projects/{project_name}/statistic/audited_sqls": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "statistics audited sql", + "description": "update rule knowledge", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取审核SQL总数,以及触发审核规则的SQL数量", - "operationId": "statisticsAuditedSQLV1", + "summary": "更新规则知识库", + "operationId": "updateRuleKnowledge", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule name", + "name": "rule_name", "in": "path", "required": true + }, + { + "type": "string", + "description": "db type of rule", + "name": "db_type", + "in": "path", + "required": true + }, + { + "description": "update rule knowledge", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateRuleKnowledgeReq" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.StatisticsAuditedSQLResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/statistic/instance_health": { + "/v1/rule_template_tips": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance health", + "description": "get global rule template tips", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取各类型数据源的健康情况", - "operationId": "GetInstanceHealthV1", + "summary": "获取全局规则模板提示", + "operationId": "getRuleTemplateTipsV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "filter db type", + "name": "filter_db_type", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstanceHealthResV1" + "$ref": "#/definitions/v1.GetRuleTemplateTipsResV1" } } } } }, - "/v1/projects/{project_name}/statistic/project_score": { + "/v1/rule_templates": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get project score", + "description": "get all global rule template", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取项目分数", - "operationId": "GetProjectScoreV1", + "summary": "全局规则模板列表", + "operationId": "getRuleTemplateListV1", "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", "required": true } ], @@ -5238,63 +4917,69 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectScoreResV1" + "$ref": "#/definitions/v1.GetRuleTemplatesResV1" } } } - } - }, - "/v1/projects/{project_name}/statistic/risk_audit_plans": { - "get": { + }, + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get risk audit plan", + "description": "create a global rule template", + "consumes": [ + "application/json" + ], "tags": [ - "statistic" + "rule_template" ], - "summary": "获取扫描任务报告评分低于60的扫描任务", - "operationId": "getRiskAuditPlanV1", + "summary": "添加全局规则模板", + "operationId": "createRuleTemplateV1", "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "add rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.CreateRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRiskAuditPlanResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/statistic/risk_workflow": { - "get": { + "/v1/rule_templates/parse": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "statistic risk workflow", + "description": "parse rule template", + "consumes": [ + "multipart/form-data" + ], "tags": [ - "statistic" + "rule_template" ], - "summary": "获取存在风险的工单", - "operationId": "statisticRiskWorkflowV1", + "summary": "解析规则模板文件", + "operationId": "importProjectRuleTemplateV1", "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "type": "file", + "description": "SQLE rule template file", + "name": "rule_template_file", + "in": "formData", "required": true } ], @@ -5302,62 +4987,66 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.StatisticRiskWorkflowResV1" + "$ref": "#/definitions/v1.ParseProjectRuleTemplateFileResV1" } } } } }, - "/v1/projects/{project_name}/statistic/role_user": { + "/v1/rule_templates/{rule_template_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get role user count", + "description": "get global rule template", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取各角色类型对应的成员数量", - "operationId": "getRoleUserCountV1", + "summary": "获取全局规则模板信息", + "operationId": "getRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true + }, + { + "type": "string", + "description": "fuzzy rule,keyword for desc and annotation", + "name": "fuzzy_keyword_rule", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRoleUserCountResV1" + "$ref": "#/definitions/v1.GetRuleTemplateResV1" } } } - } - }, - "/v1/projects/{project_name}/statistic/workflow_status": { - "get": { + }, + "delete": { "security": [ { "ApiKeyAuth": [] } ], - "description": "statistic workflow status", + "description": "delete global rule template", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取项目下工单各个状态的数量", - "operationId": "statisticWorkflowStatusV1", + "summary": "删除全局规则模板", + "operationId": "deleteRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true } @@ -5366,78 +5055,82 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowStatusCountResV1" + "$ref": "#/definitions/controller.BaseRes" } } } - } - }, - "/v1/projects/{project_name}/statistics": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get project statistics", + "description": "update global rule template", "tags": [ - "statistic" + "rule_template" ], - "summary": "获取项目统计信息", - "operationId": "getProjectStatisticsV1", + "summary": "更新全局规则模板", + "operationId": "updateRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true + }, + { + "description": "update rule template request", + "name": "req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v1.UpdateRuleTemplateReqV1" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetProjectStatisticsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/task_groups": { + "/v1/rule_templates/{rule_template_name}/clone": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create tasks group.", + "description": "clone a rule template", "consumes": [ "application/json" ], - "produces": [ - "application/json" - ], "tags": [ - "task" + "rule_template" ], - "summary": "创建审核任务组", - "operationId": "createAuditTasksV1", + "summary": "克隆全局规则模板", + "operationId": "CloneRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true }, { - "description": "parameters for creating audit tasks group", + "description": "clone rule template request", "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateAuditTasksGroupReqV1" + "$ref": "#/definitions/v1.CloneRuleTemplateReqV1" } } ], @@ -5445,189 +5138,166 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.CreateAuditTasksGroupResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/projects/{project_name}/tasks/audits": { - "post": { + "/v1/rule_templates/{rule_template_name}/export": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create and audit a task, you can upload sql content in three ways, any one can be used, but only one is effective.\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.", - "consumes": [ - "multipart/form-data" - ], - "produces": [ - "application/json" - ], + "description": "export rule template", "tags": [ - "task" + "rule_template" ], - "summary": "创建Sql扫描任务并提交审核", - "operationId": "createAndAuditTaskV1", + "summary": "导出全局规则模板", + "operationId": "exportRuleTemplateV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", + "description": "rule template name", + "name": "rule_template_name", "in": "path", "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "formData", - "required": true - }, - { - "type": "string", - "description": "schema of instance", - "name": "instance_schema", - "in": "formData" - }, - { - "type": "string", - "description": "sqls for audit", - "name": "sql", - "in": "formData" - }, - { - "type": "file", - "description": "input SQL file", - "name": "input_sql_file", - "in": "formData" - }, - { - "type": "file", - "description": "input mybatis XML file", - "name": "input_mybatis_xml_file", - "in": "formData" - }, - { - "type": "file", - "description": "input ZIP file", - "name": "input_zip_file", - "in": "formData" } ], "responses": { "200": { - "description": "OK", + "description": "sqle rule template file", "schema": { - "$ref": "#/definitions/v1.GetAuditTaskResV1" + "type": "file" } } } } }, - "/v1/projects/{project_name}/unarchive": { - "post": { + "/v1/rules": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "archive project", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get all rule template", "tags": [ - "project" + "rule_template" ], - "summary": "取消归档项目", - "operationId": "unarchiveProjectV1", + "summary": "规则列表", + "operationId": "getRuleListV1", "parameters": [ { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { + "description": "filter db type", + "name": "filter_db_type", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy rule,keyword for desc and annotation", + "name": "fuzzy_keyword_rule", + "in": "query" + }, + { + "type": "string", + "description": "filter global rule template name", + "name": "filter_global_rule_template_name", + "in": "query" + }, + { + "type": "string", + "description": "filter rule name list", + "name": "filter_rule_names", + "in": "query" + } + ], + "responses": { + "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetRulesResV1" } } } } }, - "/v1/projects/{project_name}/workflow_template": { + "/v1/sql_analysis": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow template detail", + "description": "Direct get sql analysis result", "tags": [ - "workflow" + "sql_analysis" ], - "summary": "获取审批流程模板详情", - "operationId": "getWorkflowTemplateV1", + "summary": "直接获取SQL分析结果", + "operationId": "directGetSQLAnalysisV1", "parameters": [ { "type": "string", "description": "project name", "name": "project_name", - "in": "path", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "instance name", + "name": "instance_name", + "in": "query", "required": true + }, + { + "type": "string", + "description": "schema name", + "name": "schema_name", + "in": "query" + }, + { + "type": "string", + "description": "sql", + "name": "sql", + "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowTemplateResV1" + "$ref": "#/definitions/v1.DirectGetSQLAnalysisResV1" } } } - }, - "patch": { + } + }, + "/v1/sql_audit": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update the workflow template", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "Direct audit sql", "tags": [ - "workflow" + "sql_audit" ], - "summary": "更新Sql审批流程模板", - "operationId": "updateWorkflowTemplateV1", + "summary": "直接审核SQL", + "operationId": "directAuditV1", + "deprecated": true, "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "create workflow template", - "name": "instance", + "description": "sqls that should be audited", + "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateWorkflowTemplateReqV1" + "$ref": "#/definitions/v1.DirectAuditReqV1" } } ], @@ -5635,166 +5305,63 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.DirectAuditResV1" } } } } }, - "/v1/projects/{project_name}/workflows": { + "/v1/statistic/instances/sql_average_execution_time": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow list", + "description": "get average execution time of sql", "tags": [ - "workflow" + "statistic" ], - "summary": "获取工单列表", - "operationId": "getWorkflowsV1", + "summary": "获取sql上线平均耗时,按平均耗时降序排列", + "operationId": "getSqlAverageExecutionTimeV1", "parameters": [ - { - "type": "string", - "description": "filter subject", - "name": "filter_subject", - "in": "query" - }, - { - "type": "string", - "description": "filter by workflow_id", - "name": "filter_workflow_id", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search by workflow description", - "name": "fuzzy_search_workflow_desc", - "in": "query" - }, - { - "type": "string", - "description": "filter create time from", - "name": "filter_create_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter create time to", - "name": "filter_create_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_from", - "name": "filter_task_execute_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_to", - "name": "filter_task_execute_start_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter create user name", - "name": "filter_create_user_name", - "in": "query" - }, - { - "enum": [ - "wait_for_audit", - "wait_for_execution", - "rejected", - "executing", - "canceled", - "exec_failed", - "finished" - ], - "type": "string", - "description": "filter workflow status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "filter current step assignee user name", - "name": "filter_current_step_assignee_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_task_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, { "type": "integer", - "description": "size of per page", - "name": "page_size", + "description": "the limit of result item number", + "name": "limit", "in": "query", "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowsResV1" + "$ref": "#/definitions/v1.GetSqlAverageExecutionTimeResV1" } } } - }, - "post": { + } + }, + "/v1/statistic/instances/sql_execution_fail_percent": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create workflow", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get sql execution fail percent", "tags": [ - "workflow" + "statistic" ], - "summary": "创建工单", - "operationId": "createWorkflowV1", - "deprecated": true, + "summary": "获取SQL上线失败率,按失败率降序排列", + "operationId": "getSqlExecutionFailPercentV1", "parameters": [ { - "description": "create workflow request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateWorkflowReqV1" - } - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "type": "integer", + "description": "the limit of result item number", + "name": "limit", + "in": "query", "required": true } ], @@ -5802,309 +5369,177 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetSqlExecutionFailPercentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/cancel": { - "post": { + "/v1/statistic/instances/type_percent": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "batch cancel workflows", + "description": "get database instances' types percent", "tags": [ - "workflow" - ], - "summary": "批量取消工单", - "operationId": "batchCancelWorkflowsV1", - "deprecated": true, - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "batch cancel workflows request", - "name": "BatchCancelWorkflowsReqV1", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.BatchCancelWorkflowsReqV1" - } - } + "statistic" ], + "summary": "获取数据源类型百分比", + "operationId": "getInstancesTypePercentV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetInstancesTypePercentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/complete": { - "post": { + "/v1/statistic/license/usage": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "this api will directly change the work order status to finished without real online operation", + "description": "get usage of license", "tags": [ - "workflow" + "statistic" ], - "summary": "批量完成工单", - "operationId": "batchCompleteWorkflowsV1", - "deprecated": true, - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "batch complete workflows request", - "name": "data", - "in": "body", - "required": true, + "summary": "获取License使用情况", + "operationId": "getLicenseUsageV1", + "responses": { + "200": { + "description": "OK", "schema": { - "$ref": "#/definitions/v1.BatchCompleteWorkflowsReqV1" + "$ref": "#/definitions/v1.GetLicenseUsageResV1" } } + } + } + }, + "/v1/statistic/workflows/audit_pass_percent": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "get workflow audit pass percent", + "tags": [ + "statistic" ], + "summary": "获取工单审核通过率", + "operationId": "getWorkflowAuditPassPercentV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowAuditPassPercentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/exports": { + "/v1/statistic/workflows/counts": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export workflow", + "description": "get workflow counts", "tags": [ - "workflow" - ], - "summary": "导出工单", - "operationId": "exportWorkflowV1", - "parameters": [ - { - "type": "string", - "description": "filter subject", - "name": "filter_subject", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search by workflow description", - "name": "fuzzy_search_workflow_desc", - "in": "query" - }, - { - "type": "string", - "description": "filter create time from", - "name": "filter_create_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter create time to", - "name": "filter_create_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_from", - "name": "filter_task_execute_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_to", - "name": "filter_task_execute_start_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter create user name", - "name": "filter_create_user_name", - "in": "query" - }, - { - "enum": [ - "wait_for_audit", - "wait_for_execution", - "rejected", - "executing", - "canceled", - "exec_failed", - "finished" - ], - "type": "string", - "description": "filter workflow status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "filter current step assignee user name", - "name": "filter_current_step_assignee_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_task_instance_name", - "in": "query" - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } + "statistic" ], + "summary": "获取工单数量统计数据", + "operationId": "getWorkflowCountV1", "responses": { "200": { - "description": "export workflow", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/v1.GetWorkflowCountsResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_id}/tasks/terminate": { - "post": { + "/v1/statistic/workflows/duration_of_waiting_for_audit": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "terminate multiple task by project and workflow", + "description": "get duration from workflow being created to audited", "tags": [ - "workflow" - ], - "summary": "终止工单下多个上线任务", - "operationId": "terminateMultipleTaskByWorkflowV1", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } + "statistic" ], + "summary": "获取工单从创建到审核结束的平均时长", + "operationId": "getWorkflowDurationOfWaitingForAuditV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowDurationOfWaitingForAuditResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/terminate": { - "post": { + "/v1/statistic/workflows/duration_of_waiting_for_execution": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "execute one task on workflow", + "description": "get duration from workflow being created to executed", "tags": [ - "workflow" - ], - "summary": "终止单个上线任务", - "operationId": "terminateSingleTaskByWorkflowV1", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } + "statistic" ], + "summary": "获取工单各从审核完毕到执行上线的平均时长", + "operationId": "getWorkflowDurationOfWaitingForExecutionV1", + "deprecated": true, "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowDurationOfWaitingForExecutionResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/": { + "/v1/statistic/workflows/each_day_counts": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow detail", + "description": "get counts of created workflow each day", "tags": [ - "workflow" + "statistic" ], - "summary": "获取工单详情", - "operationId": "getWorkflowV1", - "deprecated": true, + "summary": "获取每天工单创建数量", + "operationId": "getWorkflowCreatedCountEachDayV1", "parameters": [ { "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", + "description": "filter date from.(format:yyyy-mm-dd)", + "name": "filter_date_from", + "in": "query", "required": true }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", + "description": "filter date to.(format:yyyy-mm-dd)", + "name": "filter_date_to", + "in": "query", "required": true } ], @@ -6112,92 +5547,78 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowResV1" + "$ref": "#/definitions/v1.GetWorkflowCreatedCountsEachDayResV1" } } } - }, - "patch": { + } + }, + "/v1/statistic/workflows/instance_type_percent": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update workflow when it is rejected to creator.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get workflows percent counted by instance type", "tags": [ - "workflow" + "statistic" ], - "summary": "更新工单(驳回后才可更新)", - "operationId": "updateWorkflowV1", - "deprecated": true, - "parameters": [ - { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "update workflow request", - "name": "instance", - "in": "body", - "required": true, + "summary": "获取按数据源类型统计的工单百分比", + "operationId": "getWorkflowPercentCountedByInstanceTypeV1", + "responses": { + "200": { + "description": "OK", "schema": { - "$ref": "#/definitions/v1.UpdateWorkflowReqV1" + "$ref": "#/definitions/v1.GetWorkflowPercentCountedByInstanceTypeResV1" } } + } + } + }, + "/v1/statistic/workflows/pass_percent": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } ], + "description": "get workflow pass percent", + "tags": [ + "statistic" + ], + "summary": "获取工单通过率", + "operationId": "getWorkflowPassPercentV1", + "deprecated": true, "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowPassPercentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/cancel": { - "post": { + "/v1/statistic/workflows/rejected_percent_group_by_creator": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "cancel workflow", + "description": "get workflows rejected percent group by creator. The result will be sorted by rejected percent in descending order", "tags": [ - "workflow" + "statistic" ], - "summary": "审批关闭(中止)", - "operationId": "cancelWorkflowV1", - "deprecated": true, + "summary": "获取各个用户提交的工单驳回率,按驳回率降序排列", + "operationId": "getWorkflowRejectedPercentGroupByCreatorV1", "parameters": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", + "type": "integer", + "description": "the limit of result item number", + "name": "limit", + "in": "query", "required": true } ], @@ -6205,141 +5626,148 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowRejectedPercentGroupByCreatorResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/approve": { - "post": { + "/v1/statistic/workflows/rejected_percent_group_by_instance": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "approve workflow", + "description": "get workflow rejected percent group by instance. The result will be sorted by rejected percent in descending order", "tags": [ - "workflow" + "statistic" ], - "summary": "审批通过", - "operationId": "approveWorkflowV1", + "summary": "获取各个数据源相关的工单驳回率,按驳回率降序排列", + "operationId": "getWorkflowRejectedPercentGroupByInstanceV1", "deprecated": true, "parameters": [ { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow step id", - "name": "workflow_step_id", - "in": "path", + "type": "integer", + "description": "the limit of result item number", + "name": "limit", + "in": "query", "required": true - }, + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/v1.GetWorkflowRejectedPercentGroupByInstanceResV1" + } + } + } + } + }, + "/v1/statistic/workflows/status_count": { + "get": { + "security": [ { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "ApiKeyAuth": [] } ], + "description": "get count of workflow status", + "tags": [ + "statistic" + ], + "summary": "获取各种状态工单的数量", + "operationId": "getWorkflowStatusCountV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetWorkflowStatusCountResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/reject": { + "/v1/task_groups/audit": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "reject workflow", + "description": "audit task group.\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.\n4. file[input_zip_file]: it is zip file, sql will be parsed from it.", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], "tags": [ - "workflow" + "task" ], - "summary": "审批驳回", - "operationId": "rejectWorkflowV1", - "deprecated": true, + "summary": "审核任务组", + "operationId": "auditTaskGroupIdV1", "parameters": [ { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", + "type": "integer", + "description": "group id of tasks", + "name": "task_group_id", + "in": "formData", "required": true }, { "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true + "description": "sqls for audit", + "name": "sql", + "in": "formData" }, { - "type": "string", - "description": "workflow step id", - "name": "workflow_step_id", - "in": "path", - "required": true + "type": "file", + "description": "input SQL file", + "name": "input_sql_file", + "in": "formData" }, { - "description": "workflow approve request", - "name": "workflow_approve", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.RejectWorkflowReqV1" - } + "type": "file", + "description": "input mybatis XML file", + "name": "input_mybatis_xml_file", + "in": "formData" + }, + { + "type": "file", + "description": "input ZIP file", + "name": "input_zip_file", + "in": "formData" } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.AuditTaskGroupResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/tasks": { + "/v1/tasks/audits/{task_id}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get summary of workflow instance tasks", + "description": "get task", "tags": [ - "workflow" + "task" ], - "summary": "获取工单数据源任务概览", - "operationId": "getSummaryOfInstanceTasksV1", - "deprecated": true, + "summary": "获取Sql扫描任务信息", + "operationId": "getAuditTaskV1", "parameters": [ { "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", + "description": "task id", + "name": "task_id", "in": "path", "required": true } @@ -6348,38 +5776,30 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowTasksResV1" + "$ref": "#/definitions/v1.GetAuditTaskResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/execute": { - "post": { + "/v1/tasks/audits/{task_id}/sql_content": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "execute tasks on workflow", + "description": "get SQL content for the audit task", "tags": [ - "workflow" + "task" ], - "summary": "多数据源批量上线", - "operationId": "executeTasksOnWorkflowV1", - "deprecated": true, + "summary": "获取指定扫描任务的SQL内容", + "operationId": "getAuditTaskSQLContentV1", "parameters": [ { "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", + "description": "task id", + "name": "task_id", "in": "path", "required": true } @@ -6388,41 +5808,26 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetAuditTaskSQLContentResV1" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/execute": { - "post": { + "/v1/tasks/audits/{task_id}/sql_file": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "execute one task on workflow", + "description": "download SQL file for the audit task", "tags": [ - "workflow" + "task" ], - "summary": "工单提交单个数据源上线", - "operationId": "executeOneTaskOnWorkflowV1", - "deprecated": true, + "summary": "下载指定扫描任务的SQL文件", + "operationId": "downloadAuditTaskSQLFileV1", "parameters": [ - { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, { "type": "string", "description": "task id", @@ -6433,42 +5838,28 @@ ], "responses": { "200": { - "description": "OK", + "description": "sql file", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "type": "file" } } } } }, - "/v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/schedule": { - "put": { + "/v1/tasks/audits/{task_id}/sql_report": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update workflow schedule.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "download report file of all SQLs information belong to the specified audit task", "tags": [ - "workflow" + "task" ], - "summary": "设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置)", - "operationId": "updateWorkflowScheduleV1", - "deprecated": true, + "summary": "下载指定扫描任务的SQLs信息报告", + "operationId": "downloadAuditTaskSQLReportV1", "parameters": [ - { - "type": "string", - "description": "workflow name", - "name": "workflow_name", - "in": "path", - "required": true - }, { "type": "string", "description": "task id", @@ -6477,91 +5868,95 @@ "required": true }, { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "update workflow schedule request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateWorkflowScheduleReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/role_tips": { - "get": { - "security": [ - { - "ApiKeyAuth": [] + "type": "boolean", + "description": "select unique (fingerprint and audit result) for task sql", + "name": "no_duplicate", + "in": "query" } ], - "description": "get role tip list", - "tags": [ - "role" - ], - "summary": "获取角色提示列表", - "operationId": "getRoleTipListV1", "responses": { "200": { - "description": "OK", + "description": "sql report csv file", "schema": { - "$ref": "#/definitions/v1.GetRoleTipsResV1" + "type": "file" } } } } }, - "/v1/roles": { + "/v1/tasks/audits/{task_id}/sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get role list", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get information of all SQLs belong to the specified audit task", "tags": [ - "role" + "task" ], - "summary": "获取角色列表", - "operationId": "getRoleListV1", + "summary": "获取指定扫描任务的SQLs信息", + "operationId": "getAuditTaskSQLsV1", "parameters": [ { "type": "string", - "description": "filter role name", - "name": "filter_role_name", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "enum": [ + "initialized", + "doing", + "succeeded", + "failed", + "manually_executed" + ], + "type": "string", + "description": "filter: exec status of task sql", + "name": "filter_exec_status", + "in": "query" + }, + { + "enum": [ + "initialized", + "doing", + "finished" + ], + "type": "string", + "description": "filter: audit status of task sql", + "name": "filter_audit_status", "in": "query" }, { - "type": "integer", + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "type": "string", + "description": "filter: audit level of task sql", + "name": "filter_audit_level", + "in": "query" + }, + { + "type": "boolean", + "description": "select unique (fingerprint and audit result) for task sql", + "name": "no_duplicate", + "in": "query" + }, + { + "type": "string", "description": "page index", "name": "page_index", "in": "query", "required": true }, { - "type": "integer", - "description": "size of per page", + "type": "string", + "description": "page size", "name": "page_size", "in": "query", "required": true @@ -6571,37 +5966,50 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRolesResV1" + "$ref": "#/definitions/v1.GetAuditTaskSQLsResV1" } } } - }, - "post": { + } + }, + "/v1/tasks/audits/{task_id}/sqls/{number}": { + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create role", + "description": "modify the relevant information of a certain SQL in the audit task", "consumes": [ "application/json" ], - "produces": [ - "application/json" - ], "tags": [ - "role" + "task" ], - "summary": "创建角色", - "operationId": "createRoleV1", + "summary": "修改扫描任务中某条SQL的相关信息", + "operationId": "updateAuditTaskSQLsV1", "parameters": [ { - "description": "create role", - "name": "instance", + "type": "string", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "sql number", + "name": "number", + "in": "path", + "required": true + }, + { + "description": "modify the relevant information of a certain SQL in the audit task", + "name": "audit_plan", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateRoleReqV1" + "$ref": "#/definitions/v1.UpdateAuditTaskSQLsReqV1" } } ], @@ -6615,30 +6023,31 @@ } } }, - "/v1/roles/{role_name}/": { - "delete": { + "/v1/tasks/audits/{task_id}/sqls/{number}/analysis": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete role", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get SQL explain and related table metadata for analysis", "tags": [ - "role" + "task" ], - "summary": "删除角色", - "operationId": "deleteRoleV1", + "summary": "获取task相关的SQL执行计划和表元数据", + "operationId": "getTaskAnalysisData", "parameters": [ { "type": "string", - "description": "role name", - "name": "role_name", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "sql number", + "name": "number", "in": "path", "required": true } @@ -6647,129 +6056,167 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetTaskAnalysisDataResV1" } } } - }, - "patch": { + } + }, + "/v1/user_tips": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update role", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], + "description": "get user tip list", "tags": [ - "role" + "user" ], - "summary": "更新角色信息", - "operationId": "updateRoleV1", + "summary": "获取用户提示列表", + "operationId": "getUserTipListV1", "parameters": [ { "type": "string", - "description": "role name", - "name": "role_name", - "in": "path", + "description": "project name", + "name": "filter_project", + "in": "query", "required": true - }, - { - "description": "update role request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateRoleReqV1" - } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v1.GetUserTipsResV1" } } } } }, - "/v1/rule_knowledge/db_types/{db_type}/custom_rules/{rule_name}/": { + "/v1/workflows": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get custom rule knowledge", + "description": "get global workflow list", "tags": [ - "rule_template" + "workflow" ], - "summary": "查看自定义规则知识库", - "operationId": "getCustomRuleKnowledgeV1", + "summary": "获取全局工单列表", + "operationId": "getGlobalWorkflowsV1", "parameters": [ { "type": "string", - "description": "rule name", - "name": "rule_name", - "in": "path", - "required": true + "description": "filter subject", + "name": "filter_subject", + "in": "query" }, { "type": "string", - "description": "db type of rule", - "name": "db_type", - "in": "path", - "required": true - } - ], + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter create time to", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_from", + "name": "filter_task_execute_start_time_from", + "in": "query" + }, + { + "type": "string", + "description": "filter_task_execute_start_time_to", + "name": "filter_task_execute_start_time_to", + "in": "query" + }, + { + "type": "string", + "description": "filter create user id", + "name": "filter_create_user_id", + "in": "query" + }, + { + "enum": [ + "wait_for_audit", + "wait_for_execution", + "rejected", + "executing", + "canceled", + "exec_failed", + "finished" + ], + "type": "string", + "description": "filter workflow status", + "name": "filter_status", + "in": "query" + }, + { + "type": "string", + "description": "filter current step assignee user id", + "name": "filter_current_step_assignee_user_id", + "in": "query" + }, + { + "type": "string", + "description": "filter instance id", + "name": "filter_task_instance_name", + "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true + } + ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleKnowledgeResV1" + "$ref": "#/definitions/v1.GetWorkflowsResV1" } } } - }, - "patch": { + } + }, + "/v2/audit_files": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update custom rule knowledge", + "description": "Direct audit sql from SQL files and MyBatis files", "tags": [ - "rule_template" + "sql_audit" ], - "summary": "更新自定义规则知识库", - "operationId": "updateCustomRuleKnowledge", + "summary": "直接从文件内容提取SQL并审核,SQL文件暂时只支持一次解析一个文件", + "operationId": "directAuditFilesV2", "parameters": [ { - "type": "string", - "description": "rule name", - "name": "rule_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "db type of rule", - "name": "db_type", - "in": "path", - "required": true - }, - { - "description": "update rule knowledge", + "description": "files that should be audited", "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateRuleKnowledgeReq" + "$ref": "#/definitions/v2.DirectAuditFileReqV2" } } ], @@ -6777,142 +6224,140 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v2.DirectAuditResV2" } } } } }, - "/v1/rule_knowledge/db_types/{db_type}/rules/{rule_name}/": { + "/v2/configurations/drivers": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get rule knowledge", + "description": "get drivers", "tags": [ - "rule_template" - ], - "summary": "查看规则知识库", - "operationId": "getRuleKnowledgeV1", - "parameters": [ - { - "type": "string", - "description": "rule name", - "name": "rule_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "db type of rule", - "name": "db_type", - "in": "path", - "required": true - } + "configuration" ], + "summary": "获取当前 server 支持的审核类型", + "operationId": "getDriversV2", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleKnowledgeResV1" + "$ref": "#/definitions/v2.GetDriversRes" } } } - }, - "patch": { + } + }, + "/v2/projects/{project_name}/audit_plans": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "update rule knowledge", + "description": "get audit plan info list", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "更新规则知识库", - "operationId": "updateRuleKnowledge", + "summary": "获取扫描任务信息列表", + "operationId": "getAuditPlansV2", "parameters": [ { "type": "string", - "description": "rule name", - "name": "rule_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true }, { "type": "string", - "description": "db type of rule", - "name": "db_type", - "in": "path", - "required": true + "description": "filter audit plan db type", + "name": "filter_audit_plan_db_type", + "in": "query" }, { - "description": "update rule knowledge", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateRuleKnowledgeReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/rule_template_tips": { - "get": { - "security": [ + "type": "string", + "description": "fuzzy search audit plan name", + "name": "fuzzy_search_audit_plan_name", + "in": "query" + }, { - "ApiKeyAuth": [] - } - ], - "description": "get global rule template tips", - "tags": [ - "rule_template" - ], - "summary": "获取全局规则模板提示", - "operationId": "getRuleTemplateTipsV1", - "parameters": [ + "type": "string", + "description": "filter audit plan type", + "name": "filter_audit_plan_type", + "in": "query" + }, { "type": "string", - "description": "filter db type", - "name": "filter_db_type", + "description": "filter audit plan instance name", + "name": "filter_audit_plan_instance_name", "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleTemplateTipsResV1" + "$ref": "#/definitions/v2.GetAuditPlansResV2" } } } } }, - "/v1/rule_templates": { + "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get all global rule template", + "description": "get audit plan report SQLs", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "全局规则模板列表", - "operationId": "getRuleTemplateListV1", + "summary": "获取指定扫描任务的SQL扫描详情", + "operationId": "getAuditPlanReportsSQLs", "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + }, { "type": "integer", "description": "page index", @@ -6932,100 +6377,51 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleTemplatesResV1" + "$ref": "#/definitions/v2.GetAuditPlanReportSQLsResV2" } } } - }, - "post": { + } + }, + "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis": { + "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create a global rule template", - "consumes": [ - "application/json" - ], + "description": "get SQL explain and related table metadata for analysis", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "添加全局规则模板", - "operationId": "createRuleTemplateV1", + "summary": "获取task相关的SQL执行计划和表元数据", + "operationId": "getAuditPlantAnalysisDataV2", "parameters": [ { - "description": "add rule template request", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateRuleTemplateReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/rule_templates/parse": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "parse rule template", - "consumes": [ - "multipart/form-data" - ], - "tags": [ - "rule_template" - ], - "summary": "解析规则模板文件", - "operationId": "importProjectRuleTemplateV1", - "parameters": [ + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, { - "type": "file", - "description": "SQLE rule template file", - "name": "rule_template_file", - "in": "formData", + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.ParseProjectRuleTemplateFileResV1" - } - } - } - } - }, - "/v1/rule_templates/{rule_template_name}/": { - "get": { - "security": [ + }, { - "ApiKeyAuth": [] - } - ], - "description": "get global rule template", - "tags": [ - "rule_template" - ], - "summary": "获取全局规则模板信息", - "operationId": "getRuleTemplateV1", - "parameters": [ + "type": "string", + "description": "audit plan report id", + "name": "audit_plan_report_id", + "in": "path", + "required": true + }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "sql number", + "name": "number", "in": "path", "required": true } @@ -7034,68 +6430,47 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRuleTemplateResV1" + "$ref": "#/definitions/v2.GetAuditPlanAnalysisDataResV2" } } } - }, - "delete": { + } + }, + "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "delete global rule template", + "description": "full sync audit plan SQLs", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "删除全局规则模板", - "operationId": "deleteRuleTemplateV1", + "summary": "全量同步SQL到扫描任务", + "operationId": "fullSyncAuditPlanSQLsV2", "parameters": [ { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update global rule template", - "tags": [ - "rule_template" - ], - "summary": "更新全局规则模板", - "operationId": "updateRuleTemplateV1", - "parameters": [ + }, { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "audit plan name", + "name": "audit_plan_name", "in": "path", "required": true }, { - "description": "update rule template request", - "name": "req", + "description": "full sync audit plan SQLs request", + "name": "sqls", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.UpdateRuleTemplateReqV1" + "$ref": "#/definitions/v2.FullSyncAuditPlanSQLsReqV2" } } ], @@ -7109,37 +6484,41 @@ } } }, - "/v1/rule_templates/{rule_template_name}/clone": { + "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "clone a rule template", - "consumes": [ - "application/json" - ], + "description": "partial sync audit plan SQLs", "tags": [ - "rule_template" + "audit_plan" ], - "summary": "克隆全局规则模板", - "operationId": "CloneRuleTemplateV1", + "summary": "增量同步SQL到扫描任务", + "operationId": "partialSyncAuditPlanSQLsV2", "parameters": [ { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true }, { - "description": "clone rule template request", - "name": "req", + "type": "string", + "description": "audit plan name", + "name": "audit_plan_name", + "in": "path", + "required": true + }, + { + "description": "partial sync audit plan SQLs request", + "name": "sqls", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CloneRuleTemplateReqV1" + "$ref": "#/definitions/v2.PartialSyncAuditPlanSQLsReqV2" } } ], @@ -7153,276 +6532,355 @@ } } }, - "/v1/rule_templates/{rule_template_name}/export": { + "/v2/projects/{project_name}/instances/{instance_name}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "export rule template", + "description": "get instance db", "tags": [ - "rule_template" + "instance" ], - "summary": "导出全局规则模板", - "operationId": "exportRuleTemplateV1", + "summary": "获取实例信息", + "operationId": "getInstanceV2", "parameters": [ { "type": "string", - "description": "rule template name", - "name": "rule_template_name", + "description": "project name", + "name": "project_name", "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "sqle rule template file", - "schema": { - "type": "file" - } - } - } - } - }, - "/v1/rules": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get all rule template", - "tags": [ - "rule_template" - ], - "summary": "规则列表", - "operationId": "getRuleListV1", - "parameters": [ - { - "type": "string", - "description": "filter db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "filter global rule template name", - "name": "filter_global_rule_template_name", - "in": "query" }, { "type": "string", - "description": "filter rule name list", - "name": "filter_rule_names", - "in": "query" + "description": "instance name", + "name": "instance_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetRulesResV1" + "$ref": "#/definitions/v2.GetInstanceResV2" } } } } }, - "/v1/sql_analysis": { + "/v2/projects/{project_name}/sql_manages": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Direct get sql analysis result", + "description": "get sql manage list", "tags": [ - "sql_analysis" + "SqlManage" ], - "summary": "直接获取SQL分析结果", - "operationId": "directGetSQLAnalysisV1", + "summary": "获取管控sql列表", + "operationId": "GetSqlManageListV2", "parameters": [ { "type": "string", "description": "project name", "name": "project_name", - "in": "query", + "in": "path", "required": true }, { "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "query", - "required": true + "description": "fuzzy search sql fingerprint", + "name": "fuzzy_search_sql_fingerprint", + "in": "query" }, { "type": "string", - "description": "schema name", - "name": "schema_name", + "description": "assignee", + "name": "filter_assignee", "in": "query" }, { "type": "string", - "description": "sql", - "name": "sql", + "description": "instance name", + "name": "filter_instance_name", + "in": "query" + }, + { + "enum": [ + "audit_plan", + "sql_audit_record" + ], + "type": "string", + "description": "source", + "name": "filter_source", + "in": "query" + }, + { + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "type": "string", + "description": "audit level", + "name": "filter_audit_level", + "in": "query" + }, + { + "type": "string", + "description": "last audit start time from", + "name": "filter_last_audit_start_time_from", + "in": "query" + }, + { + "type": "string", + "description": "last audit start time to", + "name": "filter_last_audit_start_time_to", + "in": "query" + }, + { + "enum": [ + "unhandled", + "solved", + "ignored", + "manual_audited" + ], + "type": "string", + "description": "status", + "name": "filter_status", + "in": "query" + }, + { + "type": "string", + "description": "rule name", + "name": "filter_rule_name", "in": "query" + }, + { + "type": "string", + "description": "db type", + "name": "filter_db_type", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search endpoint", + "name": "fuzzy_search_endpoint", + "in": "query" + }, + { + "type": "string", + "description": "fuzzy search schema name", + "name": "fuzzy_search_schema_name", + "in": "query" + }, + { + "enum": [ + "first_appear_timestamp", + "last_receive_timestamp", + "fp_count" + ], + "type": "string", + "description": "sort field", + "name": "sort_field", + "in": "query" + }, + { + "enum": [ + "asc", + "desc" + ], + "type": "string", + "description": "sort order", + "name": "sort_order", + "in": "query" + }, + { + "type": "integer", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "size of per page", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.DirectGetSQLAnalysisResV1" + "$ref": "#/definitions/v2.GetSqlManageListResp" } } } } }, - "/v1/sql_audit": { + "/v2/projects/{project_name}/workflows": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "Direct audit sql", + "description": "create workflow", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], "tags": [ - "sql_audit" + "workflow" ], - "summary": "直接审核SQL", - "operationId": "directAuditV1", - "deprecated": true, + "summary": "创建工单", + "operationId": "createWorkflowV2", "parameters": [ { - "description": "sqls that should be audited", - "name": "req", + "description": "create workflow request", + "name": "instance", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.DirectAuditReqV1" + "$ref": "#/definitions/v2.CreateWorkflowReqV2" } + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.DirectAuditResV1" + "$ref": "#/definitions/v2.CreateWorkflowResV2" } } } } }, - "/v1/static/instance_logo": { - "get": { + "/v2/projects/{project_name}/workflows/cancel": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get instance type logo", + "description": "batch cancel workflows", "tags": [ - "instance" + "workflow" ], - "summary": "获取实例类型logo", - "operationId": "getInstanceTypeLogo", + "summary": "批量取消工单", + "operationId": "batchCancelWorkflowsV2", "parameters": [ { "type": "string", - "description": "instance type", - "name": "instance_type", - "in": "query", + "description": "project name", + "name": "project_name", + "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "get instance type logo", + }, + { + "description": "batch cancel workflows request", + "name": "BatchCancelWorkflowsReqV2", + "in": "body", + "required": true, "schema": { - "type": "file" + "$ref": "#/definitions/v2.BatchCancelWorkflowsReqV2" } } - } - } - }, - "/v1/static/logo": { - "get": { - "description": "get logo", - "tags": [ - "configuration" - ], - "summary": "获取logo", - "operationId": "getLogo", - "parameters": [ - { - "type": "string", - "description": "timestamp", - "name": "timestamp", - "in": "query" - } ], "responses": { "200": { - "description": "get logo", + "description": "OK", "schema": { - "type": "file" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/instances/sql_average_execution_time": { - "get": { + "/v2/projects/{project_name}/workflows/complete": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get average execution time of sql", + "description": "this api will directly change the work order status to finished without real online operation", "tags": [ - "statistic" + "workflow" ], - "summary": "获取sql上线平均耗时,按平均耗时降序排列", - "operationId": "getSqlAverageExecutionTimeV1", + "summary": "批量完成工单", + "operationId": "batchCompleteWorkflowsV2", "parameters": [ { - "type": "integer", - "description": "the limit of result item number", - "name": "limit", - "in": "query", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", "required": true + }, + { + "description": "batch complete workflows request", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v2.BatchCompleteWorkflowsReqV2" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlAverageExecutionTimeResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/instances/sql_execution_fail_percent": { + "/v2/projects/{project_name}/workflows/{workflow_id}/": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sql execution fail percent", + "description": "get workflow detail", "tags": [ - "statistic" + "workflow" ], - "summary": "获取SQL上线失败率,按失败率降序排列", - "operationId": "getSqlExecutionFailPercentV1", + "summary": "获取工单详情", + "operationId": "getWorkflowV2", "parameters": [ { - "type": "integer", - "description": "the limit of result item number", - "name": "limit", - "in": "query", + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", "required": true } ], @@ -7430,177 +6888,315 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSqlExecutionFailPercentResV1" + "$ref": "#/definitions/v2.GetWorkflowResV2" } } } - } - }, - "/v1/statistic/instances/type_percent": { - "get": { + }, + "patch": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get database instances' types percent", - "tags": [ - "statistic" + "description": "update workflow when it is rejected to creator.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "workflow" + ], + "summary": "更新工单(驳回后才可更新)", + "operationId": "updateWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "description": "update workflow request", + "name": "instance", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v2.UpdateWorkflowReqV2" + } + } ], - "summary": "获取数据源类型百分比", - "operationId": "getInstancesTypePercentV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetInstancesTypePercentResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/license/usage": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/cancel": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get usage of license", + "description": "cancel workflow", "tags": [ - "statistic" + "workflow" + ], + "summary": "审批关闭(中止)", + "operationId": "cancelWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + } ], - "summary": "获取License使用情况", - "operationId": "getLicenseUsageV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetLicenseUsageResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/audit_pass_percent": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/approve": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow audit pass percent", + "description": "approve workflow", "tags": [ - "statistic" + "workflow" + ], + "summary": "审批通过", + "operationId": "approveWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "workflow step id", + "name": "workflow_step_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + } ], - "summary": "获取工单审核通过率", - "operationId": "getWorkflowAuditPassPercentV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowAuditPassPercentResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/counts": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/reject": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflow counts", + "description": "reject workflow", "tags": [ - "statistic" + "workflow" + ], + "summary": "审批驳回", + "operationId": "rejectWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "workflow step id", + "name": "workflow_step_id", + "in": "path", + "required": true + }, + { + "description": "workflow approve request", + "name": "workflow_approve", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/v2.RejectWorkflowReqV2" + } + } ], - "summary": "获取工单数量统计数据", - "operationId": "getWorkflowCountV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowCountsResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/duration_of_waiting_for_audit": { + "/v2/projects/{project_name}/workflows/{workflow_id}/tasks": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get duration from workflow being created to audited", + "description": "get summary of workflow instance tasks", "tags": [ - "statistic" + "workflow" + ], + "summary": "获取工单数据源任务概览", + "operationId": "getSummaryOfInstanceTasksV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + } ], - "summary": "获取工单从创建到审核结束的平均时长", - "operationId": "getWorkflowDurationOfWaitingForAuditV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowDurationOfWaitingForAuditResV1" + "$ref": "#/definitions/v2.GetWorkflowTasksResV2" } } } } }, - "/v1/statistic/workflows/duration_of_waiting_for_execution": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/execute": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get duration from workflow being created to executed", + "description": "execute tasks on workflow", "tags": [ - "statistic" + "workflow" + ], + "summary": "多数据源批量上线", + "operationId": "executeTasksOnWorkflowV2", + "parameters": [ + { + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + } ], - "summary": "获取工单各从审核完毕到执行上线的平均时长", - "operationId": "getWorkflowDurationOfWaitingForExecutionV1", - "deprecated": true, "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowDurationOfWaitingForExecutionResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/each_day_counts": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/execute": { + "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get counts of created workflow each day", + "description": "execute one task on workflow", "tags": [ - "statistic" + "workflow" ], - "summary": "获取每天工单创建数量", - "operationId": "getWorkflowCreatedCountEachDayV1", + "summary": "工单提交单个数据源上线", + "operationId": "executeOneTaskOnWorkflowV2", "parameters": [ { "type": "string", - "description": "filter date from.(format:yyyy-mm-dd)", - "name": "filter_date_from", - "in": "query", + "description": "workflow id", + "name": "workflow_id", + "in": "path", "required": true }, { "type": "string", - "description": "filter date to.(format:yyyy-mm-dd)", - "name": "filter_date_to", - "in": "query", + "description": "project name", + "name": "project_name", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "task id", + "name": "task_id", + "in": "path", "required": true } ], @@ -7608,192 +7204,95 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowCreatedCountsEachDayResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/statistic/workflows/instance_type_percent": { - "get": { + "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/schedule": { + "put": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get workflows percent counted by instance type", - "tags": [ - "statistic" + "description": "update workflow schedule.", + "consumes": [ + "application/json" ], - "summary": "获取按数据源类型统计的工单百分比", - "operationId": "getWorkflowPercentCountedByInstanceTypeV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetWorkflowPercentCountedByInstanceTypeResV1" - } - } - } - } - }, - "/v1/statistic/workflows/pass_percent": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get workflow pass percent", - "tags": [ - "statistic" - ], - "summary": "获取工单通过率", - "operationId": "getWorkflowPassPercentV1", - "deprecated": true, - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetWorkflowPassPercentResV1" - } - } - } - } - }, - "/v1/statistic/workflows/rejected_percent_group_by_creator": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } + "produces": [ + "application/json" ], - "description": "get workflows rejected percent group by creator. The result will be sorted by rejected percent in descending order", "tags": [ - "statistic" + "workflow" ], - "summary": "获取各个用户提交的工单驳回率,按驳回率降序排列", - "operationId": "getWorkflowRejectedPercentGroupByCreatorV1", + "summary": "设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置)", + "operationId": "updateWorkflowScheduleV2", "parameters": [ { - "type": "integer", - "description": "the limit of result item number", - "name": "limit", - "in": "query", + "type": "string", + "description": "workflow id", + "name": "workflow_id", + "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetWorkflowRejectedPercentGroupByCreatorResV1" - } - } - } - } - }, - "/v1/statistic/workflows/rejected_percent_group_by_instance": { - "get": { - "security": [ + }, { - "ApiKeyAuth": [] - } - ], - "description": "get workflow rejected percent group by instance. The result will be sorted by rejected percent in descending order", - "tags": [ - "statistic" - ], - "summary": "获取各个数据源相关的工单驳回率,按驳回率降序排列", - "operationId": "getWorkflowRejectedPercentGroupByInstanceV1", - "deprecated": true, - "parameters": [ + "type": "string", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, { - "type": "integer", - "description": "the limit of result item number", - "name": "limit", - "in": "query", + "type": "string", + "description": "project name", + "name": "project_name", + "in": "path", "required": true - } - ], - "responses": { - "200": { - "description": "OK", + }, + { + "description": "update workflow schedule request", + "name": "instance", + "in": "body", + "required": true, "schema": { - "$ref": "#/definitions/v1.GetWorkflowRejectedPercentGroupByInstanceResV1" + "$ref": "#/definitions/v2.UpdateWorkflowScheduleReqV2" } } - } - } - }, - "/v1/statistic/workflows/status_count": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get count of workflow status", - "tags": [ - "statistic" ], - "summary": "获取各种状态工单的数量", - "operationId": "getWorkflowStatusCountV1", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetWorkflowStatusCountResV1" + "$ref": "#/definitions/controller.BaseRes" } } } } }, - "/v1/sync_instances": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get sync instance task list", - "tags": [ - "sync_instance" - ], - "summary": "获取同步实例任务列表", - "operationId": "GetSyncInstanceTaskList", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetSyncInstanceTaskListResV1" - } - } - } - }, + "/v2/sql_audit": { "post": { "security": [ { "ApiKeyAuth": [] } ], - "description": "create sync instance task", - "consumes": [ - "application/json" - ], + "description": "Direct audit sql", "tags": [ - "sync_instance" + "sql_audit" ], - "summary": "创建同步实例任务", - "operationId": "createSyncInstanceTaskV1", + "summary": "直接审核SQL", + "operationId": "directAuditV2", + "deprecated": true, "parameters": [ { - "description": "create sync instance task request", - "name": "sync_task", + "description": "sqls that should be audited", + "name": "req", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/v1.CreateSyncInstanceTaskReqV1" + "$ref": "#/definitions/v2.DirectAuditReqV2" } } ], @@ -7801,4745 +7300,496 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/controller.BaseRes" + "$ref": "#/definitions/v2.DirectAuditResV2" } } } } }, - "/v1/sync_instances/source_tips": { + "/v2/tasks/audits/{task_id}/sqls": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sync task tips", + "description": "get information of all SQLs belong to the specified audit task", "tags": [ - "sync_instance" + "task" + ], + "summary": "获取指定扫描任务的SQLs信息", + "operationId": "getAuditTaskSQLsV2", + "parameters": [ + { + "type": "string", + "description": "task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "enum": [ + "initialized", + "doing", + "succeeded", + "failed", + "manually_executed", + "terminating", + "terminate_succeeded", + "terminate_failed" + ], + "type": "string", + "description": "filter: exec status of task sql", + "name": "filter_exec_status", + "in": "query" + }, + { + "enum": [ + "initialized", + "doing", + "finished" + ], + "type": "string", + "description": "filter: audit status of task sql", + "name": "filter_audit_status", + "in": "query" + }, + { + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "type": "string", + "description": "filter: audit level of task sql", + "name": "filter_audit_level", + "in": "query" + }, + { + "type": "boolean", + "description": "select unique (fingerprint and audit result) for task sql", + "name": "no_duplicate", + "in": "query" + }, + { + "type": "string", + "description": "page index", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "page size", + "name": "page_size", + "in": "query", + "required": true + } ], - "summary": "获取同步任务提示", - "operationId": "GetSyncTaskSourceTips", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSyncTaskSourceTipsResV1" + "$ref": "#/definitions/v2.GetAuditTaskSQLsResV2" } } } } }, - "/v1/sync_instances/{task_id}/": { + "/v2/tasks/audits/{task_id}/sqls/{number}/analysis": { "get": { "security": [ { "ApiKeyAuth": [] } ], - "description": "get sync task detail", + "description": "get SQL explain and related table metadata for analysis", "tags": [ - "sync_instance" + "task" ], - "summary": "获取同步任务详情", - "operationId": "GetSyncInstanceTask", + "summary": "获取task相关的SQL执行计划和表元数据", + "operationId": "getTaskAnalysisDataV2", "parameters": [ { "type": "string", - "description": "sync task id", + "description": "task id", "name": "task_id", "in": "path", "required": true + }, + { + "type": "integer", + "description": "sql number", + "name": "number", + "in": "path", + "required": true } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/v1.GetSyncInstanceTaskResV1" + "$ref": "#/definitions/v2.GetTaskAnalysisDataResV2" } } } - }, - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete sync instance task", - "tags": [ - "sync_instance" - ], - "summary": "删除同步实例任务", - "operationId": "deleteSyncInstanceTaskV1", - "parameters": [ - { - "type": "string", - "description": "sync task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update sync instance task", - "tags": [ - "sync_instance" - ], - "summary": "更新同步实例任务", - "operationId": "updateSyncInstanceTaskV1", - "parameters": [ - { - "type": "string", - "description": "sync task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "description": "update sync instance request", - "name": "sync_task", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateSyncInstanceTaskReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/sync_instances/{task_id}/trigger": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "trigger sync instance", - "tags": [ - "sync_instance" - ], - "summary": "触发同步实例", - "operationId": "triggerSyncInstanceV1", - "parameters": [ - { - "type": "string", - "description": "sync task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.TriggerSyncInstanceResV1" - } - } - } - } - }, - "/v1/task_groups/audit": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "audit task group.\n1. formData[sql]: sql content;\n2. file[input_sql_file]: it is a sql file;\n3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it.\n4. file[input_zip_file]: it is zip file, sql will be parsed from it.", - "consumes": [ - "multipart/form-data" - ], - "produces": [ - "application/json" - ], - "tags": [ - "task" - ], - "summary": "审核任务组", - "operationId": "auditTaskGroupIdV1", - "parameters": [ - { - "type": "integer", - "description": "group id of tasks", - "name": "task_group_id", - "in": "formData", - "required": true - }, - { - "type": "string", - "description": "sqls for audit", - "name": "sql", - "in": "formData" - }, - { - "type": "file", - "description": "input SQL file", - "name": "input_sql_file", - "in": "formData" - }, - { - "type": "file", - "description": "input mybatis XML file", - "name": "input_mybatis_xml_file", - "in": "formData" - }, - { - "type": "file", - "description": "input ZIP file", - "name": "input_zip_file", - "in": "formData" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.AuditTaskGroupResV1" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get task", - "tags": [ - "task" - ], - "summary": "获取Sql扫描任务信息", - "operationId": "getAuditTaskV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetAuditTaskResV1" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sql_content": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get SQL content for the audit task", - "tags": [ - "task" - ], - "summary": "获取指定扫描任务的SQL内容", - "operationId": "getAuditTaskSQLContentV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetAuditTaskSQLContentResV1" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sql_file": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "download SQL file for the audit task", - "tags": [ - "task" - ], - "summary": "下载指定扫描任务的SQL文件", - "operationId": "downloadAuditTaskSQLFileV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "sql file", - "schema": { - "type": "file" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sql_report": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "download report file of all SQLs information belong to the specified audit task", - "tags": [ - "task" - ], - "summary": "下载指定扫描任务的SQLs信息报告", - "operationId": "downloadAuditTaskSQLReportV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "boolean", - "description": "select unique (fingerprint and audit result) for task sql", - "name": "no_duplicate", - "in": "query" - } - ], - "responses": { - "200": { - "description": "sql report csv file", - "schema": { - "type": "file" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sqls": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get information of all SQLs belong to the specified audit task", - "tags": [ - "task" - ], - "summary": "获取指定扫描任务的SQLs信息", - "operationId": "getAuditTaskSQLsV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "enum": [ - "initialized", - "doing", - "succeeded", - "failed", - "manually_executed" - ], - "type": "string", - "description": "filter: exec status of task sql", - "name": "filter_exec_status", - "in": "query" - }, - { - "enum": [ - "initialized", - "doing", - "finished" - ], - "type": "string", - "description": "filter: audit status of task sql", - "name": "filter_audit_status", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "filter: audit level of task sql", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "boolean", - "description": "select unique (fingerprint and audit result) for task sql", - "name": "no_duplicate", - "in": "query" - }, - { - "type": "string", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "page size", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetAuditTaskSQLsResV1" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sqls/{number}": { - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "modify the relevant information of a certain SQL in the audit task", - "consumes": [ - "application/json" - ], - "tags": [ - "task" - ], - "summary": "修改扫描任务中某条SQL的相关信息", - "operationId": "updateAuditTaskSQLsV1", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "sql number", - "name": "number", - "in": "path", - "required": true - }, - { - "description": "modify the relevant information of a certain SQL in the audit task", - "name": "audit_plan", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateAuditTaskSQLsReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/tasks/audits/{task_id}/sqls/{number}/analysis": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get SQL explain and related table metadata for analysis", - "tags": [ - "task" - ], - "summary": "获取task相关的SQL执行计划和表元数据", - "operationId": "getTaskAnalysisData", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "integer", - "description": "sql number", - "name": "number", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetTaskAnalysisDataResV1" - } - } - } - } - }, - "/v1/user": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get current user info", - "tags": [ - "user" - ], - "summary": "获取当前用户信息", - "operationId": "getCurrentUserV1", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserDetailResV1" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update current user", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "更新个人信息", - "operationId": "updateCurrentUserV1", - "parameters": [ - { - "description": "update user", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateCurrentUserReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/user/password": { - "put": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update current user's password", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "用户修改密码", - "operationId": "UpdateCurrentUserPasswordV1", - "parameters": [ - { - "description": "update user's password", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateCurrentUserPasswordReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/user_group_tips": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user group tip list", - "tags": [ - "user_group" - ], - "summary": "获取用户组提示列表", - "operationId": "getUserGroupTipListV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "filter_project", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserGroupTipsResV1" - } - } - } - } - }, - "/v1/user_groups": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user group info list", - "produces": [ - "application/json" - ], - "tags": [ - "user_group" - ], - "summary": "获取用户组列表", - "operationId": "getUserGroupListV1", - "parameters": [ - { - "type": "string", - "description": "filter user group name", - "name": "filter_user_group_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserGroupsResV1" - } - } - } - }, - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "create user group", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user_group" - ], - "summary": "创建用户组", - "operationId": "CreateUserGroupV1", - "parameters": [ - { - "description": "create user group", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateUserGroupReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/user_groups/{user_group_name}/": { - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete user group", - "tags": [ - "user_group" - ], - "summary": "删除用户组", - "operationId": "deleteUserGroupV1", - "parameters": [ - { - "type": "string", - "description": "user_group_name", - "name": "user_group_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update user group", - "tags": [ - "user_group" - ], - "summary": "更新用户组", - "operationId": "updateUserGroupV1", - "parameters": [ - { - "type": "string", - "description": "user_group_name", - "name": "user_group_name", - "in": "path", - "required": true - }, - { - "description": "update user group", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.PatchUserGroupReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/user_tips": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user tip list", - "tags": [ - "user" - ], - "summary": "获取用户提示列表", - "operationId": "getUserTipListV1", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "filter_project", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserTipsResV1" - } - } - } - } - }, - "/v1/users": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user info list", - "tags": [ - "user" - ], - "summary": "获取用户信息列表", - "operationId": "getUserListV1", - "parameters": [ - { - "type": "string", - "description": "filter user name", - "name": "filter_user_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUsersResV1" - } - } - } - }, - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "create user", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "创建用户", - "operationId": "createUserV1", - "parameters": [ - { - "description": "create user", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.CreateUserReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/users/{user_name}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get user info", - "tags": [ - "user" - ], - "summary": "获取用户信息", - "operationId": "getUserV1", - "parameters": [ - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetUserDetailResV1" - } - } - } - }, - "delete": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "delete user", - "tags": [ - "user" - ], - "summary": "删除用户", - "operationId": "deleteUserV1", - "parameters": [ - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update user", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "更新用户信息", - "operationId": "updateUserV1", - "parameters": [ - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - }, - { - "description": "update user", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateUserReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/users/{user_name}/password": { - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "admin modifies the passwords of other users", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user" - ], - "summary": "admin修改其他用户密码", - "operationId": "UpdateOtherUserPasswordV1", - "parameters": [ - { - "type": "string", - "description": "user name", - "name": "user_name", - "in": "path", - "required": true - }, - { - "description": "change user's password", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UpdateOtherUserPasswordReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v1/workflows": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get global workflow list", - "tags": [ - "workflow" - ], - "summary": "获取全局工单列表", - "operationId": "getGlobalWorkflowsV1", - "parameters": [ - { - "type": "string", - "description": "filter subject", - "name": "filter_subject", - "in": "query" - }, - { - "type": "string", - "description": "filter create time from", - "name": "filter_create_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter create time to", - "name": "filter_create_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_from", - "name": "filter_task_execute_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "filter_task_execute_start_time_to", - "name": "filter_task_execute_start_time_to", - "in": "query" - }, - { - "type": "string", - "description": "filter create user name", - "name": "filter_create_user_name", - "in": "query" - }, - { - "enum": [ - "wait_for_audit", - "wait_for_execution", - "rejected", - "executing", - "canceled", - "exec_failed", - "finished" - ], - "type": "string", - "description": "filter workflow status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "filter current step assignee user name", - "name": "filter_current_step_assignee_user_name", - "in": "query" - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_task_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v1.GetWorkflowsResV1" - } - } - } - } - }, - "/v2/audit_files": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "Direct audit sql from SQL files and MyBatis files", - "tags": [ - "sql_audit" - ], - "summary": "直接从文件内容提取SQL并审核,SQL文件暂时只支持一次解析一个文件", - "operationId": "directAuditFilesV2", - "parameters": [ - { - "description": "files that should be audited", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.DirectAuditFileReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.DirectAuditResV2" - } - } - } - } - }, - "/v2/configurations/drivers": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get drivers", - "tags": [ - "configuration" - ], - "summary": "获取当前 server 支持的审核类型", - "operationId": "getDriversV2", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetDriversRes" - } - } - } - } - }, - "/v2/login": { - "post": { - "description": "user login", - "tags": [ - "user" - ], - "summary": "用户登录", - "operationId": "loginV2", - "parameters": [ - { - "description": "user login request", - "name": "user", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v1.UserLoginReqV1" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get audit plan info list", - "tags": [ - "audit_plan" - ], - "summary": "获取扫描任务信息列表", - "operationId": "getAuditPlansV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "filter audit plan db type", - "name": "filter_audit_plan_db_type", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search audit plan name", - "name": "fuzzy_search_audit_plan_name", - "in": "query" - }, - { - "type": "string", - "description": "filter audit plan type", - "name": "filter_audit_plan_type", - "in": "query" - }, - { - "type": "string", - "description": "filter audit plan instance name", - "name": "filter_audit_plan_instance_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetAuditPlansResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get audit plan report SQLs", - "tags": [ - "audit_plan" - ], - "summary": "获取指定扫描任务的SQL扫描详情", - "operationId": "getAuditPlanReportsSQLs", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", - "in": "path", - "required": true - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetAuditPlanReportSQLsResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get SQL explain and related table metadata for analysis", - "tags": [ - "audit_plan" - ], - "summary": "获取task相关的SQL执行计划和表元数据", - "operationId": "getAuditPlantAnalysisDataV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan report id", - "name": "audit_plan_report_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "sql number", - "name": "number", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetAuditPlanAnalysisDataResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "full sync audit plan SQLs", - "tags": [ - "audit_plan" - ], - "summary": "全量同步SQL到扫描任务", - "operationId": "fullSyncAuditPlanSQLsV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "description": "full sync audit plan SQLs request", - "name": "sqls", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.FullSyncAuditPlanSQLsReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "partial sync audit plan SQLs", - "tags": [ - "audit_plan" - ], - "summary": "增量同步SQL到扫描任务", - "operationId": "partialSyncAuditPlanSQLsV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "audit plan name", - "name": "audit_plan_name", - "in": "path", - "required": true - }, - { - "description": "partial sync audit plan SQLs request", - "name": "sqls", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.PartialSyncAuditPlanSQLsReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/instances": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get instance info list", - "tags": [ - "instance" - ], - "summary": "获取实例信息列表", - "operationId": "getInstanceListV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "filter instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "type": "string", - "description": "filter db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "filter db host", - "name": "filter_db_host", - "in": "query" - }, - { - "type": "string", - "description": "filter db port", - "name": "filter_db_port", - "in": "query" - }, - { - "type": "string", - "description": "filter db user", - "name": "filter_db_user", - "in": "query" - }, - { - "type": "string", - "description": "filter rule template name", - "name": "filter_rule_template_name", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetInstancesResV2" - } - } - } - }, - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "create a instance", - "consumes": [ - "application/json" - ], - "tags": [ - "instance" - ], - "summary": "添加实例", - "operationId": "createInstanceV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "add instance", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.CreateInstanceReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/instances/{instance_name}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get instance db", - "tags": [ - "instance" - ], - "summary": "获取实例信息", - "operationId": "getInstanceV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "instance name", - "name": "instance_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetInstanceResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/sql_manages": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get sql manage list", - "tags": [ - "SqlManage" - ], - "summary": "获取管控sql列表", - "operationId": "GetSqlManageListV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "fuzzy search sql fingerprint", - "name": "fuzzy_search_sql_fingerprint", - "in": "query" - }, - { - "type": "string", - "description": "assignee", - "name": "filter_assignee", - "in": "query" - }, - { - "type": "string", - "description": "instance name", - "name": "filter_instance_name", - "in": "query" - }, - { - "enum": [ - "audit_plan", - "sql_audit_record" - ], - "type": "string", - "description": "source", - "name": "filter_source", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "audit level", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time from", - "name": "filter_last_audit_start_time_from", - "in": "query" - }, - { - "type": "string", - "description": "last audit start time to", - "name": "filter_last_audit_start_time_to", - "in": "query" - }, - { - "enum": [ - "unhandled", - "solved", - "ignored", - "manual_audited" - ], - "type": "string", - "description": "status", - "name": "filter_status", - "in": "query" - }, - { - "type": "string", - "description": "rule name", - "name": "filter_rule_name", - "in": "query" - }, - { - "type": "string", - "description": "db type", - "name": "filter_db_type", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search endpoint", - "name": "fuzzy_search_endpoint", - "in": "query" - }, - { - "type": "string", - "description": "fuzzy search schema name", - "name": "fuzzy_search_schema_name", - "in": "query" - }, - { - "enum": [ - "first_appear_timestamp", - "last_receive_timestamp", - "fp_count" - ], - "type": "string", - "description": "sort field", - "name": "sort_field", - "in": "query" - }, - { - "enum": [ - "asc", - "desc" - ], - "type": "string", - "description": "sort order", - "name": "sort_order", - "in": "query" - }, - { - "type": "integer", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "integer", - "description": "size of per page", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetSqlManageListResp" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "create workflow", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflow" - ], - "summary": "创建工单", - "operationId": "createWorkflowV2", - "parameters": [ - { - "description": "create workflow request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.CreateWorkflowReqV2" - } - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.CreateWorkflowResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/cancel": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "batch cancel workflows", - "tags": [ - "workflow" - ], - "summary": "批量取消工单", - "operationId": "batchCancelWorkflowsV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "batch cancel workflows request", - "name": "BatchCancelWorkflowsReqV2", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.BatchCancelWorkflowsReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/complete": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "this api will directly change the work order status to finished without real online operation", - "tags": [ - "workflow" - ], - "summary": "批量完成工单", - "operationId": "batchCompleteWorkflowsV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "batch complete workflows request", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.BatchCompleteWorkflowsReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get workflow detail", - "tags": [ - "workflow" - ], - "summary": "获取工单详情", - "operationId": "getWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetWorkflowResV2" - } - } - } - }, - "patch": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update workflow when it is rejected to creator.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflow" - ], - "summary": "更新工单(驳回后才可更新)", - "operationId": "updateWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "update workflow request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.UpdateWorkflowReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/cancel": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "cancel workflow", - "tags": [ - "workflow" - ], - "summary": "审批关闭(中止)", - "operationId": "cancelWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/approve": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "approve workflow", - "tags": [ - "workflow" - ], - "summary": "审批通过", - "operationId": "approveWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow step id", - "name": "workflow_step_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/steps/{workflow_step_id}/reject": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "reject workflow", - "tags": [ - "workflow" - ], - "summary": "审批驳回", - "operationId": "rejectWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "workflow step id", - "name": "workflow_step_id", - "in": "path", - "required": true - }, - { - "description": "workflow approve request", - "name": "workflow_approve", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.RejectWorkflowReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/tasks": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get summary of workflow instance tasks", - "tags": [ - "workflow" - ], - "summary": "获取工单数据源任务概览", - "operationId": "getSummaryOfInstanceTasksV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetWorkflowTasksResV2" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/execute": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "execute tasks on workflow", - "tags": [ - "workflow" - ], - "summary": "多数据源批量上线", - "operationId": "executeTasksOnWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/execute": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "execute one task on workflow", - "tags": [ - "workflow" - ], - "summary": "工单提交单个数据源上线", - "operationId": "executeOneTaskOnWorkflowV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/schedule": { - "put": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "update workflow schedule.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "workflow" - ], - "summary": "设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置)", - "operationId": "updateWorkflowScheduleV2", - "parameters": [ - { - "type": "string", - "description": "workflow id", - "name": "workflow_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "project name", - "name": "project_name", - "in": "path", - "required": true - }, - { - "description": "update workflow schedule request", - "name": "instance", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.UpdateWorkflowScheduleReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/controller.BaseRes" - } - } - } - } - }, - "/v2/sql_audit": { - "post": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "Direct audit sql", - "tags": [ - "sql_audit" - ], - "summary": "直接审核SQL", - "operationId": "directAuditV2", - "deprecated": true, - "parameters": [ - { - "description": "sqls that should be audited", - "name": "req", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/v2.DirectAuditReqV2" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.DirectAuditResV2" - } - } - } - } - }, - "/v2/tasks/audits/{task_id}/sqls": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get information of all SQLs belong to the specified audit task", - "tags": [ - "task" - ], - "summary": "获取指定扫描任务的SQLs信息", - "operationId": "getAuditTaskSQLsV2", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "enum": [ - "initialized", - "doing", - "succeeded", - "failed", - "manually_executed", - "terminating", - "terminate_succeeded", - "terminate_failed" - ], - "type": "string", - "description": "filter: exec status of task sql", - "name": "filter_exec_status", - "in": "query" - }, - { - "enum": [ - "initialized", - "doing", - "finished" - ], - "type": "string", - "description": "filter: audit status of task sql", - "name": "filter_audit_status", - "in": "query" - }, - { - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "type": "string", - "description": "filter: audit level of task sql", - "name": "filter_audit_level", - "in": "query" - }, - { - "type": "boolean", - "description": "select unique (fingerprint and audit result) for task sql", - "name": "no_duplicate", - "in": "query" - }, - { - "type": "string", - "description": "page index", - "name": "page_index", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "page size", - "name": "page_size", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetAuditTaskSQLsResV2" - } - } - } - } - }, - "/v2/tasks/audits/{task_id}/sqls/{number}/analysis": { - "get": { - "security": [ - { - "ApiKeyAuth": [] - } - ], - "description": "get SQL explain and related table metadata for analysis", - "tags": [ - "task" - ], - "summary": "获取task相关的SQL执行计划和表元数据", - "operationId": "getTaskAnalysisDataV2", - "parameters": [ - { - "type": "string", - "description": "task id", - "name": "task_id", - "in": "path", - "required": true - }, - { - "type": "integer", - "description": "sql number", - "name": "number", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/v2.GetTaskAnalysisDataResV2" - } - } - } - } - } - }, - "definitions": { - "controller.BaseRes": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.AffectRows": { - "type": "object", - "properties": { - "count": { - "type": "integer" - }, - "err_message": { - "type": "string" - } - } - }, - "v1.AuditPlanCount": { - "type": "object", - "properties": { - "audit_plan_count": { - "type": "integer" - }, - "audit_plan_desc": { - "type": "string" - }, - "audit_plan_type": { - "type": "string" - } - } - }, - "v1.AuditPlanMetaV1": { - "type": "object", - "properties": { - "audit_plan_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanParamResV1" - } - }, - "audit_plan_type": { - "type": "string" - }, - "audit_plan_type_desc": { - "type": "string" - }, - "instance_type": { - "type": "string" - } - } - }, - "v1.AuditPlanParamReqV1": { - "type": "object", - "properties": { - "key": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "v1.AuditPlanParamResV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "key": { - "type": "string" - }, - "type": { - "type": "string", - "enum": [ - "string", - "int", - "bool" - ] - }, - "value": { - "type": "string" - } - } - }, - "v1.AuditPlanReportResV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error", - "" - ] - }, - "audit_plan_report_id": { - "type": "string", - "example": "1" - }, - "audit_plan_report_timestamp": { - "type": "string", - "example": "RFC3339" - }, - "pass_rate": { - "type": "number" - }, - "score": { - "type": "integer" - } - } - }, - "v1.AuditPlanReportSQLResV1": { - "type": "object", - "properties": { - "audit_plan_report_sql": { - "type": "string", - "example": "select * from t1 where id = 1" - }, - "audit_plan_report_sql_audit_result": { - "type": "string", - "example": "same format as task audit result" - }, - "number": { - "type": "integer", - "example": 1 - } - } - }, - "v1.AuditPlanResV1": { - "type": "object", - "properties": { - "audit_plan_cron": { - "type": "string", - "example": "0 */2 * * *" - }, - "audit_plan_db_type": { - "type": "string", - "example": "mysql" - }, - "audit_plan_instance_database": { - "type": "string", - "example": "app1" - }, - "audit_plan_instance_name": { - "type": "string", - "example": "test_mysql" - }, - "audit_plan_meta": { - "type": "object", - "$ref": "#/definitions/v1.AuditPlanMetaV1" - }, - "audit_plan_name": { - "type": "string", - "example": "audit_for_java_app1" - }, - "audit_plan_token": { - "type": "string", - "example": "it's a JWT Token for scanner" - }, - "rule_template_name": { - "type": "string", - "example": "default_MySQL" - } - } - }, - "v1.AuditPlanSQLHeadV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "name": { - "type": "string" - }, - "type": { - "type": "string", - "enum": [ - "sql" - ] - } - } - }, - "v1.AuditPlanSQLReqV1": { - "type": "object", - "properties": { - "audit_plan_sql_counter": { - "type": "string", - "example": "6" - }, - "audit_plan_sql_fingerprint": { - "type": "string", - "example": "select * from t1 where id = ?" - }, - "audit_plan_sql_last_receive_text": { - "type": "string", - "example": "select * from t1 where id = 1" - }, - "audit_plan_sql_last_receive_timestamp": { - "type": "string", - "example": "RFC3339" - }, - "audit_plan_sql_schema": { - "type": "string", - "example": "db1" - }, - "db_user": { - "type": "string", - "example": "database_user001" - }, - "endpoint": { - "type": "string", - "example": "10.186.1.2" - }, - "first_query_at": { - "type": "string", - "example": "2023-09-12T02:48:01.317880Z" - }, - "query_time_avg": { - "type": "number", - "example": 3.22 - }, - "query_time_max": { - "type": "number", - "example": 5.22 - } - } - }, - "v1.AuditPlanSQLResV1": { - "type": "object", - "properties": { - "head": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanSQLHeadV1" - } - }, - "rows": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - }, - "v1.AuditPlanTypesV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "instance_type": { - "type": "string", - "enum": [ - "MySQL", - "Oracle", - "TiDB", - "OceanBase For MySQL", - "" - ] - }, - "type": { - "type": "string" - } - } - }, - "v1.AuditResDataV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error", - "" - ] - }, - "pass_rate": { - "type": "number" - }, - "score": { - "type": "integer" - }, - "sql_results": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditSQLResV1" - } - } - } - }, - "v1.AuditResult": { - "type": "object", - "properties": { - "level": { - "type": "string", - "example": "warn" - }, - "message": { - "type": "string", - "example": "避免使用不必要的内置函数md5()" - }, - "rule_name": { - "type": "string" - } - } - }, - "v1.AuditSQLResV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string" - }, - "audit_result": { - "type": "string" - }, - "exec_sql": { - "type": "string" - }, - "number": { - "type": "integer" - } - } - }, - "v1.AuditTaskGroupRes": { - "type": "object", - "properties": { - "task_group_id": { - "type": "integer" - }, - "tasks": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditTaskResV1" - } - } - } - }, - "v1.AuditTaskGroupResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskGroupRes" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.AuditTaskResV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error", - "" - ] - }, - "exec_end_time": { - "type": "string" - }, - "exec_start_time": { - "type": "string" - }, - "instance_db_type": { - "type": "string" - }, - "instance_name": { - "type": "string" - }, - "instance_schema": { - "type": "string", - "example": "db1" - }, - "pass_rate": { - "type": "number" - }, - "score": { - "type": "integer" - }, - "sql_source": { - "type": "string", - "enum": [ - "form_data", - "sql_file", - "mybatis_xml_file", - "audit_plan" - ] - }, - "status": { - "type": "string", - "enum": [ - "initialized", - "audited", - "executing", - "exec_success", - "exec_failed", - "manually_executed" - ] - }, - "task_id": { - "type": "integer" - } - } - }, - "v1.AuditTaskSQLContentResV1": { - "type": "object", - "properties": { - "sql": { - "type": "string", - "example": "alter table tb1 drop columns c1" - } - } - }, - "v1.AuditTaskSQLResV1": { - "type": "object", - "properties": { - "audit_level": { - "type": "string" - }, - "audit_result": { - "type": "string" - }, - "audit_status": { - "type": "string" - }, - "description": { - "type": "string" - }, - "exec_result": { - "type": "string" - }, - "exec_sql": { - "type": "string" - }, - "exec_status": { - "type": "string" - }, - "number": { - "type": "integer" - }, - "rollback_sql": { - "type": "string" - } - } - }, - "v1.AuditTasksGroupResV1": { - "type": "object", - "properties": { - "task_group_id": { - "type": "integer" - } - } - }, - "v1.AuditWhitelistResV1": { - "type": "object", - "properties": { - "audit_whitelist_id": { - "type": "integer" - }, - "desc": { - "type": "string" - }, - "match_type": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "v1.AuditedSQLCount": { - "type": "object", - "properties": { - "risk_sql_count": { - "type": "integer" - }, - "total_sql_count": { - "type": "integer" - } - } - }, - "v1.BatchCancelWorkflowsReqV1": { - "type": "object", - "properties": { - "workflow_names": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.BatchCheckInstanceConnectionsReqV1": { - "type": "object", - "properties": { - "instances": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceForCheckConnection" - } - } - } - }, - "v1.BatchCompleteWorkflowsReqV1": { - "type": "object", - "properties": { - "workflow_names": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.BatchGetInstanceConnectionsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceConnectionResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.BatchUpdateSqlManageReq": { - "type": "object", - "properties": { - "assignees": { - "type": "array", - "items": { - "type": "string" - } - }, - "remark": { - "type": "string" - }, - "sql_manage_id_list": { - "type": "array", - "items": { - "type": "integer" - } - }, - "status": { - "type": "string", - "enum": [ - "solved", - "ignored", - "manual_audited" - ] - } - } - }, - "v1.BindOauth2UserReqV1": { - "type": "object", - "properties": { - "oauth2_token": { - "type": "string" - }, - "pwd": { - "type": "string" - }, - "user_name": { - "type": "string" - } - } - }, - "v1.BindOauth2UserResDataV1": { - "type": "object", - "properties": { - "token": { - "type": "string" - } - } - }, - "v1.BindOauth2UserResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.BindOauth2UserResDataV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.BindRoleReqV1": { - "type": "object", - "properties": { - "instance_name": { - "type": "string" - }, - "role_names": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.CheckLicenseResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "content": { - "type": "string" - }, - "license": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.LicenseItem" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.CloneProjectRuleTemplateReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - } - }, - "new_rule_template_name": { - "type": "string" - } - } - }, - "v1.CloneRuleTemplateReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "new_rule_template_name": { - "type": "string" - } - } - }, - "v1.CompanyNotice": { - "type": "object", - "properties": { - "notice_str": { - "type": "string" - } - } - }, - "v1.CreateAuditPlanReqV1": { - "type": "object", - "properties": { - "audit_plan_cron": { - "type": "string", - "example": "0 */2 * * *" - }, - "audit_plan_instance_database": { - "type": "string", - "example": "app1" - }, - "audit_plan_instance_name": { - "type": "string", - "example": "test_mysql" - }, - "audit_plan_instance_type": { - "type": "string", - "example": "mysql" - }, - "audit_plan_name": { - "type": "string", - "example": "audit_plan_for_java_repo_1" - }, - "audit_plan_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanParamReqV1" - } - }, - "audit_plan_type": { - "type": "string", - "example": "slow log" - }, - "rule_template_name": { - "type": "string", - "example": "default_MySQL" - } - } - }, - "v1.CreateAuditTasksGroupReqV1": { - "type": "object", - "properties": { - "instances": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceForCreatingTask" - } - } - } - }, - "v1.CreateAuditTasksGroupResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditTasksGroupResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.CreateAuditWhitelistReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string", - "example": "used for rapid release" - }, - "match_type": { - "type": "string", - "enum": [ - "exact_match", - "fp_match" - ], - "example": "exact_match" - }, - "value": { - "type": "string", - "example": "create table" - } - } - }, - "v1.CreateCustomRuleReqV1": { - "type": "object", - "properties": { - "annotation": { - "type": "string", - "example": "this is test rule" - }, - "db_type": { - "type": "string", - "example": "MySQL" - }, - "desc": { - "type": "string", - "example": "this is test rule" - }, - "level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "notice" - }, - "rule_script": { - "type": "string" - }, - "type": { - "type": "string", - "example": "DDL规则" - } - } - }, - "v1.CreateInstanceReqV1": { - "type": "object", - "properties": { - "additional_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamReqV1" - } - }, - "db_host": { - "type": "string", - "example": "10.10.10.10" - }, - "db_password": { - "type": "string", - "example": "123456" - }, - "db_port": { - "type": "string", - "example": "3306" - }, - "db_type": { - "type": "string", - "example": "mysql" - }, - "db_user": { - "type": "string", - "example": "root" - }, - "desc": { - "type": "string", - "example": "this is a test instance" - }, - "instance_name": { - "type": "string", - "example": "test" - }, - "maintenance_times": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MaintenanceTimeReqV1" - } - }, - "rule_template_name": { - "type": "string" - }, - "sql_query_config": { - "type": "object", - "$ref": "#/definitions/v1.SQLQueryConfigReqV1" - } - } - }, - "v1.CreateMemberGroupReqV1": { - "type": "object", - "properties": { - "roles": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" - } - }, - "user_group_name": { - "type": "string" - } - } - }, - "v1.CreateMemberReqV1": { - "type": "object", - "properties": { - "is_manager": { - "type": "boolean" - }, - "roles": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" - } - }, - "user_name": { - "type": "string" - } - } - }, - "v1.CreateProjectReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "v1.CreateProjectRuleTemplateReqV1": { - "type": "object", - "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - } - }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleReqV1" - } - }, - "rule_template_name": { - "type": "string" - } - } - }, - "v1.CreateRoleReqV1": { - "type": "object", - "properties": { - "operation_code_list": { - "type": "array", - "items": { - "type": "integer" - } - }, - "role_desc": { - "type": "string" - }, - "role_name": { - "type": "string" - } - } - }, - "v1.CreateRuleTemplateReqV1": { - "type": "object", - "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleReqV1" - } - }, - "rule_template_name": { - "type": "string" - } - } - }, - "v1.CreateSQLAuditRecordResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.SQLAuditRecordResData" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.CreateSyncInstanceTaskReqV1": { - "type": "object", - "required": [ - "db_type", - "global_rule_template", - "source", - "sync_instance_interval", - "url", - "version" - ], - "properties": { - "db_type": { - "type": "string", - "example": "mysql" - }, - "global_rule_template": { - "type": "string", - "example": "default_mysql" - }, - "source": { - "type": "string", - "example": "actiontech-dmp" - }, - "sync_instance_interval": { - "type": "string", - "example": "0 0 * * *" - }, - "url": { - "type": "string", - "example": "http://10.186.62.56:10000" - }, - "version": { - "type": "string", - "example": "5.23.01.0" - } - } - }, - "v1.CreateUserGroupReqV1": { - "type": "object", - "properties": { - "user_group_desc": { - "type": "string", - "example": "this is a group" - }, - "user_group_name": { - "type": "string", - "example": "test" - }, - "user_name_list": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.CreateUserReqV1": { - "type": "object", - "properties": { - "email": { - "type": "string", - "example": "test@email.com" - }, - "management_permission_code_list": { - "type": "array", - "items": { - "type": "integer" - } - }, - "phone": { - "type": "string", - "example": "18962136666" - }, - "user_group_name_list": { - "type": "array", - "items": { - "type": "string" - } - }, - "user_name": { - "type": "string", - "example": "test" - }, - "user_password": { - "type": "string", - "example": "123456" - }, - "wechat_id": { - "type": "string", - "example": "UserID" - } - } - }, - "v1.CreateWorkflowReqV1": { - "type": "object", - "properties": { - "desc": { - "type": "string" - }, - "task_ids": { - "type": "array", - "items": { - "type": "integer" - } - }, - "workflow_subject": { - "type": "string" - } - } - }, - "v1.CustomRuleResV1": { - "type": "object", - "properties": { - "annotation": { - "type": "string", - "example": "this is test rule" - }, - "db_type": { - "type": "string", - "example": "MySQL" - }, - "desc": { - "type": "string", - "example": "this is test rule" - }, - "level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "notice" - }, - "rule_id": { - "type": "string" - }, - "rule_script": { - "type": "string" - }, - "type": { - "type": "string", - "example": "DDL规则" - } - } - }, - "v1.DBTypeAuditPlan": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanCount" - } - }, - "db_type": { - "type": "string" - } - } - }, - "v1.DBTypeHealth": { - "type": "object", - "properties": { - "db_type": { - "type": "string" - }, - "health_instance_names": { - "type": "array", - "items": { - "type": "string" - } - }, - "unhealth_instance_names": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.DashboardProjectTipV1": { - "type": "object", - "properties": { - "project_name": { - "type": "string" - }, - "unfinished_workflow_count": { - "description": "只统计与当前用户相关的未完成工单", - "type": "integer" - } - } - }, - "v1.DashboardResV1": { - "type": "object", - "properties": { - "workflow_statistics": { - "type": "object", - "$ref": "#/definitions/v1.WorkflowStatisticsResV1" - } - } - }, - "v1.DingTalkConfigurationV1": { - "type": "object", - "properties": { - "app_key": { - "type": "string" - }, - "is_enable_ding_talk_notify": { - "type": "boolean" - } - } - }, - "v1.DirectAuditFileReqV1": { - "type": "object", - "properties": { - "file_contents": { - "description": "调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现\n每个数组元素是一个文件内容", - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "select * from t1; select * from t2;" - ] - }, - "instance_name": { - "type": "string", - "example": "instance1" - }, - "instance_type": { - "type": "string", - "example": "MySQL" - }, - "project_name": { - "type": "string", - "example": "project1" - }, - "schema_name": { - "type": "string", - "example": "schema1" - }, - "sql_type": { - "type": "string", - "enum": [ - "sql", - "mybatis", - "" - ], - "example": "sql" - } - } - }, - "v1.DirectAuditReqV1": { - "type": "object", - "properties": { - "instance_name": { - "type": "string", - "example": "instance1" - }, - "instance_type": { - "type": "string", - "example": "MySQL" - }, - "project_name": { - "type": "string", - "example": "project1" - }, - "schema_name": { - "type": "string", - "example": "schema1" - }, - "sql_content": { - "description": "调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现", - "type": "string", - "example": "select * from t1; select * from t2;" - }, - "sql_type": { - "type": "string", - "enum": [ - "sql", - "mybatis", - "" - ], - "example": "sql" - } - } - }, - "v1.DirectAuditResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditResDataV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.DirectGetSQLAnalysisResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.SqlAnalysisResDataV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.DriversResV1": { - "type": "object", - "properties": { - "driver_name_list": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "v1.ExplainClassicResult": { - "type": "object", - "properties": { - "head": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMetaItemHeadResV1" - } - }, - "rows": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - }, - "v1.FeishuConfigurationV1": { - "type": "object", - "properties": { - "app_id": { - "type": "string" - }, - "is_feishu_notification_enabled": { - "type": "boolean" - } - } - }, - "v1.FullSyncAuditPlanSQLsReqV1": { - "type": "object", - "properties": { - "audit_plan_sql_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanSQLReqV1" - } - } - } - }, - "v1.GetAuditPlanAnalysisDataResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetSQLAnalysisDataResItemV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanMetasResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanMetaV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanNotifyConfigResDataV1": { - "type": "object", - "properties": { - "enable_email_notify": { - "type": "boolean" - }, - "enable_web_hook_notify": { - "type": "boolean" - }, - "notify_interval": { - "type": "integer" - }, - "notify_level": { - "type": "string" - }, - "web_hook_template": { - "type": "string" - }, - "web_hook_url": { - "type": "string" - } - } - }, - "v1.GetAuditPlanNotifyConfigResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetAuditPlanNotifyConfigResDataV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanReportResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditPlanReportResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanReportSQLsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanReportSQLResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditPlanReportsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanReportResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditPlanResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditPlanResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlanSQLsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditPlanSQLResV1" - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditPlanTypesResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanTypesV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditPlansResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditTaskResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditTaskSQLContentResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskSQLContentResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetAuditTaskSQLsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditTaskSQLResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetAuditWhitelistResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditWhitelistResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, - "v1.GetCompanyNoticeResp": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.CompanyNotice" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetCustomRuleResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.CustomRuleResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetCustomRulesResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.CustomRuleResV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetDashboardProjectTipsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.DashboardProjectTipV1" - } - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetDashboardResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.DashboardResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetDingTalkConfigurationResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.DingTalkConfigurationV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetDriversResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.DriversResV1" - }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetFeishuAuditConfigurationResV1": { + } + } + }, + "definitions": { + "controller.BaseRes": { "type": "object", "properties": { "code": { "type": "integer", "example": 0 }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.FeishuConfigurationV1" - }, "message": { "type": "string", "example": "ok" } } }, - "v1.GetFeishuConfigurationResV1": { + "v1.AffectRows": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.FeishuConfigurationV1" + "count": { + "type": "integer" }, - "message": { - "type": "string", - "example": "ok" + "err_message": { + "type": "string" } } }, - "v1.GetInstanceAdditionalMetasResV1": { + "v1.AuditPlanCount": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_plan_count": { + "type": "integer" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalMetaV1" - } + "audit_plan_desc": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "audit_plan_type": { + "type": "string" } } }, - "v1.GetInstanceConnectableReqV1": { + "v1.AuditPlanMetaV1": { "type": "object", "properties": { - "additional_params": { + "audit_plan_params": { "type": "array", "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamReqV1" + "$ref": "#/definitions/v1.AuditPlanParamResV1" } }, - "db_type": { - "type": "string", - "example": "mysql" - }, - "host": { - "type": "string", - "example": "10.10.10.10" - }, - "password": { - "type": "string", - "example": "123456" + "audit_plan_type": { + "type": "string" }, - "port": { - "type": "string", - "example": "3306" + "audit_plan_type_desc": { + "type": "string" }, - "user": { - "type": "string", - "example": "root" + "instance_type": { + "type": "string" } } }, - "v1.GetInstanceConnectableResV1": { + "v1.AuditPlanParamReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstanceConnectableResV1" + "key": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "value": { + "type": "string" } } }, - "v1.GetInstanceHealthResV1": { + "v1.AuditPlanParamResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.DBTypeHealth" - } + "key": { + "type": "string" }, - "message": { + "type": { "type": "string", - "example": "ok" + "enum": [ + "string", + "int", + "bool" + ] + }, + "value": { + "type": "string" } } }, - "v1.GetInstanceResV1": { + "v1.AuditPlanReportResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error", + "" + ] }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstanceResV1" + "audit_plan_report_id": { + "type": "string", + "example": "1" }, - "message": { + "audit_plan_report_timestamp": { "type": "string", - "example": "ok" + "example": "RFC3339" + }, + "pass_rate": { + "type": "number" + }, + "score": { + "type": "integer" } } }, - "v1.GetInstanceSchemaResV1": { + "v1.AuditPlanReportSQLResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstanceSchemaResV1" + "audit_plan_report_sql": { + "type": "string", + "example": "select * from t1 where id = 1" }, - "message": { + "audit_plan_report_sql_audit_result": { "type": "string", - "example": "ok" + "example": "same format as task audit result" + }, + "number": { + "type": "integer", + "example": 1 } } }, - "v1.GetInstanceTipsResV1": { + "v1.AuditPlanResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_plan_cron": { + "type": "string", + "example": "0 */2 * * *" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceTipResV1" - } + "audit_plan_db_type": { + "type": "string", + "example": "mysql" }, - "message": { + "audit_plan_instance_database": { "type": "string", - "example": "ok" - } - } - }, - "v1.GetInstancesResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 + "example": "app1" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceResV1" - } + "audit_plan_instance_name": { + "type": "string", + "example": "test_mysql" }, - "message": { + "audit_plan_meta": { + "type": "object", + "$ref": "#/definitions/v1.AuditPlanMetaV1" + }, + "audit_plan_name": { "type": "string", - "example": "ok" + "example": "audit_for_java_app1" }, - "total_nums": { - "type": "integer" + "audit_plan_token": { + "type": "string", + "example": "it's a JWT Token for scanner" + }, + "rule_template_name": { + "type": "string", + "example": "default_MySQL" } } }, - "v1.GetInstancesTypePercentResV1": { + "v1.AuditPlanSQLHeadV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstancesTypePercentV1" + "name": { + "type": "string" }, - "message": { + "type": { "type": "string", - "example": "ok" + "enum": [ + "sql" + ] } } }, - "v1.GetLDAPConfigurationResV1": { + "v1.AuditPlanSQLReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_plan_sql_counter": { + "type": "string", + "example": "6" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.LDAPConfigurationResV1" + "audit_plan_sql_fingerprint": { + "type": "string", + "example": "select * from t1 where id = ?" + }, + "audit_plan_sql_last_receive_text": { + "type": "string", + "example": "select * from t1 where id = 1" + }, + "audit_plan_sql_last_receive_timestamp": { + "type": "string", + "example": "RFC3339" + }, + "audit_plan_sql_schema": { + "type": "string", + "example": "db1" + }, + "db_user": { + "type": "string", + "example": "database_user001" + }, + "endpoint": { + "type": "string", + "example": "10.186.1.2" }, - "message": { + "first_query_at": { "type": "string", - "example": "ok" + "example": "2023-09-12T02:48:01.317880Z" + }, + "query_time_avg": { + "type": "number", + "example": 3.22 + }, + "query_time_max": { + "type": "number", + "example": 5.22 } } }, - "v1.GetLicenseResV1": { + "v1.AuditPlanSQLResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "content": { - "type": "string" - }, - "license": { + "head": { "type": "array", "items": { - "$ref": "#/definitions/v1.LicenseItem" + "$ref": "#/definitions/v1.AuditPlanSQLHeadV1" } }, - "message": { - "type": "string", - "example": "ok" + "rows": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } } } }, - "v1.GetLicenseUsageResV1": { + "v1.AuditPlanTypesV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.LicenseUsageV1" + "desc": { + "type": "string" }, - "message": { + "instance_type": { "type": "string", - "example": "ok" - } - } - }, - "v1.GetManagementPermissionsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ManagementPermissionResV1" - } + "enum": [ + "MySQL", + "Oracle", + "TiDB", + "OceanBase For MySQL", + "" + ] }, - "message": { - "type": "string", - "example": "ok" + "type": { + "type": "string" } } }, - "v1.GetMemberGroupRespDataV1": { + "v1.AuditResDataV1": { "type": "object", "properties": { - "roles": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" - } + "audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error", + "" + ] }, - "user_group_name": { - "type": "string" + "pass_rate": { + "type": "number" + }, + "score": { + "type": "integer" }, - "users": { + "sql_results": { "type": "array", "items": { - "$ref": "#/definitions/v1.MemberGroupUserItem" + "$ref": "#/definitions/v1.AuditSQLResV1" } } } }, - "v1.GetMemberGroupRespV1": { + "v1.AuditResult": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetMemberGroupRespDataV1" + "level": { + "type": "string", + "example": "warn" }, "message": { "type": "string", - "example": "ok" + "example": "避免使用不必要的内置函数md5()" + }, + "rule_name": { + "type": "string" } } }, - "v1.GetMemberGroupsRespV1": { + "v1.AuditSQLResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_level": { + "type": "string" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.GetMemberGroupRespDataV1" - } + "audit_result": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "exec_sql": { + "type": "string" }, - "total_nums": { + "number": { "type": "integer" } } }, - "v1.GetMemberRespDataV1": { + "v1.AuditTaskGroupRes": { "type": "object", "properties": { - "is_manager": { - "type": "boolean" + "task_group_id": { + "type": "integer" }, - "roles": { + "tasks": { "type": "array", "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" + "$ref": "#/definitions/v1.AuditTaskResV1" } - }, - "user_name": { - "type": "string" } } }, - "v1.GetMemberRespV1": { + "v1.AuditTaskGroupResV1": { "type": "object", "properties": { "code": { @@ -12548,7 +7798,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.GetMemberRespDataV1" + "$ref": "#/definitions/v1.AuditTaskGroupRes" }, "message": { "type": "string", @@ -12556,191 +7806,177 @@ } } }, - "v1.GetMemberTipsResV1": { + "v1.AuditTaskResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error", + "" + ] }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MemberTipResV1" - } + "exec_end_time": { + "type": "string" }, - "message": { + "exec_start_time": { + "type": "string" + }, + "instance_db_type": { + "type": "string" + }, + "instance_name": { + "type": "string" + }, + "instance_schema": { "type": "string", - "example": "ok" + "example": "db1" + }, + "pass_rate": { + "type": "number" + }, + "score": { + "type": "integer" + }, + "sql_source": { + "type": "string", + "enum": [ + "form_data", + "sql_file", + "mybatis_xml_file", + "audit_plan" + ] + }, + "status": { + "type": "string", + "enum": [ + "initialized", + "audited", + "executing", + "exec_success", + "exec_failed", + "manually_executed" + ] + }, + "task_id": { + "type": "integer" } } }, - "v1.GetMembersRespV1": { + "v1.AuditTaskSQLContentResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.GetMemberRespDataV1" - } - }, - "message": { + "sql": { "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" + "example": "alter table tb1 drop columns c1" } } }, - "v1.GetOauth2ConfigurationResDataV1": { + "v1.AuditTaskSQLResV1": { "type": "object", "properties": { - "access_token_tag": { + "audit_level": { "type": "string" }, - "client_host": { + "audit_result": { "type": "string" }, - "client_id": { + "audit_status": { "type": "string" }, - "enable_oauth2": { - "type": "boolean" - }, - "login_tip": { + "description": { "type": "string" }, - "scopes": { - "type": "array", - "items": { - "type": "string" - } - }, - "server_auth_url": { + "exec_result": { "type": "string" }, - "server_token_url": { + "exec_sql": { "type": "string" }, - "server_user_id_url": { + "exec_status": { "type": "string" }, - "user_id_tag": { + "number": { + "type": "integer" + }, + "rollback_sql": { "type": "string" } } }, - "v1.GetOauth2ConfigurationResV1": { + "v1.AuditTasksGroupResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetOauth2ConfigurationResDataV1" - }, - "message": { - "type": "string", - "example": "ok" + "task_group_id": { + "type": "integer" } } }, - "v1.GetOauth2TipsResDataV1": { + "v1.AuditWhitelistResV1": { "type": "object", "properties": { - "enable_oauth2": { - "type": "boolean" + "audit_whitelist_id": { + "type": "integer" + }, + "desc": { + "type": "string" + }, + "match_type": { + "type": "string" }, - "login_tip": { + "value": { "type": "string" } } }, - "v1.GetOauth2TipsResV1": { + "v1.AuditedSQLCount": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetOauth2TipsResDataV1" + "risk_sql_count": { + "type": "integer" }, - "message": { - "type": "string", - "example": "ok" + "total_sql_count": { + "type": "integer" } } }, - "v1.GetOperationActionListResV1": { + "v1.BatchCancelWorkflowsReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "workflow_names": { "type": "array", "items": { - "$ref": "#/definitions/v1.OperationActionList" + "type": "string" } - }, - "message": { - "type": "string", - "example": "ok" } } }, - "v1.GetOperationRecordListResV1": { + "v1.BatchCheckInstanceConnectionsReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "instances": { "type": "array", "items": { - "$ref": "#/definitions/v1.OperationRecordList" + "$ref": "#/definitions/v1.InstanceForCheckConnection" } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" } } }, - "v1.GetOperationTypeNamesListResV1": { + "v1.BatchCompleteWorkflowsReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "workflow_names": { "type": "array", "items": { - "$ref": "#/definitions/v1.OperationTypeNameList" + "type": "string" } - }, - "message": { - "type": "string", - "example": "ok" } } }, - "v1.GetOperationsResV1": { + "v1.BatchGetInstanceConnectionsResV1": { "type": "object", "properties": { "code": { @@ -12750,7 +7986,7 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.OperationResV1" + "$ref": "#/definitions/v1.InstanceConnectionResV1" } }, "message": { @@ -12759,85 +7995,137 @@ } } }, - "v1.GetProjectDetailResV1": { + "v1.BatchUpdateSqlManageReq": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "assignees": { + "type": "array", + "items": { + "type": "string" + } }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.ProjectDetailItem" + "remark": { + "type": "string" }, - "message": { + "sql_manage_id_list": { + "type": "array", + "items": { + "type": "integer" + } + }, + "status": { "type": "string", - "example": "ok" + "enum": [ + "solved", + "ignored", + "manual_audited" + ] } } }, - "v1.GetProjectResV1": { + "v1.CheckLicenseResV1": { "type": "object", "properties": { "code": { "type": "integer", "example": 0 }, - "data": { + "content": { + "type": "string" + }, + "license": { "type": "array", "items": { - "$ref": "#/definitions/v1.ProjectListItem" + "$ref": "#/definitions/v1.LicenseItem" } }, "message": { "type": "string", "example": "ok" - }, - "total_nums": { - "type": "integer" } } }, - "v1.GetProjectRuleTemplateResV1": { + "v1.CloneProjectRuleTemplateReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.RuleProjectTemplateDetailResV1" + "new_rule_template_name": { + "type": "string" + } + } + }, + "v1.CloneRuleTemplateReqV1": { + "type": "object", + "properties": { + "desc": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "new_rule_template_name": { + "type": "string" } } }, - "v1.GetProjectRuleTemplatesResV1": { + "v1.CompanyNotice": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "notice_str": { + "type": "string" + } + } + }, + "v1.CreateAuditPlanReqV1": { + "type": "object", + "properties": { + "audit_plan_cron": { + "type": "string", + "example": "0 */2 * * *" }, - "data": { + "audit_plan_instance_database": { + "type": "string", + "example": "app1" + }, + "audit_plan_instance_name": { + "type": "string", + "example": "test_mysql" + }, + "audit_plan_instance_type": { + "type": "string", + "example": "mysql" + }, + "audit_plan_name": { + "type": "string", + "example": "audit_plan_for_java_repo_1" + }, + "audit_plan_params": { "type": "array", "items": { - "$ref": "#/definitions/v1.ProjectRuleTemplateResV1" + "$ref": "#/definitions/v1.AuditPlanParamReqV1" } }, - "message": { + "audit_plan_type": { "type": "string", - "example": "ok" + "example": "slow log" }, - "total_nums": { - "type": "integer" + "rule_template_name": { + "type": "string", + "example": "default_MySQL" } } }, - "v1.GetProjectScoreResV1": { + "v1.CreateAuditTasksGroupReqV1": { + "type": "object", + "properties": { + "instances": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.InstanceForCreatingTask" + } + } + } + }, + "v1.CreateAuditTasksGroupResV1": { "type": "object", "properties": { "code": { @@ -12846,7 +8134,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.ProjectScore" + "$ref": "#/definitions/v1.AuditTasksGroupResV1" }, "message": { "type": "string", @@ -12854,104 +8142,102 @@ } } }, - "v1.GetProjectStatisticsResDataV1": { + "v1.CreateAuditWhitelistReqV1": { "type": "object", "properties": { - "audit_plan_total": { - "type": "integer" - }, - "instance_total": { - "type": "integer" - }, - "member_total": { - "type": "integer" - }, - "rule_template_total": { - "type": "integer" + "desc": { + "type": "string", + "example": "used for rapid release" }, - "whitelist_total": { - "type": "integer" + "match_type": { + "type": "string", + "enum": [ + "exact_match", + "fp_match" + ], + "example": "exact_match" }, - "workflow_total": { - "type": "integer" + "value": { + "type": "string", + "example": "create table" } } }, - "v1.GetProjectStatisticsResV1": { + "v1.CreateCustomRuleReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "annotation": { + "type": "string", + "example": "this is test rule" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetProjectStatisticsResDataV1" + "db_type": { + "type": "string", + "example": "MySQL" }, - "message": { + "desc": { "type": "string", - "example": "ok" - } - } - }, - "v1.GetProjectTipsResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 + "example": "this is test rule" + }, + "level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "example": "notice" }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ProjectTipResV1" - } + "rule_script": { + "type": "string" }, - "message": { + "type": { "type": "string", - "example": "ok" + "example": "DDL规则" } } }, - "v1.GetRiskAuditPlanResV1": { + "v1.CreateProjectRuleTemplateReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { + "desc": { + "type": "string" + }, + "rule_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.RiskAuditPlan" + "$ref": "#/definitions/v1.RuleReqV1" } }, - "message": { - "type": "string", - "example": "ok" + "rule_template_name": { + "type": "string" } } }, - "v1.GetRoleTipsResV1": { + "v1.CreateRuleTemplateReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { + "desc": { + "type": "string" + }, + "rule_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.RoleTipResV1" + "$ref": "#/definitions/v1.RuleReqV1" } }, - "message": { - "type": "string", - "example": "ok" + "rule_template_name": { + "type": "string" } } }, - "v1.GetRoleUserCountResV1": { + "v1.CreateSQLAuditRecordResV1": { "type": "object", "properties": { "code": { @@ -12959,10 +8245,8 @@ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RoleUserCount" - } + "type": "object", + "$ref": "#/definitions/v1.SQLAuditRecordResData" }, "message": { "type": "string", @@ -12970,174 +8254,190 @@ } } }, - "v1.GetRolesResV1": { + "v1.CreateWorkflowReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { + "task_ids": { "type": "array", "items": { - "$ref": "#/definitions/v1.RoleResV1" + "type": "integer" } }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" + "workflow_subject": { + "type": "string" } } }, - "v1.GetRuleKnowledgeResV1": { + "v1.CustomRuleResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "annotation": { + "type": "string", + "example": "this is test rule" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.RuleKnowledgeResV1" + "db_type": { + "type": "string", + "example": "MySQL" }, - "message": { + "desc": { "type": "string", - "example": "ok" - } - } - }, - "v1.GetRuleTemplateResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 + "example": "this is test rule" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.RuleTemplateDetailResV1" + "level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "example": "notice" }, - "message": { + "rule_id": { + "type": "string" + }, + "rule_script": { + "type": "string" + }, + "type": { "type": "string", - "example": "ok" + "example": "DDL规则" } } }, - "v1.GetRuleTemplateTipsResV1": { + "v1.DBTypeAuditPlan": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleTemplateTipResV1" + "$ref": "#/definitions/v1.AuditPlanCount" } }, - "message": { - "type": "string", - "example": "ok" + "db_type": { + "type": "string" } } }, - "v1.GetRuleTemplatesResV1": { + "v1.DBTypeHealth": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { + "health_instance_names": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleTemplateResV1" + "type": "string" } }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" + "unhealth_instance_names": { + "type": "array", + "items": { + "type": "string" + } } } }, - "v1.GetRuleTypeByDBTypeResV1": { + "v1.DashboardResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleTypeV1" - } - }, - "message": { - "type": "string", - "example": "ok" + "workflow_statistics": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowStatisticsResV1" } } }, - "v1.GetRulesResV1": { + "v1.DingTalkConfigurationV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleResV1" - } + "app_key": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "is_enable_ding_talk_notify": { + "type": "boolean" } } }, - "v1.GetSMTPConfigurationResV1": { + "v1.DirectAuditFileReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "file_contents": { + "description": "调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现\n每个数组元素是一个文件内容", + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "select * from t1; select * from t2;" + ] }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.SMTPConfigurationResV1" + "instance_name": { + "type": "string", + "example": "instance1" }, - "message": { + "instance_type": { "type": "string", - "example": "ok" + "example": "MySQL" + }, + "project_name": { + "type": "string", + "example": "project1" + }, + "schema_name": { + "type": "string", + "example": "schema1" + }, + "sql_type": { + "type": "string", + "enum": [ + "sql", + "mybatis", + "" + ], + "example": "sql" } } }, - "v1.GetSQLAnalysisDataResItemV1": { + "v1.DirectAuditReqV1": { "type": "object", "properties": { - "sql_explain": { - "type": "object", - "$ref": "#/definitions/v1.SQLExplain" + "instance_name": { + "type": "string", + "example": "instance1" + }, + "instance_type": { + "type": "string", + "example": "MySQL" + }, + "project_name": { + "type": "string", + "example": "project1" + }, + "schema_name": { + "type": "string", + "example": "schema1" + }, + "sql_content": { + "description": "调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现", + "type": "string", + "example": "select * from t1; select * from t2;" }, - "table_metas": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMeta" - } + "sql_type": { + "type": "string", + "enum": [ + "sql", + "mybatis", + "" + ], + "example": "sql" } } }, - "v1.GetSQLAuditRecordResV1": { + "v1.DirectAuditResV1": { "type": "object", "properties": { "code": { @@ -13146,7 +8446,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.SQLAuditRecord" + "$ref": "#/definitions/v1.AuditResDataV1" }, "message": { "type": "string", @@ -13154,7 +8454,7 @@ } } }, - "v1.GetSQLAuditRecordTagTipsResV1": { + "v1.DirectGetSQLAnalysisResV1": { "type": "object", "properties": { "code": { @@ -13164,7 +8464,7 @@ "data": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.SqlAnalysisResDataV1" } }, "message": { @@ -13173,88 +8473,60 @@ } } }, - "v1.GetSQLAuditRecordsResV1": { + "v1.DriversResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "driver_name_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.SQLAuditRecord" + "type": "string" } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" } } }, - "v1.GetSQLEInfoResDataV1": { + "v1.ExplainClassicResult": { "type": "object", "properties": { - "logo_url": { - "type": "string" - }, - "title": { - "type": "string" + "head": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMetaItemHeadResV1" + } }, - "version": { - "type": "string" + "rows": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } } } }, - "v1.GetSQLEInfoResV1": { + "v1.FeishuConfigurationV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetSQLEInfoResDataV1" + "app_id": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.GetSQLQueryConfigurationResDataV1": { - "type": "object", - "properties": { - "enable_sql_query": { + "is_feishu_notification_enabled": { "type": "boolean" - }, - "sql_query_root_uri": { - "type": "string" } } }, - "v1.GetSQLQueryConfigurationResV1": { + "v1.FullSyncAuditPlanSQLsReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.GetSQLQueryConfigurationResDataV1" - }, - "message": { - "type": "string", - "example": "ok" + "audit_plan_sql_list": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.AuditPlanSQLReqV1" + } } } }, - "v1.GetSqlAverageExecutionTimeResV1": { + "v1.GetAuditPlanAnalysisDataResV1": { "type": "object", "properties": { "code": { @@ -13262,10 +8534,8 @@ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.SqlAverageExecutionTime" - } + "type": "object", + "$ref": "#/definitions/v1.GetSQLAnalysisDataResItemV1" }, "message": { "type": "string", @@ -13273,7 +8543,7 @@ } } }, - "v1.GetSqlExecutionFailPercentResV1": { + "v1.GetAuditPlanMetasResV1": { "type": "object", "properties": { "code": { @@ -13283,7 +8553,7 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.SqlExecutionFailPercent" + "$ref": "#/definitions/v1.AuditPlanMetaV1" } }, "message": { @@ -13292,35 +8562,30 @@ } } }, - "v1.GetSqlManageListResp": { + "v1.GetAuditPlanNotifyConfigResDataV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.SqlManage" - } + "enable_email_notify": { + "type": "boolean" }, - "message": { - "type": "string", - "example": "ok" + "enable_web_hook_notify": { + "type": "boolean" }, - "sql_manage_bad_num": { + "notify_interval": { "type": "integer" }, - "sql_manage_optimized_num": { - "type": "integer" + "notify_level": { + "type": "string" }, - "sql_manage_total_num": { - "type": "integer" + "web_hook_template": { + "type": "string" + }, + "web_hook_url": { + "type": "string" } } }, - "v1.GetSqlManageRuleTipsResp": { + "v1.GetAuditPlanNotifyConfigResV1": { "type": "object", "properties": { "code": { @@ -13328,10 +8593,8 @@ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleTips" - } + "type": "object", + "$ref": "#/definitions/v1.GetAuditPlanNotifyConfigResDataV1" }, "message": { "type": "string", @@ -13339,7 +8602,7 @@ } } }, - "v1.GetSqlManageSqlAnalysisResp": { + "v1.GetAuditPlanReportResV1": { "type": "object", "properties": { "code": { @@ -13348,7 +8611,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.SqlAnalysis" + "$ref": "#/definitions/v1.AuditPlanReportResV1" }, "message": { "type": "string", @@ -13356,7 +8619,7 @@ } } }, - "v1.GetSyncInstanceTaskListResV1": { + "v1.GetAuditPlanReportSQLsResV1": { "type": "object", "properties": { "code": { @@ -13366,33 +8629,19 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.InstanceTaskResV1" + "$ref": "#/definitions/v1.AuditPlanReportSQLResV1" } }, "message": { "type": "string", "example": "ok" - } - } - }, - "v1.GetSyncInstanceTaskResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.InstanceTaskDetailResV1" }, - "message": { - "type": "string", - "example": "ok" + "total_nums": { + "type": "integer" } } }, - "v1.GetSyncTaskSourceTipsResV1": { + "v1.GetAuditPlanReportsResV1": { "type": "object", "properties": { "code": { @@ -13402,33 +8651,19 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.SyncTaskTipsResV1" + "$ref": "#/definitions/v1.AuditPlanReportResV1" } }, "message": { "type": "string", "example": "ok" - } - } - }, - "v1.GetSystemVariablesResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.SystemVariablesResV1" }, - "message": { - "type": "string", - "example": "ok" + "total_nums": { + "type": "integer" } } }, - "v1.GetTableMetadataResV1": { + "v1.GetAuditPlanResV1": { "type": "object", "properties": { "code": { @@ -13437,7 +8672,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.InstanceTableMeta" + "$ref": "#/definitions/v1.AuditPlanResV1" }, "message": { "type": "string", @@ -13445,22 +8680,7 @@ } } }, - "v1.GetTaskAnalysisDataResItemV1": { - "type": "object", - "properties": { - "sql_explain": { - "type": "object", - "$ref": "#/definitions/v1.SQLExplain" - }, - "table_metas": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMeta" - } - } - } - }, - "v1.GetTaskAnalysisDataResV1": { + "v1.GetAuditPlanSQLsResV1": { "type": "object", "properties": { "code": { @@ -13469,32 +8689,18 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.GetTaskAnalysisDataResItemV1" + "$ref": "#/definitions/v1.AuditPlanSQLResV1" }, "message": { "type": "string", "example": "ok" - } - } - }, - "v1.GetUserDetailResV1": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.UserDetailResV1" }, - "message": { - "type": "string", - "example": "ok" + "total_nums": { + "type": "integer" } } }, - "v1.GetUserGroupTipsResV1": { + "v1.GetAuditPlanTypesResV1": { "type": "object", "properties": { "code": { @@ -13504,7 +8710,7 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.UserGroupTipListItem" + "$ref": "#/definitions/v1.AuditPlanTypesV1" } }, "message": { @@ -13513,7 +8719,7 @@ } } }, - "v1.GetUserGroupsResV1": { + "v1.GetAuditPlansResV1": { "type": "object", "properties": { "code": { @@ -13523,7 +8729,7 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.UserGroupListItemResV1" + "$ref": "#/definitions/v1.AuditPlanResV1" } }, "message": { @@ -13535,7 +8741,7 @@ } } }, - "v1.GetUserLoginResV1": { + "v1.GetAuditTaskResV1": { "type": "object", "properties": { "code": { @@ -13544,7 +8750,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.UserLoginResV1" + "$ref": "#/definitions/v1.AuditTaskResV1" }, "message": { "type": "string", @@ -13552,7 +8758,7 @@ } } }, - "v1.GetUserTipsResV1": { + "v1.GetAuditTaskSQLContentResV1": { "type": "object", "properties": { "code": { @@ -13560,10 +8766,8 @@ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.UserTipResV1" - } + "type": "object", + "$ref": "#/definitions/v1.AuditTaskSQLContentResV1" }, "message": { "type": "string", @@ -13571,7 +8775,7 @@ } } }, - "v1.GetUsersResV1": { + "v1.GetAuditTaskSQLsResV1": { "type": "object", "properties": { "code": { @@ -13581,7 +8785,7 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.UserResV1" + "$ref": "#/definitions/v1.AuditTaskSQLResV1" } }, "message": { @@ -13593,7 +8797,7 @@ } } }, - "v1.GetWeChatConfigurationResV1": { + "v1.GetAuditWhitelistResV1": { "type": "object", "properties": { "code": { @@ -13601,16 +8805,21 @@ "example": 0 }, "data": { - "type": "object", - "$ref": "#/definitions/v1.WeChatConfigurationResV1" + "type": "array", + "items": { + "$ref": "#/definitions/v1.AuditWhitelistResV1" + } }, "message": { "type": "string", "example": "ok" + }, + "total_nums": { + "type": "integer" } } }, - "v1.GetWorkflowAuditPassPercentResV1": { + "v1.GetCompanyNoticeResp": { "type": "object", "properties": { "code": { @@ -13619,7 +8828,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowAuditPassPercentV1" + "$ref": "#/definitions/v1.CompanyNotice" }, "message": { "type": "string", @@ -13627,7 +8836,7 @@ } } }, - "v1.GetWorkflowCountsResV1": { + "v1.GetCustomRuleResV1": { "type": "object", "properties": { "code": { @@ -13636,7 +8845,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowCountsV1" + "$ref": "#/definitions/v1.CustomRuleResV1" }, "message": { "type": "string", @@ -13644,7 +8853,7 @@ } } }, - "v1.GetWorkflowCreatedCountsEachDayResV1": { + "v1.GetCustomRulesResV1": { "type": "object", "properties": { "code": { @@ -13652,8 +8861,10 @@ "example": 0 }, "data": { - "type": "object", - "$ref": "#/definitions/v1.WorkflowCreatedCountsEachDayV1" + "type": "array", + "items": { + "$ref": "#/definitions/v1.CustomRuleResV1" + } }, "message": { "type": "string", @@ -13661,7 +8872,7 @@ } } }, - "v1.GetWorkflowDurationOfWaitingForAuditResV1": { + "v1.GetDashboardResV1": { "type": "object", "properties": { "code": { @@ -13670,7 +8881,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowStageDuration" + "$ref": "#/definitions/v1.DashboardResV1" }, "message": { "type": "string", @@ -13678,7 +8889,7 @@ } } }, - "v1.GetWorkflowDurationOfWaitingForExecutionResV1": { + "v1.GetDingTalkConfigurationResV1": { "type": "object", "properties": { "code": { @@ -13687,7 +8898,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowStageDuration" + "$ref": "#/definitions/v1.DingTalkConfigurationV1" }, "message": { "type": "string", @@ -13695,7 +8906,7 @@ } } }, - "v1.GetWorkflowPassPercentResV1": { + "v1.GetDriversResV1": { "type": "object", "properties": { "code": { @@ -13704,7 +8915,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowPassPercentV1" + "$ref": "#/definitions/v1.DriversResV1" }, "message": { "type": "string", @@ -13712,7 +8923,7 @@ } } }, - "v1.GetWorkflowPercentCountedByInstanceTypeResV1": { + "v1.GetFeishuAuditConfigurationResV1": { "type": "object", "properties": { "code": { @@ -13721,7 +8932,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowPercentCountedByInstanceTypeV1" + "$ref": "#/definitions/v1.FeishuConfigurationV1" }, "message": { "type": "string", @@ -13729,7 +8940,7 @@ } } }, - "v1.GetWorkflowRejectedPercentGroupByCreatorResV1": { + "v1.GetInstanceConnectableResV1": { "type": "object", "properties": { "code": { @@ -13737,10 +8948,8 @@ "example": 0 }, "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.WorkflowRejectedPercentGroupByCreator" - } + "type": "object", + "$ref": "#/definitions/v1.InstanceConnectableResV1" }, "message": { "type": "string", @@ -13748,7 +8957,7 @@ } } }, - "v1.GetWorkflowRejectedPercentGroupByInstanceResV1": { + "v1.GetInstanceHealthResV1": { "type": "object", "properties": { "code": { @@ -13758,7 +8967,7 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.WorkflowRejectedPercentGroupByInstance" + "$ref": "#/definitions/v1.DBTypeHealth" } }, "message": { @@ -13767,7 +8976,7 @@ } } }, - "v1.GetWorkflowResV1": { + "v1.GetInstanceSchemaResV1": { "type": "object", "properties": { "code": { @@ -13776,7 +8985,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowResV1" + "$ref": "#/definitions/v1.InstanceSchemaResV1" }, "message": { "type": "string", @@ -13784,7 +8993,7 @@ } } }, - "v1.GetWorkflowStatusCountResV1": { + "v1.GetInstanceTipsResV1": { "type": "object", "properties": { "code": { @@ -13792,8 +9001,10 @@ "example": 0 }, "data": { - "type": "object", - "$ref": "#/definitions/v1.WorkflowStatusCountV1" + "type": "array", + "items": { + "$ref": "#/definitions/v1.InstanceTipResV1" + } }, "message": { "type": "string", @@ -13801,70 +9012,37 @@ } } }, - "v1.GetWorkflowTasksItemV1": { + "v1.GetInstancesTypePercentResV1": { "type": "object", "properties": { - "current_step_assignee_user_name_list": { - "type": "array", - "items": { - "type": "string" - } - }, - "exec_end_time": { - "type": "string" - }, - "exec_start_time": { - "type": "string" - }, - "execution_user_name": { - "type": "string" - }, - "instance_maintenance_times": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MaintenanceTimeResV1" - } - }, - "instance_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "schedule_time": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.InstancesTypePercentV1" }, - "status": { + "message": { "type": "string", - "enum": [ - "wait_for_audit", - "wait_for_execution", - "exec_scheduled", - "exec_failed", - "exec_succeeded", - "executing", - "manually_executed" - ] - }, - "task_id": { - "type": "integer" - }, - "task_pass_rate": { - "type": "number" - }, - "task_score": { - "type": "integer" + "example": "ok" } } }, - "v1.GetWorkflowTasksResV1": { + "v1.GetLicenseResV1": { "type": "object", "properties": { "code": { "type": "integer", "example": 0 }, - "data": { + "content": { + "type": "string" + }, + "license": { "type": "array", "items": { - "$ref": "#/definitions/v1.GetWorkflowTasksItemV1" + "$ref": "#/definitions/v1.LicenseItem" } }, "message": { @@ -13873,7 +9051,7 @@ } } }, - "v1.GetWorkflowTemplateResV1": { + "v1.GetLicenseUsageResV1": { "type": "object", "properties": { "code": { @@ -13882,7 +9060,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.WorkflowTemplateDetailResV1" + "$ref": "#/definitions/v1.LicenseUsageV1" }, "message": { "type": "string", @@ -13890,7 +9068,7 @@ } } }, - "v1.GetWorkflowWebHookConfigResV1": { + "v1.GetOperationActionListResV1": { "type": "object", "properties": { "code": { @@ -13898,8 +9076,10 @@ "example": 0 }, "data": { - "type": "object", - "$ref": "#/definitions/v1.WebHookConfigV1" + "type": "array", + "items": { + "$ref": "#/definitions/v1.OperationActionList" + } }, "message": { "type": "string", @@ -13907,7 +9087,7 @@ } } }, - "v1.GetWorkflowsResV1": { + "v1.GetOperationRecordListResV1": { "type": "object", "properties": { "code": { @@ -13917,7 +9097,7 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.WorkflowDetailResV1" + "$ref": "#/definitions/v1.OperationRecordList" } }, "message": { @@ -13929,420 +9109,273 @@ } } }, - "v1.GlobalRuleTemplateInstance": { - "type": "object", - "properties": { - "instance_name": { - "type": "string" - }, - "project_name": { - "type": "string" - } - } - }, - "v1.InstanceAdditionalMetaV1": { - "type": "object", - "properties": { - "db_type": { - "type": "string" - }, - "params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamResV1" - } - } - } - }, - "v1.InstanceAdditionalParamReqV1": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "v1.InstanceAdditionalParamResV1": { - "type": "object", - "properties": { - "description": { - "type": "string", - "example": "参数项中文名" - }, - "name": { - "type": "string", - "example": "param name" - }, - "type": { - "type": "string", - "example": "int" - }, - "value": { - "type": "string", - "example": "0" - } - } - }, - "v1.InstanceConnectableResV1": { - "type": "object", - "properties": { - "connect_error_message": { - "type": "string" - }, - "is_instance_connectable": { - "type": "boolean" - } - } - }, - "v1.InstanceConnectionResV1": { - "type": "object", - "properties": { - "connect_error_message": { - "type": "string" - }, - "instance_name": { - "type": "string" - }, - "is_instance_connectable": { - "type": "boolean" - } - } - }, - "v1.InstanceForCheckConnection": { - "type": "object", - "properties": { - "name": { - "type": "string" - } - } - }, - "v1.InstanceForCreatingTask": { - "type": "object", - "properties": { - "instance_name": { - "type": "string" - }, - "instance_schema": { - "type": "string" - } - } - }, - "v1.InstanceResV1": { + "v1.GetOperationTypeNamesListResV1": { "type": "object", "properties": { - "additional_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamResV1" - } - }, - "db_host": { - "type": "string", - "example": "10.10.10.10" - }, - "db_port": { - "type": "string", - "example": "3306" - }, - "db_type": { - "type": "string", - "example": "mysql" - }, - "db_user": { - "type": "string", - "example": "root" - }, - "desc": { - "type": "string", - "example": "this is a instance" - }, - "instance_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "maintenance_times": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.MaintenanceTimeResV1" + "$ref": "#/definitions/v1.OperationTypeNameList" } }, - "rule_template_name": { - "type": "string" - }, - "source": { + "message": { "type": "string", - "example": "SQLE" - }, - "sql_query_config": { - "type": "object", - "$ref": "#/definitions/v1.SQLQueryConfigResV1" + "example": "ok" } } }, - "v1.InstanceSchemaResV1": { + "v1.GetOperationsResV1": { "type": "object", "properties": { - "schema_name_list": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.OperationResV1" } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.InstanceTableMeta": { + "v1.GetProjectRuleTemplateResV1": { "type": "object", "properties": { - "columns": { - "type": "object", - "$ref": "#/definitions/v1.TableColumns" - }, - "create_table_sql": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "indexes": { + "data": { "type": "object", - "$ref": "#/definitions/v1.TableIndexes" - }, - "name": { - "type": "string" + "$ref": "#/definitions/v1.RuleProjectTemplateDetailResV1" }, - "schema": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.InstanceTaskDetailResV1": { + "v1.GetProjectRuleTemplatesResV1": { "type": "object", "properties": { - "db_type": { - "type": "string", - "example": "mysql" - }, - "id": { + "code": { "type": "integer", - "example": 1 - }, - "rule_template": { - "type": "string", - "example": "default_mysql" - }, - "source": { - "type": "string", - "example": "actiontech-dmp" + "example": 0 }, - "sync_instance_interval": { - "type": "string", - "example": "0 0 * * *" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.ProjectRuleTemplateResV1" + } }, - "url": { + "message": { "type": "string", - "example": "http://10.186.62.56:10000" + "example": "ok" }, - "version": { - "type": "string", - "example": "1.23.1" + "total_nums": { + "type": "integer" } } }, - "v1.InstanceTaskResV1": { + "v1.GetProjectScoreResV1": { "type": "object", "properties": { - "db_type": { - "type": "string", - "example": "mysql" - }, - "id": { + "code": { "type": "integer", - "example": 1 - }, - "last_sync_status": { - "type": "string", - "enum": [ - "succeeded", - "failed" - ], - "example": "succeeded" - }, - "last_sync_success_time": { - "type": "string", - "example": "2021-08-12 12:00:00" - }, - "source": { - "type": "string", - "example": "actiontech-dmp" + "example": 0 }, - "url": { - "type": "string", - "example": "http://10.186.62.56:10000" + "data": { + "type": "object", + "$ref": "#/definitions/v1.ProjectScore" }, - "version": { + "message": { "type": "string", - "example": "1.23.1" + "example": "ok" } } }, - "v1.InstanceTipResV1": { + "v1.GetProjectStatisticsResDataV1": { "type": "object", "properties": { - "host": { - "type": "string" + "audit_plan_total": { + "type": "integer" }, - "instance_name": { - "type": "string" + "instance_total": { + "type": "integer" }, - "instance_type": { - "type": "string" + "member_total": { + "type": "integer" }, - "port": { - "type": "string" + "rule_template_total": { + "type": "integer" }, - "workflow_template_id": { + "whitelist_total": { + "type": "integer" + }, + "workflow_total": { "type": "integer" } } }, - "v1.InstanceTypePercent": { + "v1.GetProjectStatisticsResV1": { "type": "object", "properties": { - "count": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 }, - "percent": { - "type": "number" + "data": { + "type": "object", + "$ref": "#/definitions/v1.GetProjectStatisticsResDataV1" }, - "type": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.InstancesTypePercentV1": { + "v1.GetRiskAuditPlanResV1": { "type": "object", "properties": { - "instance_total_num": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 }, - "instance_type_percents": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.InstanceTypePercent" + "$ref": "#/definitions/v1.RiskAuditPlan" } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.LDAPConfigurationReqV1": { + "v1.GetRoleUserCountResV1": { "type": "object", "properties": { - "enable_ldap": { - "type": "boolean" - }, - "enable_ssl": { - "type": "boolean" - }, - "ldap_connect_dn": { - "type": "string" - }, - "ldap_connect_pwd": { - "type": "string" - }, - "ldap_search_base_dn": { - "type": "string" - }, - "ldap_server_host": { - "type": "string" - }, - "ldap_server_port": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "ldap_user_email_rdn_key": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RoleUserCount" + } }, - "ldap_user_name_rdn_key": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.LDAPConfigurationResV1": { + "v1.GetRuleKnowledgeResV1": { "type": "object", "properties": { - "enable_ldap": { - "type": "boolean" - }, - "enable_ssl": { - "type": "boolean" - }, - "ldap_connect_dn": { - "type": "string" - }, - "ldap_search_base_dn": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "ldap_server_host": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.RuleKnowledgeResV1" }, - "ldap_server_port": { - "type": "string" + "message": { + "type": "string", + "example": "ok" + } + } + }, + "v1.GetRuleTemplateResV1": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 0 }, - "ldap_user_email_rdn_key": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.RuleTemplateDetailResV1" }, - "ldap_user_name_rdn_key": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.LicenseItem": { + "v1.GetRuleTemplateTipsResV1": { "type": "object", "properties": { - "description": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "limit": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleTemplateTipResV1" + } }, - "name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.LicenseUsageItem": { + "v1.GetRuleTemplatesResV1": { "type": "object", "properties": { - "is_limited": { - "type": "boolean" - }, - "limit": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 }, - "resource_type": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleTemplateResV1" + } }, - "resource_type_desc": { - "type": "string" + "message": { + "type": "string", + "example": "ok" }, - "used": { + "total_nums": { "type": "integer" } } }, - "v1.LicenseUsageV1": { + "v1.GetRuleTypeByDBTypeResV1": { "type": "object", "properties": { - "instances_usage": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.LicenseUsageItem" + "$ref": "#/definitions/v1.RuleTypeV1" } }, - "users_usage": { - "type": "object", - "$ref": "#/definitions/v1.LicenseUsageItem" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ListTableBySchemaResV1": { + "v1.GetRulesResV1": { "type": "object", "properties": { "code": { @@ -14352,7 +9385,7 @@ "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.Table" + "$ref": "#/definitions/v1.RuleResV1" } }, "message": { @@ -14361,213 +9394,183 @@ } } }, - "v1.MaintenanceTimeReqV1": { + "v1.GetSQLAnalysisDataResItemV1": { "type": "object", "properties": { - "maintenance_start_time": { + "sql_explain": { "type": "object", - "$ref": "#/definitions/v1.TimeReqV1" + "$ref": "#/definitions/v1.SQLExplain" }, - "maintenance_stop_time": { - "type": "object", - "$ref": "#/definitions/v1.TimeReqV1" + "table_metas": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMeta" + } } } }, - "v1.MaintenanceTimeResV1": { + "v1.GetSQLAuditRecordResV1": { "type": "object", "properties": { - "maintenance_start_time": { - "type": "object", - "$ref": "#/definitions/v1.TimeResV1" + "code": { + "type": "integer", + "example": 0 }, - "maintenance_stop_time": { + "data": { "type": "object", - "$ref": "#/definitions/v1.TimeResV1" + "$ref": "#/definitions/v1.SQLAuditRecord" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ManagementPermissionResV1": { + "v1.GetSQLAuditRecordTagTipsResV1": { "type": "object", "properties": { "code": { - "type": "integer" + "type": "integer", + "example": 0 }, - "desc": { - "type": "string" - } - } - }, - "v1.MemberGroupUserItem": { - "type": "object", - "properties": { - "name": { - "type": "string" - } - } - }, - "v1.MemberTipResV1": { - "type": "object", - "properties": { - "user_name": { - "type": "string" + "data": { + "type": "array", + "items": { + "type": "string" + } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.Oauth2ConfigurationReqV1": { + "v1.GetSQLAuditRecordsResV1": { "type": "object", "properties": { - "access_token_tag": { - "type": "string" - }, - "client_host": { - "type": "string" - }, - "client_id": { - "type": "string" - }, - "client_key": { - "type": "string" - }, - "enable_oauth2": { - "type": "boolean" - }, - "login_tip": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "scopes": { + "data": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.SQLAuditRecord" } }, - "server_auth_url": { - "type": "string" - }, - "server_token_url": { - "type": "string" - }, - "server_user_id_url": { - "type": "string" + "message": { + "type": "string", + "example": "ok" }, - "user_id_tag": { - "type": "string" + "total_nums": { + "type": "integer" } } }, - "v1.Operation": { + "v1.GetSqlAverageExecutionTimeResV1": { "type": "object", "properties": { - "op_code": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 }, - "op_desc": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.SqlAverageExecutionTime" + } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.OperationActionList": { + "v1.GetSqlExecutionFailPercentResV1": { "type": "object", "properties": { - "desc": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "operation_action": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.SqlExecutionFailPercent" + } }, - "operation_type": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.OperationRecordList": { + "v1.GetSqlManageListResp": { "type": "object", "properties": { - "id": { - "type": "integer" - }, - "operation_action": { - "type": "string" - }, - "operation_content": { - "type": "string" - }, - "operation_time": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "operation_type_name": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.SqlManage" + } }, - "operation_user": { - "type": "object", - "$ref": "#/definitions/v1.OperationUser" + "message": { + "type": "string", + "example": "ok" }, - "project_name": { - "type": "string" + "sql_manage_bad_num": { + "type": "integer" }, - "status": { - "type": "string", - "enum": [ - "succeeded", - "failed" - ] - } - } - }, - "v1.OperationResV1": { - "type": "object", - "properties": { - "op_code": { + "sql_manage_optimized_num": { "type": "integer" }, - "op_desc": { - "type": "string" + "sql_manage_total_num": { + "type": "integer" } } }, - "v1.OperationTypeNameList": { + "v1.GetSqlManageRuleTipsResp": { "type": "object", "properties": { - "desc": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "operation_type_name": { - "type": "string" - } - } - }, - "v1.OperationUser": { - "type": "object", - "properties": { - "ip": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleTips" + } }, - "user_name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ParseProjectRuleTemplateFileResDataV1": { + "v1.GetSqlManageSqlAnalysisResp": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "name": { - "type": "string" + "data": { + "description": "V1版本不能引用V2版本的结构体,所以只能复制一份", + "type": "object", + "$ref": "#/definitions/v1.SqlAnalysis" }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleResV1" - } + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ParseProjectRuleTemplateFileResV1": { + "v1.GetSystemVariablesResV1": { "type": "object", "properties": { "code": { @@ -14576,7 +9579,7 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.ParseProjectRuleTemplateFileResDataV1" + "$ref": "#/definitions/v1.SystemVariablesResV1" }, "message": { "type": "string", @@ -14584,795 +9587,708 @@ } } }, - "v1.PartialSyncAuditPlanSQLsReqV1": { + "v1.GetTableMetadataResV1": { "type": "object", "properties": { - "audit_plan_sql_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditPlanSQLReqV1" - } + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.InstanceTableMeta" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.PatchUserGroupReqV1": { + "v1.GetTaskAnalysisDataResItemV1": { "type": "object", "properties": { - "is_disabled": { - "type": "boolean" - }, - "user_group_desc": { - "type": "string", - "example": "this is a group" + "sql_explain": { + "type": "object", + "$ref": "#/definitions/v1.SQLExplain" }, - "user_name_list": { + "table_metas": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.TableMeta" } } } }, - "v1.PerformanceStatistics": { + "v1.GetTaskAnalysisDataResV1": { "type": "object", "properties": { - "affect_rows": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "object", - "$ref": "#/definitions/v1.AffectRows" - } - } - }, - "v1.PersonaliseReqV1": { - "type": "object", - "properties": { - "title": { - "type": "string" + "$ref": "#/definitions/v1.GetTaskAnalysisDataResItemV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectDetailItem": { + "v1.GetUserTipsResV1": { "type": "object", "properties": { - "archived": { - "type": "boolean" - }, - "create_time": { - "type": "string" - }, - "create_user_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "desc": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.UserTipResV1" + } }, - "name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectListItem": { + "v1.GetWorkflowAuditPassPercentResV1": { "type": "object", "properties": { - "archived": { - "type": "boolean" - }, - "create_time": { - "type": "string" - }, - "create_user_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "desc": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowAuditPassPercentV1" }, - "name": { - "type": "string" - } - } - }, - "v1.ProjectRuleTemplateInstance": { - "type": "object", - "properties": { - "name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectRuleTemplateResV1": { + "v1.GetWorkflowCountsResV1": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "instance_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ProjectRuleTemplateInstance" - } + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowCountsV1" }, - "rule_template_name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectScore": { + "v1.GetWorkflowCreatedCountsEachDayResV1": { "type": "object", "properties": { - "score": { - "type": "integer" + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowCreatedCountsEachDayV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.ProjectTipResV1": { + "v1.GetWorkflowDurationOfWaitingForAuditResV1": { "type": "object", "properties": { - "project_name": { - "type": "string" + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowStageDuration" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RejectWorkflowReqV1": { + "v1.GetWorkflowDurationOfWaitingForExecutionResV1": { "type": "object", "properties": { - "reason": { - "type": "string" + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowStageDuration" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RiskAuditPlan": { + "v1.GetWorkflowPassPercentResV1": { "type": "object", "properties": { - "audit_plan_name": { - "type": "string" - }, - "audit_plan_report_id": { - "type": "integer" - }, - "audit_plan_report_timestamp": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "risk_sql_count": { - "type": "integer" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowPassPercentV1" }, - "trigger_audit_plan_time": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RiskWorkflow": { + "v1.GetWorkflowPercentCountedByInstanceTypeResV1": { "type": "object", "properties": { - "create_user_name": { - "type": "string" - }, - "update_time": { - "type": "string" - }, - "workflow_id": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "workflow_name": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowPercentCountedByInstanceTypeV1" }, - "workflow_status": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RoleResV1": { + "v1.GetWorkflowRejectedPercentGroupByCreatorResV1": { "type": "object", "properties": { - "is_disabled": { - "type": "boolean" + "code": { + "type": "integer", + "example": 0 }, - "operation_list": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.Operation" + "$ref": "#/definitions/v1.WorkflowRejectedPercentGroupByCreator" } }, - "role_desc": { - "type": "string" - }, - "role_name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RoleTipResV1": { + "v1.GetWorkflowRejectedPercentGroupByInstanceResV1": { "type": "object", "properties": { - "operations": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.Operation" + "$ref": "#/definitions/v1.WorkflowRejectedPercentGroupByInstance" } }, - "role_name": { - "type": "string" - } - } - }, - "v1.RoleUserCount": { - "type": "object", - "properties": { - "count": { - "type": "integer" - }, - "role": { - "type": "string" - } - } - }, - "v1.RuleInfo": { - "type": "object", - "properties": { - "annotation": { - "type": "string", - "example": "this is test rule" - }, - "desc": { + "message": { "type": "string", - "example": "this is test rule" + "example": "ok" } } }, - "v1.RuleKnowledgeResV1": { + "v1.GetWorkflowResV1": { "type": "object", "properties": { - "knowledge_content": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "rule": { + "data": { "type": "object", - "$ref": "#/definitions/v1.RuleInfo" + "$ref": "#/definitions/v1.WorkflowResV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RuleParamReqV1": { + "v1.GetWorkflowStatusCountResV1": { "type": "object", "properties": { - "key": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "value": { - "type": "string" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowStatusCountV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RuleParamResV1": { + "v1.GetWorkflowTasksItemV1": { "type": "object", "properties": { - "desc": { + "current_step_assignee_user_name_list": { + "type": "array", + "items": { + "type": "string" + } + }, + "exec_end_time": { "type": "string" }, - "key": { + "exec_start_time": { "type": "string" }, - "type": { + "execution_user_name": { + "type": "string" + }, + "instance_maintenance_times": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.MaintenanceTimeResV1" + } + }, + "instance_name": { + "type": "string" + }, + "schedule_time": { + "type": "string" + }, + "status": { "type": "string", "enum": [ - "string", - "int", - "bool" + "wait_for_audit", + "wait_for_execution", + "exec_scheduled", + "exec_failed", + "exec_succeeded", + "executing", + "manually_executed" ] }, - "value": { - "type": "string" + "task_id": { + "type": "integer" + }, + "task_pass_rate": { + "type": "number" + }, + "task_score": { + "type": "integer" } } }, - "v1.RuleProjectTemplateDetailResV1": { + "v1.GetWorkflowTasksResV1": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "instance_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ProjectRuleTemplateInstance" - } + "code": { + "type": "integer", + "example": 0 }, - "rule_list": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleResV1" + "$ref": "#/definitions/v1.GetWorkflowTasksItemV1" } }, - "rule_template_name": { - "type": "string" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.RuleReqV1": { + "v1.GetWorkflowTemplateResV1": { "type": "object", "properties": { - "is_custom_rule": { - "type": "boolean" + "code": { + "type": "integer", + "example": 0 }, - "level": { - "type": "string", - "example": "error" + "data": { + "type": "object", + "$ref": "#/definitions/v1.WorkflowTemplateDetailResV1" }, - "name": { + "message": { "type": "string", - "example": "ddl_check_index_count" + "example": "ok" + } + } + }, + "v1.GetWorkflowsResV1": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 0 }, - "params": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleParamReqV1" + "$ref": "#/definitions/v1.WorkflowDetailResV1" } + }, + "message": { + "type": "string", + "example": "ok" + }, + "total_nums": { + "type": "integer" } } }, - "v1.RuleResV1": { + "v1.InstanceAdditionalParamResV1": { "type": "object", "properties": { - "annotation": { + "description": { "type": "string", - "example": "避免多次 table rebuild 带来的消耗、以及对线上业务的影响" + "example": "参数项中文名" }, - "db_type": { + "name": { "type": "string", - "example": "mysql" - }, - "desc": { - "type": "string" - }, - "is_custom_rule": { - "type": "boolean" + "example": "param name" }, - "level": { + "type": { "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "error" - }, - "params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleParamResV1" - } - }, - "rule_name": { - "type": "string" + "example": "int" }, - "type": { + "value": { "type": "string", - "example": "全局配置" + "example": "0" } } }, - "v1.RuleRespV1": { + "v1.InstanceConnectableResV1": { "type": "object", "properties": { - "desc": { + "connect_error_message": { "type": "string" }, - "rule_name": { - "type": "string" + "is_instance_connectable": { + "type": "boolean" } } }, - "v1.RuleTemplateDetailResV1": { + "v1.InstanceConnectionResV1": { "type": "object", "properties": { - "db_type": { + "connect_error_message": { "type": "string" }, - "desc": { + "instance_name": { "type": "string" }, - "instance_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.GlobalRuleTemplateInstance" - } - }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleResV1" - } - }, - "rule_template_name": { - "type": "string" + "is_instance_connectable": { + "type": "boolean" } } }, - "v1.RuleTemplateResV1": { + "v1.InstanceForCheckConnection": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "desc": { - "type": "string" - }, - "instance_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.GlobalRuleTemplateInstance" - } - }, - "rule_template_name": { + "name": { "type": "string" } } }, - "v1.RuleTemplateTipResV1": { + "v1.InstanceForCreatingTask": { "type": "object", "properties": { - "db_type": { + "instance_name": { "type": "string" }, - "rule_template_name": { + "instance_schema": { "type": "string" } } }, - "v1.RuleTips": { + "v1.InstanceSchemaResV1": { "type": "object", "properties": { - "db_type": { - "type": "string" - }, - "rule": { + "schema_name_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleRespV1" + "type": "string" } } } }, - "v1.RuleTypeV1": { - "type": "object", - "properties": { - "is_custom_rule_type": { - "type": "boolean" - }, - "rule_count": { - "type": "integer" - }, - "rule_type": { - "type": "string" - } - } - }, - "v1.SMTPConfigurationResV1": { + "v1.InstanceTableMeta": { "type": "object", "properties": { - "enable_smtp_notify": { - "type": "boolean" - }, - "is_skip_verify": { - "type": "boolean" + "columns": { + "type": "object", + "$ref": "#/definitions/v1.TableColumns" }, - "smtp_host": { + "create_table_sql": { "type": "string" }, - "smtp_port": { + "indexes": { + "type": "object", + "$ref": "#/definitions/v1.TableIndexes" + }, + "name": { "type": "string" }, - "smtp_username": { + "schema": { "type": "string" } } }, - "v1.SQLAuditRecord": { + "v1.InstanceTipResV1": { "type": "object", "properties": { - "created_at": { + "host": { "type": "string" }, - "creator": { + "instance_id": { "type": "string" }, - "instance": { - "type": "object", - "$ref": "#/definitions/v1.SQLAuditRecordInstance" - }, - "sql_audit_record_id": { + "instance_name": { "type": "string" }, - "sql_audit_status": { + "instance_type": { "type": "string" }, - "tags": { - "type": "array", - "items": { - "type": "string" - } + "port": { + "type": "string" }, - "task": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskResV1" + "workflow_template_id": { + "type": "integer" } } }, - "v1.SQLAuditRecordInstance": { + "v1.InstanceTypePercent": { "type": "object", "properties": { - "db_host": { - "type": "string", - "example": "10.10.10.10" + "count": { + "type": "integer" }, - "db_port": { - "type": "string", - "example": "3306" + "percent": { + "type": "number" + }, + "type": { + "type": "string" } } }, - "v1.SQLAuditRecordResData": { + "v1.InstancesTypePercentV1": { "type": "object", "properties": { - "sql_audit_record_id": { - "type": "string" + "instance_total_num": { + "type": "integer" }, - "task": { - "type": "object", - "$ref": "#/definitions/v1.AuditTaskResV1" + "instance_type_percents": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.InstanceTypePercent" + } } } }, - "v1.SQLExplain": { + "v1.LicenseItem": { "type": "object", "properties": { - "classic_result": { - "description": "explain result in table format", - "type": "object", - "$ref": "#/definitions/v1.ExplainClassicResult" - }, - "message": { + "description": { "type": "string" }, - "sql": { + "limit": { "type": "string" - } - } - }, - "v1.SQLQueryConfigReqV1": { - "type": "object", - "properties": { - "allow_query_when_less_than_audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "error" - }, - "audit_enabled": { - "type": "boolean", - "example": false - }, - "max_pre_query_rows": { - "type": "integer", - "example": 100 }, - "query_timeout_second": { - "type": "integer", - "example": 10 + "name": { + "type": "string" } } }, - "v1.SQLQueryConfigResV1": { + "v1.LicenseUsageItem": { "type": "object", "properties": { - "allow_query_when_less_than_audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ] - }, - "audit_enabled": { + "is_limited": { "type": "boolean" }, - "max_pre_query_rows": { + "limit": { "type": "integer" }, - "query_timeout_second": { + "resource_type": { + "type": "string" + }, + "resource_type_desc": { + "type": "string" + }, + "used": { "type": "integer" } } }, - "v1.Source": { + "v1.LicenseUsageV1": { "type": "object", "properties": { - "audit_plan_name": { - "type": "string" - }, - "sql_audit_record_ids": { + "instances_usage": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.LicenseUsageItem" } }, - "type": { - "type": "string", - "enum": [ - "audit_plan", - "sql_audit_record" - ] - } - } - }, - "v1.SqlAnalysis": { - "type": "object", - "properties": { - "performance_statistics": { - "type": "object", - "$ref": "#/definitions/v1.PerformanceStatistics" - }, - "sql_explain": { - "type": "object", - "$ref": "#/definitions/v1.SQLExplain" - }, - "table_metas": { + "users_usage": { "type": "object", - "$ref": "#/definitions/v1.TableMetas" + "$ref": "#/definitions/v1.LicenseUsageItem" } } }, - "v1.SqlAnalysisResDataV1": { + "v1.ListTableBySchemaResV1": { "type": "object", "properties": { - "sql_explain": { - "type": "object", - "$ref": "#/definitions/v1.SQLExplain" + "code": { + "type": "integer", + "example": 0 }, - "table_metas": { + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.TableMeta" + "$ref": "#/definitions/v1.Table" } + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.SqlAverageExecutionTime": { + "v1.MaintenanceTimeResV1": { "type": "object", "properties": { - "average_execution_seconds": { - "type": "integer" - }, - "instance_name": { - "type": "string" - }, - "max_execution_seconds": { - "type": "integer" + "maintenance_start_time": { + "type": "object", + "$ref": "#/definitions/v1.TimeResV1" }, - "min_execution_seconds": { - "type": "integer" + "maintenance_stop_time": { + "type": "object", + "$ref": "#/definitions/v1.TimeResV1" } } }, - "v1.SqlExecutionFailPercent": { + "v1.OperationActionList": { "type": "object", "properties": { - "instance_name": { + "desc": { "type": "string" }, - "percent": { - "type": "number" + "operation_action": { + "type": "string" + }, + "operation_type": { + "type": "string" } } }, - "v1.SqlManage": { + "v1.OperationRecordList": { "type": "object", "properties": { - "appear_num": { + "id": { "type": "integer" }, - "assignees": { - "type": "array", - "items": { - "type": "string" - } - }, - "audit_result": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.AuditResult" - } - }, - "endpoint": { + "operation_action": { "type": "string" }, - "first_appear_time": { + "operation_content": { "type": "string" }, - "id": { - "type": "integer" - }, - "instance_name": { + "operation_time": { "type": "string" }, - "last_appear_time": { + "operation_type_name": { "type": "string" }, - "remark": { - "type": "string" + "operation_user": { + "type": "object", + "$ref": "#/definitions/v1.OperationUser" }, - "schema_name": { + "project_name": { "type": "string" }, - "source": { - "type": "object", - "$ref": "#/definitions/v1.Source" + "status": { + "type": "string", + "enum": [ + "succeeded", + "failed" + ] + } + } + }, + "v1.OperationResV1": { + "type": "object", + "properties": { + "op_code": { + "type": "integer" }, - "sql": { + "op_desc": { + "type": "string" + } + } + }, + "v1.OperationTypeNameList": { + "type": "object", + "properties": { + "desc": { "type": "string" }, - "sql_fingerprint": { + "operation_type_name": { "type": "string" - }, - "status": { - "type": "string", - "enum": [ - "unhandled", - "solved", - "ignored", - "manual_audited" - ] } } }, - "v1.StatisticAuditPlanResV1": { + "v1.OperationUser": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.DBTypeAuditPlan" - } + "ip": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "user_name": { + "type": "string" } } }, - "v1.StatisticRiskWorkflowResV1": { + "v1.ParseProjectRuleTemplateFileResDataV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { + "desc": { + "type": "string" + }, + "name": { + "type": "string" + }, + "rule_list": { "type": "array", "items": { - "$ref": "#/definitions/v1.RiskWorkflow" + "$ref": "#/definitions/v1.RuleResV1" } - }, - "message": { - "type": "string", - "example": "ok" } } }, - "v1.StatisticsAuditedSQLResV1": { + "v1.ParseProjectRuleTemplateFileResV1": { "type": "object", "properties": { "code": { @@ -15381,424 +10297,421 @@ }, "data": { "type": "object", - "$ref": "#/definitions/v1.AuditedSQLCount" + "$ref": "#/definitions/v1.ParseProjectRuleTemplateFileResDataV1" }, "message": { "type": "string", "example": "ok" - }, - "risk_rate": { - "type": "integer" - } - } - }, - "v1.SyncInstanceResV1": { - "type": "object", - "properties": { - "is_sync_instance_success": { - "type": "boolean", - "example": true - }, - "sync_error_message": { - "type": "string" } } }, - "v1.SyncTaskTipsResV1": { + "v1.PartialSyncAuditPlanSQLsReqV1": { "type": "object", "properties": { - "db_types": { + "audit_plan_sql_list": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.AuditPlanSQLReqV1" } - }, - "source": { - "type": "string", - "example": "actiontech-dmp" } } }, - "v1.SystemVariablesResV1": { + "v1.PerformanceStatistics": { "type": "object", "properties": { - "operation_record_expired_hours": { - "type": "integer" - }, - "url": { - "type": "string" - }, - "workflow_expired_hours": { - "type": "integer" + "affect_rows": { + "type": "object", + "$ref": "#/definitions/v1.AffectRows" } } }, - "v1.Table": { + "v1.ProjectRuleTemplateResV1": { "type": "object", "properties": { - "name": { + "db_type": { + "type": "string" + }, + "desc": { + "type": "string" + }, + "rule_template_name": { "type": "string" } } }, - "v1.TableColumns": { + "v1.ProjectScore": { "type": "object", "properties": { - "head": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMetaItemHeadResV1" - } - }, - "rows": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } + "score": { + "type": "integer" } } }, - "v1.TableIndexes": { + "v1.RejectWorkflowReqV1": { "type": "object", "properties": { - "head": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMetaItemHeadResV1" - } - }, - "rows": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } + "reason": { + "type": "string" } } }, - "v1.TableMeta": { + "v1.RiskAuditPlan": { "type": "object", "properties": { - "columns": { - "type": "object", - "$ref": "#/definitions/v1.TableColumns" - }, - "create_table_sql": { + "audit_plan_name": { "type": "string" }, - "indexes": { - "type": "object", - "$ref": "#/definitions/v1.TableIndexes" + "audit_plan_report_id": { + "type": "integer" }, - "message": { + "audit_plan_report_timestamp": { "type": "string" }, - "name": { - "type": "string" + "risk_sql_count": { + "type": "integer" }, - "schema": { + "trigger_audit_plan_time": { "type": "string" } } }, - "v1.TableMetaItemHeadResV1": { + "v1.RiskWorkflow": { "type": "object", "properties": { - "desc": { + "create_user_name": { "type": "string" }, - "field_name": { + "update_time": { + "type": "string" + }, + "workflow_id": { + "type": "string" + }, + "workflow_name": { + "type": "string" + }, + "workflow_status": { "type": "string" } } }, - "v1.TableMetas": { + "v1.RoleUserCount": { "type": "object", "properties": { - "err_message": { - "type": "string" + "count": { + "type": "integer" }, - "table_meta_items": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.TableMeta" - } + "role": { + "type": "string" } } }, - "v1.TestAuditPlanNotifyConfigResDataV1": { + "v1.RuleInfo": { "type": "object", "properties": { - "is_notify_send_normal": { - "type": "boolean" + "annotation": { + "type": "string", + "example": "this is test rule" }, - "send_error_message": { - "type": "string" + "desc": { + "type": "string", + "example": "this is test rule" } } }, - "v1.TestAuditPlanNotifyConfigResV1": { + "v1.RuleKnowledgeResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "knowledge_content": { + "type": "string" }, - "data": { + "rule": { "type": "object", - "$ref": "#/definitions/v1.TestAuditPlanNotifyConfigResDataV1" - }, - "message": { - "type": "string", - "example": "ok" + "$ref": "#/definitions/v1.RuleInfo" } } }, - "v1.TestDingTalkConfigResDataV1": { + "v1.RuleParamReqV1": { "type": "object", "properties": { - "is_ding_talk_send_normal": { - "type": "boolean" + "key": { + "type": "string" }, - "send_error_message": { + "value": { "type": "string" } } }, - "v1.TestDingTalkConfigResV1": { + "v1.RuleParamResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "desc": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestDingTalkConfigResDataV1" + "key": { + "type": "string" }, - "message": { + "type": { "type": "string", - "example": "ok" + "enum": [ + "string", + "int", + "bool" + ] + }, + "value": { + "type": "string" } } }, - "v1.TestFeishuConfigResDataV1": { + "v1.RuleProjectTemplateDetailResV1": { "type": "object", "properties": { - "error_message": { + "db_type": { "type": "string" }, - "is_message_sent_normally": { - "type": "boolean" + "desc": { + "type": "string" + }, + "rule_list": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleResV1" + } + }, + "rule_template_name": { + "type": "string" } } }, - "v1.TestFeishuConfigResV1": { + "v1.RuleReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "is_custom_rule": { + "type": "boolean" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestFeishuConfigResDataV1" + "level": { + "type": "string", + "example": "error" }, - "message": { + "name": { "type": "string", - "example": "ok" + "example": "ddl_check_index_count" + }, + "params": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleParamReqV1" + } } } }, - "v1.TestFeishuConfigurationReqV1": { + "v1.RuleResV1": { "type": "object", "properties": { - "account": { + "annotation": { + "type": "string", + "example": "避免多次 table rebuild 带来的消耗、以及对线上业务的影响" + }, + "db_type": { + "type": "string", + "example": "mysql" + }, + "desc": { "type": "string" }, - "account_type": { + "is_custom_rule": { + "type": "boolean" + }, + "level": { "type": "string", "enum": [ - "email", - "phone" - ] - } - } - }, - "v1.TestSMTPConfigurationReqV1": { - "type": "object", - "properties": { - "recipient_addr": { + "normal", + "notice", + "warn", + "error" + ], + "example": "error" + }, + "params": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleParamResV1" + } + }, + "rule_name": { "type": "string" + }, + "type": { + "type": "string", + "example": "全局配置" } } }, - "v1.TestSMTPConfigurationResDataV1": { + "v1.RuleRespV1": { "type": "object", "properties": { - "is_smtp_send_normal": { - "type": "boolean" + "desc": { + "type": "string" }, - "send_error_message": { + "rule_name": { "type": "string" } } }, - "v1.TestSMTPConfigurationResV1": { + "v1.RuleTemplateDetailResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestSMTPConfigurationResDataV1" + "desc": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" - } - } - }, - "v1.TestWeChatConfigurationReqV1": { - "type": "object", - "properties": { - "recipient_id": { + "rule_list": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleResV1" + } + }, + "rule_template_name": { "type": "string" } } }, - "v1.TestWeChatConfigurationResDataV1": { + "v1.RuleTemplateResV1": { "type": "object", "properties": { - "is_wechat_send_normal": { - "type": "boolean" + "db_type": { + "type": "string" }, - "send_error_message": { + "desc": { + "type": "string" + }, + "rule_template_name": { "type": "string" } } }, - "v1.TestWeChatConfigurationResV1": { + "v1.RuleTemplateTipResV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "db_type": { + "type": "string" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestWeChatConfigurationResDataV1" + "rule_template_id": { + "type": "string" }, - "message": { - "type": "string", - "example": "ok" + "rule_template_name": { + "type": "string" } } }, - "v1.TestWorkflowWebHookConfigResDataV1": { + "v1.RuleTips": { "type": "object", "properties": { - "send_error_message": { + "db_type": { "type": "string" + }, + "rule": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.RuleRespV1" + } } } }, - "v1.TestWorkflowWebHookConfigResV1": { + "v1.RuleTypeV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "is_custom_rule_type": { + "type": "boolean" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.TestWorkflowWebHookConfigResDataV1" + "rule_count": { + "type": "integer" }, - "message": { - "type": "string", - "example": "ok" + "rule_type": { + "type": "string" } } }, - "v1.TimeReqV1": { + "v1.SQLAuditRecord": { "type": "object", "properties": { - "hour": { - "type": "integer" + "created_at": { + "type": "string" }, - "minute": { - "type": "integer" + "creator": { + "type": "string" + }, + "instance": { + "type": "object", + "$ref": "#/definitions/v1.SQLAuditRecordInstance" + }, + "sql_audit_record_id": { + "type": "string" + }, + "sql_audit_status": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "task": { + "type": "object", + "$ref": "#/definitions/v1.AuditTaskResV1" } } }, - "v1.TimeResV1": { + "v1.SQLAuditRecordInstance": { "type": "object", "properties": { - "hour": { - "type": "integer" + "db_host": { + "type": "string", + "example": "10.10.10.10" }, - "minute": { - "type": "integer" + "db_port": { + "type": "string", + "example": "3306" } } }, - "v1.TriggerAuditPlanResV1": { + "v1.SQLAuditRecordResData": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "sql_audit_record_id": { + "type": "string" }, - "data": { + "task": { "type": "object", - "$ref": "#/definitions/v1.AuditPlanReportResV1" - }, - "message": { - "type": "string", - "example": "ok" + "$ref": "#/definitions/v1.AuditTaskResV1" } } }, - "v1.TriggerSyncInstanceResV1": { + "v1.SQLExplain": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { + "classic_result": { + "description": "explain result in table format", "type": "object", - "$ref": "#/definitions/v1.SyncInstanceResV1" + "$ref": "#/definitions/v1.ExplainClassicResult" }, "message": { - "type": "string", - "example": "ok" + "type": "string" + }, + "sql": { + "type": "string" } } }, - "v1.UpdateAuditPlanNotifyConfigReqV1": { + "v1.SQLQueryConfigResV1": { "type": "object", "properties": { - "enable_email_notify": { - "type": "boolean" - }, - "enable_web_hook_notify": { - "type": "boolean" - }, - "notify_interval": { - "type": "integer", - "default": 10 - }, - "notify_level": { + "allow_query_when_less_than_audit_level": { "type": "string", - "default": "warn", "enum": [ "normal", "notice", @@ -15806,715 +10719,731 @@ "error" ] }, - "web_hook_template": { - "type": "string" + "audit_enabled": { + "type": "boolean" }, - "web_hook_url": { - "type": "string" + "max_pre_query_rows": { + "type": "integer" + }, + "query_timeout_second": { + "type": "integer" } } }, - "v1.UpdateAuditPlanReqV1": { + "v1.Source": { "type": "object", "properties": { - "audit_plan_cron": { - "type": "string", - "example": "0 */2 * * *" - }, - "audit_plan_instance_database": { - "type": "string", - "example": "app1" - }, - "audit_plan_instance_name": { - "type": "string", - "example": "test_mysql" + "audit_plan_name": { + "type": "string" }, - "audit_plan_params": { + "sql_audit_record_ids": { "type": "array", "items": { - "$ref": "#/definitions/v1.AuditPlanParamReqV1" + "type": "string" } }, - "rule_template_name": { + "type": { "type": "string", - "example": "default_MySQL" + "enum": [ + "audit_plan", + "sql_audit_record" + ] } } }, - "v1.UpdateAuditTaskSQLsReqV1": { + "v1.SqlAnalysis": { "type": "object", "properties": { - "description": { - "type": "string" + "performance_statistics": { + "type": "object", + "$ref": "#/definitions/v1.PerformanceStatistics" + }, + "sql_explain": { + "type": "object", + "$ref": "#/definitions/v1.SQLExplain" + }, + "table_metas": { + "type": "object", + "$ref": "#/definitions/v1.TableMetas" } } }, - "v1.UpdateAuditWhitelistReqV1": { + "v1.SqlAnalysisResDataV1": { "type": "object", "properties": { - "desc": { - "type": "string", - "example": "used for rapid release" - }, - "match_type": { - "type": "string", - "enum": [ - "exact_match", - "fp_match" - ], - "example": "exact_match" + "sql_explain": { + "type": "object", + "$ref": "#/definitions/v1.SQLExplain" }, - "value": { - "type": "string", - "example": "create table" + "table_metas": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMeta" + } } } }, - "v1.UpdateCompanyNoticeReq": { + "v1.SqlAverageExecutionTime": { "type": "object", "properties": { - "notice_str": { + "average_execution_seconds": { + "type": "integer" + }, + "instance_name": { "type": "string" + }, + "max_execution_seconds": { + "type": "integer" + }, + "min_execution_seconds": { + "type": "integer" } } }, - "v1.UpdateCurrentUserPasswordReqV1": { + "v1.SqlExecutionFailPercent": { "type": "object", "properties": { - "new_password": { + "instance_name": { "type": "string" }, - "password": { - "type": "string" + "percent": { + "type": "number" } } }, - "v1.UpdateCurrentUserReqV1": { + "v1.SqlManage": { "type": "object", "properties": { - "email": { + "appear_num": { + "type": "integer" + }, + "assignees": { + "type": "array", + "items": { + "type": "string" + } + }, + "audit_result": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.AuditResult" + } + }, + "endpoint": { "type": "string" }, - "phone": { + "first_appear_time": { "type": "string" }, - "wechat_id": { - "type": "string", - "example": "UserID" - } - } - }, - "v1.UpdateCustomRuleReqV1": { - "type": "object", - "properties": { - "annotation": { - "type": "string", - "example": "this is test rule" + "id": { + "type": "integer" }, - "desc": { - "type": "string", - "example": "this is test rule" + "instance_name": { + "type": "string" }, - "level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ], - "example": "notice" + "last_appear_time": { + "type": "string" }, - "rule_script": { + "remark": { "type": "string" }, - "type": { - "type": "string", - "example": "DDL规则" - } - } - }, - "v1.UpdateDingTalkConfigurationReqV1": { - "type": "object", - "required": [ - "app_key", - "app_secret", - "is_enable_ding_talk_notify" - ], - "properties": { - "app_key": { + "schema_name": { "type": "string" }, - "app_secret": { + "source": { + "type": "object", + "$ref": "#/definitions/v1.Source" + }, + "sql": { "type": "string" }, - "is_enable_ding_talk_notify": { - "type": "boolean" + "sql_fingerprint": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "unhandled", + "solved", + "ignored", + "manual_audited" + ] } } }, - "v1.UpdateFeishuConfigurationReqV1": { + "v1.StatisticAuditPlanResV1": { "type": "object", - "required": [ - "app_id", - "app_secret", - "is_feishu_notification_enabled" - ], "properties": { - "app_id": { - "type": "string" + "code": { + "type": "integer", + "example": 0 }, - "app_secret": { - "type": "string" + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.DBTypeAuditPlan" + } }, - "is_feishu_notification_enabled": { - "type": "boolean" + "message": { + "type": "string", + "example": "ok" } } }, - "v1.UpdateInstanceReqV1": { + "v1.StatisticRiskWorkflowResV1": { "type": "object", "properties": { - "additional_params": { + "code": { + "type": "integer", + "example": 0 + }, + "data": { "type": "array", "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamReqV1" + "$ref": "#/definitions/v1.RiskWorkflow" } }, - "db_host": { - "type": "string", - "example": "10.10.10.10" - }, - "db_password": { - "type": "string", - "example": "123456" - }, - "db_port": { - "type": "string", - "example": "3306" - }, - "db_type": { + "message": { "type": "string", - "example": "mysql" + "example": "ok" + } + } + }, + "v1.StatisticsAuditedSQLResV1": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 0 }, - "db_user": { - "type": "string", - "example": "root" + "data": { + "type": "object", + "$ref": "#/definitions/v1.AuditedSQLCount" }, - "desc": { + "message": { "type": "string", - "example": "this is a test instance" + "example": "ok" }, - "maintenance_times": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MaintenanceTimeReqV1" - } + "risk_rate": { + "type": "integer" + } + } + }, + "v1.SystemVariablesResV1": { + "type": "object", + "properties": { + "operation_record_expired_hours": { + "type": "integer" }, - "rule_template_name": { + "url": { "type": "string" }, - "sql_query_config": { - "type": "object", - "$ref": "#/definitions/v1.SQLQueryConfigReqV1" + "workflow_expired_hours": { + "type": "integer" + } + } + }, + "v1.Table": { + "type": "object", + "properties": { + "name": { + "type": "string" } } }, - "v1.UpdateMemberGroupReqV1": { + "v1.TableColumns": { "type": "object", "properties": { - "roles": { + "head": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMetaItemHeadResV1" + } + }, + "rows": { "type": "array", "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" + "type": "object", + "additionalProperties": { + "type": "string" + } } } } }, - "v1.UpdateMemberReqV1": { + "v1.TableIndexes": { "type": "object", "properties": { - "is_manager": { - "type": "boolean" + "head": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.TableMetaItemHeadResV1" + } }, - "roles": { + "rows": { "type": "array", "items": { - "$ref": "#/definitions/v1.BindRoleReqV1" + "type": "object", + "additionalProperties": { + "type": "string" + } } } } }, - "v1.UpdateOtherUserPasswordReqV1": { + "v1.TableMeta": { "type": "object", "properties": { - "password": { + "columns": { + "type": "object", + "$ref": "#/definitions/v1.TableColumns" + }, + "create_table_sql": { + "type": "string" + }, + "indexes": { + "type": "object", + "$ref": "#/definitions/v1.TableIndexes" + }, + "message": { + "type": "string" + }, + "name": { + "type": "string" + }, + "schema": { "type": "string" } } }, - "v1.UpdateProjectReqV1": { + "v1.TableMetaItemHeadResV1": { "type": "object", "properties": { "desc": { "type": "string" + }, + "field_name": { + "type": "string" } } }, - "v1.UpdateProjectRuleTemplateReqV1": { + "v1.TableMetas": { "type": "object", "properties": { - "desc": { + "err_message": { "type": "string" }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - }, - "example": [ - "mysql-xxx" - ] - }, - "rule_list": { + "table_meta_items": { "type": "array", "items": { - "$ref": "#/definitions/v1.RuleReqV1" + "$ref": "#/definitions/v1.TableMeta" } } } }, - "v1.UpdateRoleReqV1": { + "v1.TestAuditPlanNotifyConfigResDataV1": { "type": "object", "properties": { - "is_disabled": { + "is_notify_send_normal": { "type": "boolean" }, - "operation_code_list": { - "type": "array", - "items": { - "type": "integer" - } - }, - "role_desc": { + "send_error_message": { "type": "string" } } }, - "v1.UpdateRuleKnowledgeReq": { + "v1.TestAuditPlanNotifyConfigResV1": { "type": "object", "properties": { - "knowledge_content": { - "type": "string" + "code": { + "type": "integer", + "example": 0 + }, + "data": { + "type": "object", + "$ref": "#/definitions/v1.TestAuditPlanNotifyConfigResDataV1" + }, + "message": { + "type": "string", + "example": "ok" } } }, - "v1.UpdateRuleTemplateReqV1": { + "v1.TestDingTalkConfigResDataV1": { "type": "object", "properties": { - "desc": { - "type": "string" + "is_ding_talk_send_normal": { + "type": "boolean" }, - "rule_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.RuleReqV1" - } + "send_error_message": { + "type": "string" } } }, - "v1.UpdateSMTPConfigurationReqV1": { + "v1.TestDingTalkConfigResV1": { "type": "object", "properties": { - "enable_smtp_notify": { - "type": "boolean" - }, - "is_skip_verify": { - "type": "boolean" - }, - "smtp_host": { - "type": "string", - "example": "smtp.email.qq.com" - }, - "smtp_password": { - "type": "string", - "example": "123" + "code": { + "type": "integer", + "example": 0 }, - "smtp_port": { - "type": "string", - "example": "465" + "data": { + "type": "object", + "$ref": "#/definitions/v1.TestDingTalkConfigResDataV1" }, - "smtp_username": { + "message": { "type": "string", - "example": "test@qq.com" + "example": "ok" } } }, - "v1.UpdateSQLAuditRecordReqV1": { + "v1.TestFeishuConfigResDataV1": { "type": "object", "properties": { - "tags": { - "type": "array", - "items": { - "type": "string" - } + "error_message": { + "type": "string" + }, + "is_message_sent_normally": { + "type": "boolean" } } }, - "v1.UpdateSyncInstanceTaskReqV1": { + "v1.TestFeishuConfigResV1": { "type": "object", "properties": { - "global_rule_template": { - "type": "string", - "example": "default_mysql" - }, - "sync_instance_interval": { - "type": "string", - "example": "0 0 * * *" + "code": { + "type": "integer", + "example": 0 }, - "url": { - "type": "string", - "example": "http://10.186.62.56:10000" + "data": { + "type": "object", + "$ref": "#/definitions/v1.TestFeishuConfigResDataV1" }, - "version": { + "message": { "type": "string", - "example": "5.23.01.0" + "example": "ok" } } }, - "v1.UpdateSystemVariablesReqV1": { + "v1.TestFeishuConfigurationReqV1": { "type": "object", "properties": { - "operation_record_expired_hours": { - "type": "integer", - "example": 2160 + "account": { + "type": "string" }, - "url": { + "account_type": { "type": "string", - "example": "http://10.186.61.32:8080" - }, - "workflow_expired_hours": { - "type": "integer", - "example": 720 + "enum": [ + "email", + "phone" + ] } } }, - "v1.UpdateUserReqV1": { + "v1.TimeResV1": { "type": "object", "properties": { - "email": { - "type": "string" - }, - "is_disabled": { - "type": "boolean" - }, - "management_permission_code_list": { - "type": "array", - "items": { - "type": "integer" - } + "hour": { + "type": "integer" }, - "phone": { - "type": "string" + "minute": { + "type": "integer" + } + } + }, + "v1.TriggerAuditPlanResV1": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 0 }, - "user_group_name_list": { - "type": "array", - "items": { - "type": "string" - } + "data": { + "type": "object", + "$ref": "#/definitions/v1.AuditPlanReportResV1" }, - "wechat_id": { + "message": { "type": "string", - "example": "UserID" + "example": "ok" } } }, - "v1.UpdateWeChatConfigurationReqV1": { + "v1.UpdateAuditPlanNotifyConfigReqV1": { "type": "object", "properties": { - "agent_id": { - "type": "integer" + "enable_email_notify": { + "type": "boolean" }, - "corp_id": { - "type": "string" + "enable_web_hook_notify": { + "type": "boolean" }, - "corp_secret": { - "type": "string" + "notify_interval": { + "type": "integer", + "default": 10 }, - "enable_wechat_notify": { - "type": "boolean" + "notify_level": { + "type": "string", + "default": "warn", + "enum": [ + "normal", + "notice", + "warn", + "error" + ] }, - "proxy_ip": { + "web_hook_template": { "type": "string" }, - "safe_enabled": { - "type": "boolean" + "web_hook_url": { + "type": "string" } } }, - "v1.UpdateWorkflowReqV1": { + "v1.UpdateAuditPlanReqV1": { "type": "object", "properties": { - "task_ids": { + "audit_plan_cron": { + "type": "string", + "example": "0 */2 * * *" + }, + "audit_plan_instance_database": { + "type": "string", + "example": "app1" + }, + "audit_plan_instance_name": { + "type": "string", + "example": "test_mysql" + }, + "audit_plan_params": { "type": "array", "items": { - "type": "integer" + "$ref": "#/definitions/v1.AuditPlanParamReqV1" } + }, + "rule_template_name": { + "type": "string", + "example": "default_MySQL" } } }, - "v1.UpdateWorkflowScheduleReqV1": { + "v1.UpdateAuditTaskSQLsReqV1": { "type": "object", "properties": { - "schedule_time": { + "description": { "type": "string" } } }, - "v1.UpdateWorkflowTemplateReqV1": { + "v1.UpdateAuditWhitelistReqV1": { "type": "object", "properties": { - "allow_submit_when_less_audit_level": { - "type": "string", - "enum": [ - "normal", - "notice", - "warn", - "error" - ] - }, "desc": { - "type": "string" + "type": "string", + "example": "used for rapid release" }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - } + "match_type": { + "type": "string", + "enum": [ + "exact_match", + "fp_match" + ], + "example": "exact_match" }, - "workflow_step_template_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.WorkFlowStepTemplateReqV1" - } + "value": { + "type": "string", + "example": "create table" } } }, - "v1.UploadLogoResDataV1": { + "v1.UpdateCompanyNoticeReq": { "type": "object", "properties": { - "logo_url": { + "notice_str": { "type": "string" } } }, - "v1.UploadLogoResV1": { + "v1.UpdateCustomRuleReqV1": { "type": "object", "properties": { - "code": { - "type": "integer", - "example": 0 + "annotation": { + "type": "string", + "example": "this is test rule" }, - "data": { - "type": "object", - "$ref": "#/definitions/v1.UploadLogoResDataV1" + "desc": { + "type": "string", + "example": "this is test rule" }, - "message": { + "level": { "type": "string", - "example": "ok" + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "example": "notice" + }, + "rule_script": { + "type": "string" + }, + "type": { + "type": "string", + "example": "DDL规则" } } }, - "v1.UserBindProjectResV1": { + "v1.UpdateDingTalkConfigurationReqV1": { "type": "object", + "required": [ + "app_key", + "app_secret", + "is_enable_ding_talk_notify" + ], "properties": { - "is_manager": { - "type": "boolean" + "app_key": { + "type": "string" }, - "project_name": { + "app_secret": { "type": "string" + }, + "is_enable_ding_talk_notify": { + "type": "boolean" } } }, - "v1.UserDetailResV1": { + "v1.UpdateFeishuConfigurationReqV1": { "type": "object", + "required": [ + "app_id", + "app_secret", + "is_feishu_notification_enabled" + ], "properties": { - "bind_projects": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.UserBindProjectResV1" - } - }, - "email": { + "app_id": { "type": "string" }, - "is_admin": { - "type": "boolean" - }, - "is_disabled": { - "type": "boolean" - }, - "login_type": { + "app_secret": { "type": "string" }, - "management_permission_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ManagementPermissionResV1" - } - }, - "phone": { + "is_feishu_notification_enabled": { + "type": "boolean" + } + } + }, + "v1.UpdateProjectRuleTemplateReqV1": { + "type": "object", + "properties": { + "desc": { "type": "string" }, - "user_group_name_list": { + "rule_list": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.RuleReqV1" } - }, - "user_name": { - "type": "string" - }, - "wechat_id": { - "type": "string" } } }, - "v1.UserGroupListItemResV1": { + "v1.UpdateRuleKnowledgeReq": { "type": "object", "properties": { - "is_disabled": { - "type": "boolean" - }, - "user_group_desc": { - "type": "string" - }, - "user_group_name": { + "knowledge_content": { "type": "string" - }, - "user_name_list": { - "type": "array", - "items": { - "type": "string" - } } } }, - "v1.UserGroupTipListItem": { + "v1.UpdateRuleTemplateReqV1": { "type": "object", "properties": { - "user_group_name": { + "desc": { "type": "string" }, - "user_names": { + "rule_list": { "type": "array", "items": { - "type": "string" + "$ref": "#/definitions/v1.RuleReqV1" } } } }, - "v1.UserLoginReqV1": { + "v1.UpdateSQLAuditRecordReqV1": { "type": "object", "properties": { - "password": { - "type": "string", - "example": "123456" - }, - "username": { - "type": "string", - "example": "test" + "tags": { + "type": "array", + "items": { + "type": "string" + } } } }, - "v1.UserLoginResV1": { + "v1.UpdateSystemVariablesReqV1": { "type": "object", "properties": { - "token": { + "operation_record_expired_hours": { + "type": "integer", + "example": 2160 + }, + "url": { "type": "string", - "example": "this is a jwt token string" + "example": "http://10.186.61.32:8080" + }, + "workflow_expired_hours": { + "type": "integer", + "example": 720 } } }, - "v1.UserResV1": { + "v1.UpdateWorkflowReqV1": { "type": "object", "properties": { - "email": { - "type": "string" - }, - "is_disabled": { - "type": "boolean" - }, - "login_type": { - "type": "string" - }, - "management_permission_list": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.ManagementPermissionResV1" - } - }, - "phone": { - "type": "string" - }, - "user_group_name_list": { + "task_ids": { "type": "array", "items": { - "type": "string" + "type": "integer" } - }, - "user_name": { - "type": "string" - }, - "wechat_id": { - "type": "string" } } }, - "v1.UserTipResV1": { + "v1.UpdateWorkflowScheduleReqV1": { "type": "object", "properties": { - "user_name": { + "schedule_time": { "type": "string" } } }, - "v1.WeChatConfigurationResV1": { + "v1.UpdateWorkflowTemplateReqV1": { "type": "object", "properties": { - "agent_id": { - "type": "integer" - }, - "corp_id": { - "type": "string" - }, - "enable_wechat_notify": { - "type": "boolean" + "allow_submit_when_less_audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error" + ] }, - "proxy_ip": { + "desc": { "type": "string" }, - "safe_enabled": { - "type": "boolean" + "workflow_step_template_list": { + "type": "array", + "items": { + "$ref": "#/definitions/v1.WorkFlowStepTemplateReqV1" + } } } }, - "v1.WebHookConfigV1": { + "v1.UserTipResV1": { "type": "object", "properties": { - "enable": { - "type": "boolean" - }, - "max_retry_times": { - "type": "integer" - }, - "retry_interval_seconds": { - "type": "integer" - }, - "token": { + "user_id": { "type": "string" }, - "url": { + "user_name": { "type": "string" } } @@ -16525,7 +11454,7 @@ "approved_by_authorized": { "type": "boolean" }, - "assignee_user_name_list": { + "assignee_user_id_list": { "type": "array", "items": { "type": "string" @@ -16552,7 +11481,7 @@ "approved_by_authorized": { "type": "boolean" }, - "assignee_user_name_list": { + "assignee_user_id_list": { "type": "array", "items": { "type": "string" @@ -16921,11 +11850,8 @@ "desc": { "type": "string" }, - "instance_name_list": { - "type": "array", - "items": { - "type": "string" - } + "update_time": { + "type": "string" }, "workflow_step_template_list": { "type": "array", @@ -17150,6 +12076,9 @@ }, "rollback_sql": { "type": "string" + }, + "sql_source_file": { + "type": "string" } } }, @@ -17175,58 +12104,6 @@ } } }, - "v2.CreateInstanceReqV2": { - "type": "object", - "properties": { - "additional_params": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.InstanceAdditionalParamReqV1" - } - }, - "db_host": { - "type": "string", - "example": "10.10.10.10" - }, - "db_password": { - "type": "string", - "example": "123456" - }, - "db_port": { - "type": "string", - "example": "3306" - }, - "db_type": { - "type": "string", - "example": "mysql" - }, - "db_user": { - "type": "string", - "example": "root" - }, - "desc": { - "type": "string", - "example": "this is a test instance" - }, - "instance_name": { - "type": "string", - "example": "test" - }, - "maintenance_times": { - "type": "array", - "items": { - "$ref": "#/definitions/v1.MaintenanceTimeReqV1" - } - }, - "rule_template_name": { - "type": "string" - }, - "sql_query_config": { - "type": "object", - "$ref": "#/definitions/v1.SQLQueryConfigReqV1" - } - } - }, "v2.CreateWorkflowReqV2": { "type": "object", "properties": { @@ -17493,28 +12370,6 @@ } } }, - "v2.GetInstancesResV2": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 0 - }, - "data": { - "type": "array", - "items": { - "$ref": "#/definitions/v2.InstanceResV2" - } - }, - "message": { - "type": "string", - "example": "ok" - }, - "total_nums": { - "type": "integer" - } - } - }, "v2.GetSqlManageListResp": { "type": "object", "properties": { diff --git a/sqle/docs/swagger.yaml b/sqle/docs/swagger.yaml index 4c9f4f962b..8cee801762 100644 --- a/sqle/docs/swagger.yaml +++ b/sqle/docs/swagger.yaml @@ -401,41 +401,6 @@ definitions: - manual_audited type: string type: object - v1.BindOauth2UserReqV1: - properties: - oauth2_token: - type: string - pwd: - type: string - user_name: - type: string - type: object - v1.BindOauth2UserResDataV1: - properties: - token: - type: string - type: object - v1.BindOauth2UserResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.BindOauth2UserResDataV1' - type: object - message: - example: ok - type: string - type: object - v1.BindRoleReqV1: - properties: - instance_name: - type: string - role_names: - items: - type: string - type: array - type: object v1.CheckLicenseResV1: properties: code: @@ -455,10 +420,6 @@ definitions: properties: desc: type: string - instance_name_list: - items: - type: string - type: array new_rule_template_name: type: string type: object @@ -561,80 +522,12 @@ definitions: example: DDL规则 type: string type: object - v1.CreateInstanceReqV1: - properties: - additional_params: - items: - $ref: '#/definitions/v1.InstanceAdditionalParamReqV1' - type: array - db_host: - example: 10.10.10.10 - type: string - db_password: - example: "123456" - type: string - db_port: - example: "3306" - type: string - db_type: - example: mysql - type: string - db_user: - example: root - type: string - desc: - example: this is a test instance - type: string - instance_name: - example: test - type: string - maintenance_times: - items: - $ref: '#/definitions/v1.MaintenanceTimeReqV1' - type: array - rule_template_name: - type: string - sql_query_config: - $ref: '#/definitions/v1.SQLQueryConfigReqV1' - type: object - type: object - v1.CreateMemberGroupReqV1: - properties: - roles: - items: - $ref: '#/definitions/v1.BindRoleReqV1' - type: array - user_group_name: - type: string - type: object - v1.CreateMemberReqV1: - properties: - is_manager: - type: boolean - roles: - items: - $ref: '#/definitions/v1.BindRoleReqV1' - type: array - user_name: - type: string - type: object - v1.CreateProjectReqV1: - properties: - desc: - type: string - name: - type: string - type: object v1.CreateProjectRuleTemplateReqV1: properties: db_type: type: string desc: type: string - instance_name_list: - items: - type: string - type: array rule_list: items: $ref: '#/definitions/v1.RuleReqV1' @@ -642,17 +535,6 @@ definitions: rule_template_name: type: string type: object - v1.CreateRoleReqV1: - properties: - operation_code_list: - items: - type: integer - type: array - role_desc: - type: string - role_name: - type: string - type: object v1.CreateRuleTemplateReqV1: properties: db_type: @@ -678,73 +560,6 @@ definitions: example: ok type: string type: object - v1.CreateSyncInstanceTaskReqV1: - properties: - db_type: - example: mysql - type: string - global_rule_template: - example: default_mysql - type: string - source: - example: actiontech-dmp - type: string - sync_instance_interval: - example: 0 0 * * * - type: string - url: - example: http://10.186.62.56:10000 - type: string - version: - example: 5.23.01.0 - type: string - required: - - db_type - - global_rule_template - - source - - sync_instance_interval - - url - - version - type: object - v1.CreateUserGroupReqV1: - properties: - user_group_desc: - example: this is a group - type: string - user_group_name: - example: test - type: string - user_name_list: - items: - type: string - type: array - type: object - v1.CreateUserReqV1: - properties: - email: - example: test@email.com - type: string - management_permission_code_list: - items: - type: integer - type: array - phone: - example: "18962136666" - type: string - user_group_name_list: - items: - type: string - type: array - user_name: - example: test - type: string - user_password: - example: "123456" - type: string - wechat_id: - example: UserID - type: string - type: object v1.CreateWorkflowReqV1: properties: desc: @@ -805,14 +620,6 @@ definitions: type: string type: array type: object - v1.DashboardProjectTipV1: - properties: - project_name: - type: string - unfinished_workflow_count: - description: 只统计与当前用户相关的未完成工单 - type: integer - type: object v1.DashboardResV1: properties: workflow_statistics: @@ -1181,19 +988,6 @@ definitions: example: ok type: string type: object - v1.GetDashboardProjectTipsResV1: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v1.DashboardProjectTipV1' - type: array - message: - example: ok - type: string - type: object v1.GetDashboardResV1: properties: code: @@ -1242,53 +1036,6 @@ definitions: example: ok type: string type: object - v1.GetFeishuConfigurationResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.FeishuConfigurationV1' - type: object - message: - example: ok - type: string - type: object - v1.GetInstanceAdditionalMetasResV1: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v1.InstanceAdditionalMetaV1' - type: array - message: - example: ok - type: string - type: object - v1.GetInstanceConnectableReqV1: - properties: - additional_params: - items: - $ref: '#/definitions/v1.InstanceAdditionalParamReqV1' - type: array - db_type: - example: mysql - type: string - host: - example: 10.10.10.10 - type: string - password: - example: "123456" - type: string - port: - example: "3306" - type: string - user: - example: root - type: string - type: object v1.GetInstanceConnectableResV1: properties: code: @@ -1314,18 +1061,6 @@ definitions: example: ok type: string type: object - v1.GetInstanceResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.InstanceResV1' - type: object - message: - example: ok - type: string - type: object v1.GetInstanceSchemaResV1: properties: code: @@ -1351,21 +1086,6 @@ definitions: example: ok type: string type: object - v1.GetInstancesResV1: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v1.InstanceResV1' - type: array - message: - example: ok - type: string - total_nums: - type: integer - type: object v1.GetInstancesTypePercentResV1: properties: code: @@ -1378,18 +1098,6 @@ definitions: example: ok type: string type: object - v1.GetLDAPConfigurationResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.LDAPConfigurationResV1' - type: object - message: - example: ok - type: string - type: object v1.GetLicenseResV1: properties: code: @@ -1417,240 +1125,197 @@ definitions: example: ok type: string type: object - v1.GetManagementPermissionsResV1: + v1.GetOperationActionListResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.ManagementPermissionResV1' + $ref: '#/definitions/v1.OperationActionList' type: array message: example: ok type: string type: object - v1.GetMemberGroupRespDataV1: - properties: - roles: - items: - $ref: '#/definitions/v1.BindRoleReqV1' - type: array - user_group_name: - type: string - users: - items: - $ref: '#/definitions/v1.MemberGroupUserItem' - type: array - type: object - v1.GetMemberGroupRespV1: + v1.GetOperationRecordListResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.GetMemberGroupRespDataV1' - type: object + items: + $ref: '#/definitions/v1.OperationRecordList' + type: array message: example: ok type: string + total_nums: + type: integer type: object - v1.GetMemberGroupsRespV1: + v1.GetOperationTypeNamesListResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.GetMemberGroupRespDataV1' + $ref: '#/definitions/v1.OperationTypeNameList' type: array message: example: ok type: string - total_nums: - type: integer type: object - v1.GetMemberRespDataV1: + v1.GetOperationsResV1: properties: - is_manager: - type: boolean - roles: + code: + example: 0 + type: integer + data: items: - $ref: '#/definitions/v1.BindRoleReqV1' + $ref: '#/definitions/v1.OperationResV1' type: array - user_name: + message: + example: ok type: string type: object - v1.GetMemberRespV1: + v1.GetProjectRuleTemplateResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.GetMemberRespDataV1' + $ref: '#/definitions/v1.RuleProjectTemplateDetailResV1' type: object message: example: ok type: string type: object - v1.GetMemberTipsResV1: + v1.GetProjectRuleTemplatesResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.MemberTipResV1' + $ref: '#/definitions/v1.ProjectRuleTemplateResV1' type: array message: example: ok type: string + total_nums: + type: integer type: object - v1.GetMembersRespV1: + v1.GetProjectScoreResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.GetMemberRespDataV1' - type: array + $ref: '#/definitions/v1.ProjectScore' + type: object message: example: ok type: string - total_nums: - type: integer type: object - v1.GetOauth2ConfigurationResDataV1: + v1.GetProjectStatisticsResDataV1: properties: - access_token_tag: - type: string - client_host: - type: string - client_id: - type: string - enable_oauth2: - type: boolean - login_tip: - type: string - scopes: - items: - type: string - type: array - server_auth_url: - type: string - server_token_url: - type: string - server_user_id_url: - type: string - user_id_tag: - type: string - type: object - v1.GetOauth2ConfigurationResV1: - properties: - code: - example: 0 + audit_plan_total: + type: integer + instance_total: + type: integer + member_total: + type: integer + rule_template_total: + type: integer + whitelist_total: + type: integer + workflow_total: type: integer - data: - $ref: '#/definitions/v1.GetOauth2ConfigurationResDataV1' - type: object - message: - example: ok - type: string - type: object - v1.GetOauth2TipsResDataV1: - properties: - enable_oauth2: - type: boolean - login_tip: - type: string type: object - v1.GetOauth2TipsResV1: + v1.GetProjectStatisticsResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.GetOauth2TipsResDataV1' + $ref: '#/definitions/v1.GetProjectStatisticsResDataV1' type: object message: example: ok type: string type: object - v1.GetOperationActionListResV1: + v1.GetRiskAuditPlanResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.OperationActionList' + $ref: '#/definitions/v1.RiskAuditPlan' type: array message: example: ok type: string type: object - v1.GetOperationRecordListResV1: + v1.GetRoleUserCountResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.OperationRecordList' + $ref: '#/definitions/v1.RoleUserCount' type: array message: example: ok type: string - total_nums: - type: integer type: object - v1.GetOperationTypeNamesListResV1: + v1.GetRuleKnowledgeResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.OperationTypeNameList' - type: array + $ref: '#/definitions/v1.RuleKnowledgeResV1' + type: object message: example: ok type: string type: object - v1.GetOperationsResV1: + v1.GetRuleTemplateResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.OperationResV1' - type: array + $ref: '#/definitions/v1.RuleTemplateDetailResV1' + type: object message: example: ok type: string type: object - v1.GetProjectDetailResV1: + v1.GetRuleTemplateTipsResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.ProjectDetailItem' - type: object + items: + $ref: '#/definitions/v1.RuleTemplateTipResV1' + type: array message: example: ok type: string type: object - v1.GetProjectResV1: + v1.GetRuleTemplatesResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.ProjectListItem' + $ref: '#/definitions/v1.RuleTemplateResV1' type: array message: example: ok @@ -1658,2644 +1323,2296 @@ definitions: total_nums: type: integer type: object - v1.GetProjectRuleTemplateResV1: + v1.GetRuleTypeByDBTypeResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.RuleProjectTemplateDetailResV1' - type: object + items: + $ref: '#/definitions/v1.RuleTypeV1' + type: array message: example: ok type: string type: object - v1.GetProjectRuleTemplatesResV1: + v1.GetRulesResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.ProjectRuleTemplateResV1' + $ref: '#/definitions/v1.RuleResV1' type: array message: example: ok type: string - total_nums: - type: integer type: object - v1.GetProjectScoreResV1: + v1.GetSQLAnalysisDataResItemV1: + properties: + sql_explain: + $ref: '#/definitions/v1.SQLExplain' + type: object + table_metas: + items: + $ref: '#/definitions/v1.TableMeta' + type: array + type: object + v1.GetSQLAuditRecordResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.ProjectScore' + $ref: '#/definitions/v1.SQLAuditRecord' type: object message: example: ok type: string type: object - v1.GetProjectStatisticsResDataV1: - properties: - audit_plan_total: - type: integer - instance_total: - type: integer - member_total: - type: integer - rule_template_total: - type: integer - whitelist_total: - type: integer - workflow_total: - type: integer - type: object - v1.GetProjectStatisticsResV1: + v1.GetSQLAuditRecordTagTipsResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.GetProjectStatisticsResDataV1' - type: object + items: + type: string + type: array message: example: ok type: string type: object - v1.GetProjectTipsResV1: + v1.GetSQLAuditRecordsResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.ProjectTipResV1' + $ref: '#/definitions/v1.SQLAuditRecord' type: array message: example: ok type: string + total_nums: + type: integer type: object - v1.GetRiskAuditPlanResV1: + v1.GetSqlAverageExecutionTimeResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.RiskAuditPlan' + $ref: '#/definitions/v1.SqlAverageExecutionTime' type: array message: example: ok type: string type: object - v1.GetRoleTipsResV1: + v1.GetSqlExecutionFailPercentResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.RoleTipResV1' + $ref: '#/definitions/v1.SqlExecutionFailPercent' type: array message: example: ok type: string type: object - v1.GetRoleUserCountResV1: + v1.GetSqlManageListResp: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.RoleUserCount' + $ref: '#/definitions/v1.SqlManage' type: array message: example: ok type: string + sql_manage_bad_num: + type: integer + sql_manage_optimized_num: + type: integer + sql_manage_total_num: + type: integer type: object - v1.GetRolesResV1: + v1.GetSqlManageRuleTipsResp: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.RoleResV1' + $ref: '#/definitions/v1.RuleTips' type: array message: example: ok type: string - total_nums: - type: integer type: object - v1.GetRuleKnowledgeResV1: + v1.GetSqlManageSqlAnalysisResp: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.RuleKnowledgeResV1' + $ref: '#/definitions/v1.SqlAnalysis' + description: V1版本不能引用V2版本的结构体,所以只能复制一份 type: object message: example: ok type: string type: object - v1.GetRuleTemplateResV1: + v1.GetSystemVariablesResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.RuleTemplateDetailResV1' + $ref: '#/definitions/v1.SystemVariablesResV1' type: object message: example: ok type: string type: object - v1.GetRuleTemplateTipsResV1: + v1.GetTableMetadataResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.RuleTemplateTipResV1' - type: array + $ref: '#/definitions/v1.InstanceTableMeta' + type: object message: example: ok type: string type: object - v1.GetRuleTemplatesResV1: + v1.GetTaskAnalysisDataResItemV1: + properties: + sql_explain: + $ref: '#/definitions/v1.SQLExplain' + type: object + table_metas: + items: + $ref: '#/definitions/v1.TableMeta' + type: array + type: object + v1.GetTaskAnalysisDataResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.RuleTemplateResV1' - type: array + $ref: '#/definitions/v1.GetTaskAnalysisDataResItemV1' + type: object message: example: ok type: string - total_nums: - type: integer type: object - v1.GetRuleTypeByDBTypeResV1: + v1.GetUserTipsResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.RuleTypeV1' + $ref: '#/definitions/v1.UserTipResV1' type: array message: example: ok type: string type: object - v1.GetRulesResV1: + v1.GetWorkflowAuditPassPercentResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.RuleResV1' - type: array + $ref: '#/definitions/v1.WorkflowAuditPassPercentV1' + type: object message: example: ok type: string type: object - v1.GetSMTPConfigurationResV1: + v1.GetWorkflowCountsResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.SMTPConfigurationResV1' + $ref: '#/definitions/v1.WorkflowCountsV1' type: object message: example: ok type: string type: object - v1.GetSQLAnalysisDataResItemV1: - properties: - sql_explain: - $ref: '#/definitions/v1.SQLExplain' - type: object - table_metas: - items: - $ref: '#/definitions/v1.TableMeta' - type: array - type: object - v1.GetSQLAuditRecordResV1: + v1.GetWorkflowCreatedCountsEachDayResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.SQLAuditRecord' + $ref: '#/definitions/v1.WorkflowCreatedCountsEachDayV1' type: object message: example: ok type: string type: object - v1.GetSQLAuditRecordTagTipsResV1: + v1.GetWorkflowDurationOfWaitingForAuditResV1: properties: code: example: 0 type: integer data: - items: - type: string - type: array + $ref: '#/definitions/v1.WorkflowStageDuration' + type: object message: example: ok type: string type: object - v1.GetSQLAuditRecordsResV1: + v1.GetWorkflowDurationOfWaitingForExecutionResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.SQLAuditRecord' - type: array + $ref: '#/definitions/v1.WorkflowStageDuration' + type: object message: example: ok type: string - total_nums: - type: integer - type: object - v1.GetSQLEInfoResDataV1: - properties: - logo_url: - type: string - title: - type: string - version: - type: string type: object - v1.GetSQLEInfoResV1: + v1.GetWorkflowPassPercentResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.GetSQLEInfoResDataV1' + $ref: '#/definitions/v1.WorkflowPassPercentV1' type: object message: example: ok type: string type: object - v1.GetSQLQueryConfigurationResDataV1: - properties: - enable_sql_query: - type: boolean - sql_query_root_uri: - type: string - type: object - v1.GetSQLQueryConfigurationResV1: + v1.GetWorkflowPercentCountedByInstanceTypeResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.GetSQLQueryConfigurationResDataV1' + $ref: '#/definitions/v1.WorkflowPercentCountedByInstanceTypeV1' type: object message: example: ok type: string type: object - v1.GetSqlAverageExecutionTimeResV1: + v1.GetWorkflowRejectedPercentGroupByCreatorResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.SqlAverageExecutionTime' + $ref: '#/definitions/v1.WorkflowRejectedPercentGroupByCreator' type: array message: example: ok type: string type: object - v1.GetSqlExecutionFailPercentResV1: + v1.GetWorkflowRejectedPercentGroupByInstanceResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.SqlExecutionFailPercent' + $ref: '#/definitions/v1.WorkflowRejectedPercentGroupByInstance' type: array message: example: ok type: string type: object - v1.GetSqlManageListResp: + v1.GetWorkflowResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.SqlManage' - type: array + $ref: '#/definitions/v1.WorkflowResV1' + type: object message: example: ok type: string - sql_manage_bad_num: - type: integer - sql_manage_optimized_num: - type: integer - sql_manage_total_num: - type: integer type: object - v1.GetSqlManageRuleTipsResp: + v1.GetWorkflowStatusCountResV1: properties: code: example: 0 type: integer data: - items: - $ref: '#/definitions/v1.RuleTips' - type: array - message: + $ref: '#/definitions/v1.WorkflowStatusCountV1' + type: object + message: example: ok type: string type: object - v1.GetSqlManageSqlAnalysisResp: + v1.GetWorkflowTasksItemV1: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.SqlAnalysis' - type: object - message: - example: ok + current_step_assignee_user_name_list: + items: + type: string + type: array + exec_end_time: + type: string + exec_start_time: + type: string + execution_user_name: + type: string + instance_maintenance_times: + items: + $ref: '#/definitions/v1.MaintenanceTimeResV1' + type: array + instance_name: + type: string + schedule_time: + type: string + status: + enum: + - wait_for_audit + - wait_for_execution + - exec_scheduled + - exec_failed + - exec_succeeded + - executing + - manually_executed type: string + task_id: + type: integer + task_pass_rate: + type: number + task_score: + type: integer type: object - v1.GetSyncInstanceTaskListResV1: + v1.GetWorkflowTasksResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.InstanceTaskResV1' + $ref: '#/definitions/v1.GetWorkflowTasksItemV1' type: array message: example: ok type: string type: object - v1.GetSyncInstanceTaskResV1: + v1.GetWorkflowTemplateResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.InstanceTaskDetailResV1' + $ref: '#/definitions/v1.WorkflowTemplateDetailResV1' type: object message: example: ok type: string type: object - v1.GetSyncTaskSourceTipsResV1: + v1.GetWorkflowsResV1: properties: code: example: 0 type: integer data: items: - $ref: '#/definitions/v1.SyncTaskTipsResV1' + $ref: '#/definitions/v1.WorkflowDetailResV1' type: array message: example: ok type: string + total_nums: + type: integer type: object - v1.GetSystemVariablesResV1: + v1.InstanceAdditionalParamResV1: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.SystemVariablesResV1' - type: object - message: - example: ok + description: + example: 参数项中文名 + type: string + name: + example: param name + type: string + type: + example: int + type: string + value: + example: "0" type: string type: object - v1.GetTableMetadataResV1: + v1.InstanceConnectableResV1: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.InstanceTableMeta' - type: object - message: - example: ok + connect_error_message: type: string + is_instance_connectable: + type: boolean type: object - v1.GetTaskAnalysisDataResItemV1: + v1.InstanceConnectionResV1: properties: - sql_explain: - $ref: '#/definitions/v1.SQLExplain' - type: object - table_metas: - items: - $ref: '#/definitions/v1.TableMeta' - type: array + connect_error_message: + type: string + instance_name: + type: string + is_instance_connectable: + type: boolean type: object - v1.GetTaskAnalysisDataResV1: + v1.InstanceForCheckConnection: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.GetTaskAnalysisDataResItemV1' - type: object - message: - example: ok + name: type: string type: object - v1.GetUserDetailResV1: + v1.InstanceForCreatingTask: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.UserDetailResV1' - type: object - message: - example: ok + instance_name: + type: string + instance_schema: type: string type: object - v1.GetUserGroupTipsResV1: + v1.InstanceSchemaResV1: properties: - code: - example: 0 - type: integer - data: + schema_name_list: items: - $ref: '#/definitions/v1.UserGroupTipListItem' + type: string type: array - message: - example: ok + type: object + v1.InstanceTableMeta: + properties: + columns: + $ref: '#/definitions/v1.TableColumns' + type: object + create_table_sql: + type: string + indexes: + $ref: '#/definitions/v1.TableIndexes' + type: object + name: + type: string + schema: type: string type: object - v1.GetUserGroupsResV1: + v1.InstanceTipResV1: properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v1.UserGroupListItemResV1' - type: array - message: - example: ok + host: type: string - total_nums: + instance_id: + type: string + instance_name: + type: string + instance_type: + type: string + port: + type: string + workflow_template_id: type: integer type: object - v1.GetUserLoginResV1: + v1.InstanceTypePercent: properties: - code: - example: 0 + count: type: integer - data: - $ref: '#/definitions/v1.UserLoginResV1' - type: object - message: - example: ok + percent: + type: number + type: type: string type: object - v1.GetUserTipsResV1: + v1.InstancesTypePercentV1: properties: - code: - example: 0 + instance_total_num: type: integer - data: + instance_type_percents: items: - $ref: '#/definitions/v1.UserTipResV1' + $ref: '#/definitions/v1.InstanceTypePercent' type: array - message: - example: ok + type: object + v1.LicenseItem: + properties: + description: + type: string + limit: + type: string + name: type: string type: object - v1.GetUsersResV1: + v1.LicenseUsageItem: properties: - code: - example: 0 + is_limited: + type: boolean + limit: type: integer - data: - items: - $ref: '#/definitions/v1.UserResV1' - type: array - message: - example: ok + resource_type: type: string - total_nums: + resource_type_desc: + type: string + used: type: integer type: object - v1.GetWeChatConfigurationResV1: + v1.LicenseUsageV1: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.WeChatConfigurationResV1' + instances_usage: + items: + $ref: '#/definitions/v1.LicenseUsageItem' + type: array + users_usage: + $ref: '#/definitions/v1.LicenseUsageItem' type: object - message: - example: ok - type: string type: object - v1.GetWorkflowAuditPassPercentResV1: + v1.ListTableBySchemaResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.WorkflowAuditPassPercentV1' - type: object + items: + $ref: '#/definitions/v1.Table' + type: array message: example: ok type: string type: object - v1.GetWorkflowCountsResV1: + v1.MaintenanceTimeResV1: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.WorkflowCountsV1' + maintenance_start_time: + $ref: '#/definitions/v1.TimeResV1' + type: object + maintenance_stop_time: + $ref: '#/definitions/v1.TimeResV1' type: object - message: - example: ok - type: string type: object - v1.GetWorkflowCreatedCountsEachDayResV1: + v1.OperationActionList: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.WorkflowCreatedCountsEachDayV1' - type: object - message: - example: ok + desc: type: string - type: object - v1.GetWorkflowDurationOfWaitingForAuditResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.WorkflowStageDuration' - type: object - message: - example: ok + operation_action: + type: string + operation_type: type: string type: object - v1.GetWorkflowDurationOfWaitingForExecutionResV1: + v1.OperationRecordList: properties: - code: - example: 0 + id: type: integer - data: - $ref: '#/definitions/v1.WorkflowStageDuration' + operation_action: + type: string + operation_content: + type: string + operation_time: + type: string + operation_type_name: + type: string + operation_user: + $ref: '#/definitions/v1.OperationUser' type: object - message: - example: ok + project_name: + type: string + status: + enum: + - succeeded + - failed type: string type: object - v1.GetWorkflowPassPercentResV1: + v1.OperationResV1: properties: - code: - example: 0 + op_code: type: integer - data: - $ref: '#/definitions/v1.WorkflowPassPercentV1' - type: object - message: - example: ok + op_desc: type: string type: object - v1.GetWorkflowPercentCountedByInstanceTypeResV1: + v1.OperationTypeNameList: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.WorkflowPercentCountedByInstanceTypeV1' - type: object - message: - example: ok + desc: + type: string + operation_type_name: type: string type: object - v1.GetWorkflowRejectedPercentGroupByCreatorResV1: + v1.OperationUser: properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v1.WorkflowRejectedPercentGroupByCreator' - type: array - message: - example: ok + ip: + type: string + user_name: type: string type: object - v1.GetWorkflowRejectedPercentGroupByInstanceResV1: + v1.ParseProjectRuleTemplateFileResDataV1: properties: - code: - example: 0 - type: integer - data: + db_type: + type: string + desc: + type: string + name: + type: string + rule_list: items: - $ref: '#/definitions/v1.WorkflowRejectedPercentGroupByInstance' + $ref: '#/definitions/v1.RuleResV1' type: array - message: - example: ok - type: string type: object - v1.GetWorkflowResV1: + v1.ParseProjectRuleTemplateFileResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.WorkflowResV1' + $ref: '#/definitions/v1.ParseProjectRuleTemplateFileResDataV1' type: object message: example: ok type: string type: object - v1.GetWorkflowStatusCountResV1: + v1.PartialSyncAuditPlanSQLsReqV1: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.WorkflowStatusCountV1' + audit_plan_sql_list: + items: + $ref: '#/definitions/v1.AuditPlanSQLReqV1' + type: array + type: object + v1.PerformanceStatistics: + properties: + affect_rows: + $ref: '#/definitions/v1.AffectRows' type: object - message: - example: ok - type: string type: object - v1.GetWorkflowTasksItemV1: + v1.ProjectRuleTemplateResV1: properties: - current_step_assignee_user_name_list: - items: - type: string - type: array - exec_end_time: - type: string - exec_start_time: - type: string - execution_user_name: - type: string - instance_maintenance_times: - items: - $ref: '#/definitions/v1.MaintenanceTimeResV1' - type: array - instance_name: + db_type: type: string - schedule_time: + desc: type: string - status: - enum: - - wait_for_audit - - wait_for_execution - - exec_scheduled - - exec_failed - - exec_succeeded - - executing - - manually_executed + rule_template_name: type: string - task_id: - type: integer - task_pass_rate: - type: number - task_score: - type: integer type: object - v1.GetWorkflowTasksResV1: + v1.ProjectScore: properties: - code: - example: 0 + score: type: integer - data: - items: - $ref: '#/definitions/v1.GetWorkflowTasksItemV1' - type: array - message: - example: ok + type: object + v1.RejectWorkflowReqV1: + properties: + reason: type: string type: object - v1.GetWorkflowTemplateResV1: + v1.RiskAuditPlan: properties: - code: - example: 0 + audit_plan_name: + type: string + audit_plan_report_id: type: integer - data: - $ref: '#/definitions/v1.WorkflowTemplateDetailResV1' - type: object - message: - example: ok + audit_plan_report_timestamp: + type: string + risk_sql_count: + type: integer + trigger_audit_plan_time: type: string type: object - v1.GetWorkflowWebHookConfigResV1: + v1.RiskWorkflow: properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.WebHookConfigV1' - type: object - message: - example: ok + create_user_name: + type: string + update_time: + type: string + workflow_id: + type: string + workflow_name: + type: string + workflow_status: type: string type: object - v1.GetWorkflowsResV1: + v1.RoleUserCount: properties: - code: - example: 0 + count: type: integer - data: - items: - $ref: '#/definitions/v1.WorkflowDetailResV1' - type: array - message: - example: ok + role: type: string - total_nums: - type: integer type: object - v1.GlobalRuleTemplateInstance: + v1.RuleInfo: properties: - instance_name: + annotation: + example: this is test rule type: string - project_name: + desc: + example: this is test rule type: string type: object - v1.InstanceAdditionalMetaV1: + v1.RuleKnowledgeResV1: properties: - db_type: + knowledge_content: type: string - params: - items: - $ref: '#/definitions/v1.InstanceAdditionalParamResV1' - type: array + rule: + $ref: '#/definitions/v1.RuleInfo' + type: object type: object - v1.InstanceAdditionalParamReqV1: + v1.RuleParamReqV1: properties: - name: + key: type: string value: type: string type: object - v1.InstanceAdditionalParamResV1: + v1.RuleParamResV1: properties: - description: - example: 参数项中文名 + desc: type: string - name: - example: param name + key: type: string type: - example: int + enum: + - string + - int + - bool type: string value: - example: "0" type: string type: object - v1.InstanceConnectableResV1: - properties: - connect_error_message: - type: string - is_instance_connectable: - type: boolean - type: object - v1.InstanceConnectionResV1: + v1.RuleProjectTemplateDetailResV1: properties: - connect_error_message: + db_type: type: string - instance_name: + desc: type: string - is_instance_connectable: - type: boolean - type: object - v1.InstanceForCheckConnection: - properties: - name: + rule_list: + items: + $ref: '#/definitions/v1.RuleResV1' + type: array + rule_template_name: type: string type: object - v1.InstanceForCreatingTask: + v1.RuleReqV1: properties: - instance_name: + is_custom_rule: + type: boolean + level: + example: error type: string - instance_schema: + name: + example: ddl_check_index_count type: string - type: object - v1.InstanceResV1: - properties: - additional_params: + params: items: - $ref: '#/definitions/v1.InstanceAdditionalParamResV1' + $ref: '#/definitions/v1.RuleParamReqV1' type: array - db_host: - example: 10.10.10.10 - type: string - db_port: - example: "3306" + type: object + v1.RuleResV1: + properties: + annotation: + example: 避免多次 table rebuild 带来的消耗、以及对线上业务的影响 type: string db_type: example: mysql type: string - db_user: - example: root - type: string desc: - example: this is a instance type: string - instance_name: + is_custom_rule: + type: boolean + level: + enum: + - normal + - notice + - warn + - error + example: error type: string - maintenance_times: + params: items: - $ref: '#/definitions/v1.MaintenanceTimeResV1' + $ref: '#/definitions/v1.RuleParamResV1' type: array - rule_template_name: + rule_name: type: string - source: - example: SQLE + type: + example: 全局配置 type: string - sql_query_config: - $ref: '#/definitions/v1.SQLQueryConfigResV1' - type: object - type: object - v1.InstanceSchemaResV1: - properties: - schema_name_list: - items: - type: string - type: array type: object - v1.InstanceTableMeta: + v1.RuleRespV1: properties: - columns: - $ref: '#/definitions/v1.TableColumns' - type: object - create_table_sql: - type: string - indexes: - $ref: '#/definitions/v1.TableIndexes' - type: object - name: + desc: type: string - schema: + rule_name: type: string type: object - v1.InstanceTaskDetailResV1: + v1.RuleTemplateDetailResV1: properties: db_type: - example: mysql - type: string - id: - example: 1 - type: integer - rule_template: - example: default_mysql type: string - source: - example: actiontech-dmp - type: string - sync_instance_interval: - example: 0 0 * * * - type: string - url: - example: http://10.186.62.56:10000 + desc: type: string - version: - example: 1.23.1 + rule_list: + items: + $ref: '#/definitions/v1.RuleResV1' + type: array + rule_template_name: type: string type: object - v1.InstanceTaskResV1: + v1.RuleTemplateResV1: properties: db_type: - example: mysql - type: string - id: - example: 1 - type: integer - last_sync_status: - enum: - - succeeded - - failed - example: succeeded - type: string - last_sync_success_time: - example: "2021-08-12 12:00:00" type: string - source: - example: actiontech-dmp - type: string - url: - example: http://10.186.62.56:10000 + desc: type: string - version: - example: 1.23.1 + rule_template_name: type: string type: object - v1.InstanceTipResV1: + v1.RuleTemplateTipResV1: properties: - host: - type: string - instance_name: + db_type: type: string - instance_type: + rule_template_id: type: string - port: + rule_template_name: type: string - workflow_template_id: - type: integer type: object - v1.InstanceTypePercent: + v1.RuleTips: properties: - count: - type: integer - percent: - type: number - type: + db_type: type: string - type: object - v1.InstancesTypePercentV1: - properties: - instance_total_num: - type: integer - instance_type_percents: + rule: items: - $ref: '#/definitions/v1.InstanceTypePercent' + $ref: '#/definitions/v1.RuleRespV1' type: array type: object - v1.LDAPConfigurationReqV1: + v1.RuleTypeV1: properties: - enable_ldap: - type: boolean - enable_ssl: + is_custom_rule_type: type: boolean - ldap_connect_dn: - type: string - ldap_connect_pwd: - type: string - ldap_search_base_dn: - type: string - ldap_server_host: - type: string - ldap_server_port: - type: string - ldap_user_email_rdn_key: - type: string - ldap_user_name_rdn_key: + rule_count: + type: integer + rule_type: type: string type: object - v1.LDAPConfigurationResV1: + v1.SQLAuditRecord: properties: - enable_ldap: - type: boolean - enable_ssl: - type: boolean - ldap_connect_dn: + created_at: type: string - ldap_search_base_dn: + creator: type: string - ldap_server_host: + instance: + $ref: '#/definitions/v1.SQLAuditRecordInstance' + type: object + sql_audit_record_id: type: string - ldap_server_port: + sql_audit_status: type: string - ldap_user_email_rdn_key: + tags: + items: + type: string + type: array + task: + $ref: '#/definitions/v1.AuditTaskResV1' + type: object + type: object + v1.SQLAuditRecordInstance: + properties: + db_host: + example: 10.10.10.10 type: string - ldap_user_name_rdn_key: + db_port: + example: "3306" type: string type: object - v1.LicenseItem: + v1.SQLAuditRecordResData: properties: - description: + sql_audit_record_id: type: string - limit: + task: + $ref: '#/definitions/v1.AuditTaskResV1' + type: object + type: object + v1.SQLExplain: + properties: + classic_result: + $ref: '#/definitions/v1.ExplainClassicResult' + description: explain result in table format + type: object + message: type: string - name: + sql: type: string type: object - v1.LicenseUsageItem: + v1.SQLQueryConfigResV1: properties: - is_limited: + allow_query_when_less_than_audit_level: + enum: + - normal + - notice + - warn + - error + type: string + audit_enabled: type: boolean - limit: + max_pre_query_rows: type: integer - resource_type: - type: string - resource_type_desc: - type: string - used: + query_timeout_second: type: integer type: object - v1.LicenseUsageV1: + v1.Source: properties: - instances_usage: + audit_plan_name: + type: string + sql_audit_record_ids: items: - $ref: '#/definitions/v1.LicenseUsageItem' + type: string type: array - users_usage: - $ref: '#/definitions/v1.LicenseUsageItem' - type: object + type: + enum: + - audit_plan + - sql_audit_record + type: string type: object - v1.ListTableBySchemaResV1: + v1.SqlAnalysis: properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v1.Table' - type: array - message: - example: ok - type: string - type: object - v1.MaintenanceTimeReqV1: - properties: - maintenance_start_time: - $ref: '#/definitions/v1.TimeReqV1' + performance_statistics: + $ref: '#/definitions/v1.PerformanceStatistics' type: object - maintenance_stop_time: - $ref: '#/definitions/v1.TimeReqV1' + sql_explain: + $ref: '#/definitions/v1.SQLExplain' + type: object + table_metas: + $ref: '#/definitions/v1.TableMetas' type: object type: object - v1.MaintenanceTimeResV1: + v1.SqlAnalysisResDataV1: properties: - maintenance_start_time: - $ref: '#/definitions/v1.TimeResV1' - type: object - maintenance_stop_time: - $ref: '#/definitions/v1.TimeResV1' + sql_explain: + $ref: '#/definitions/v1.SQLExplain' type: object + table_metas: + items: + $ref: '#/definitions/v1.TableMeta' + type: array type: object - v1.ManagementPermissionResV1: + v1.SqlAverageExecutionTime: properties: - code: + average_execution_seconds: type: integer - desc: - type: string - type: object - v1.MemberGroupUserItem: - properties: - name: + instance_name: type: string + max_execution_seconds: + type: integer + min_execution_seconds: + type: integer type: object - v1.MemberTipResV1: + v1.SqlExecutionFailPercent: properties: - user_name: + instance_name: type: string + percent: + type: number type: object - v1.Oauth2ConfigurationReqV1: + v1.SqlManage: properties: - access_token_tag: - type: string - client_host: - type: string - client_id: - type: string - client_key: - type: string - enable_oauth2: - type: boolean - login_tip: - type: string - scopes: + appear_num: + type: integer + assignees: items: type: string type: array - server_auth_url: - type: string - server_token_url: - type: string - server_user_id_url: - type: string - user_id_tag: - type: string - type: object - v1.Operation: - properties: - op_code: - type: integer - op_desc: - type: string - type: object - v1.OperationActionList: - properties: - desc: - type: string - operation_action: + audit_result: + items: + $ref: '#/definitions/v1.AuditResult' + type: array + endpoint: type: string - operation_type: + first_appear_time: type: string - type: object - v1.OperationRecordList: - properties: id: type: integer - operation_action: + instance_name: type: string - operation_content: + last_appear_time: type: string - operation_time: + remark: type: string - operation_type_name: + schema_name: type: string - operation_user: - $ref: '#/definitions/v1.OperationUser' + source: + $ref: '#/definitions/v1.Source' type: object - project_name: + sql: + type: string + sql_fingerprint: type: string status: enum: - - succeeded - - failed + - unhandled + - solved + - ignored + - manual_audited type: string type: object - v1.OperationResV1: + v1.StatisticAuditPlanResV1: properties: - op_code: + code: + example: 0 type: integer - op_desc: - type: string - type: object - v1.OperationTypeNameList: - properties: - desc: - type: string - operation_type_name: - type: string - type: object - v1.OperationUser: - properties: - ip: - type: string - user_name: + data: + items: + $ref: '#/definitions/v1.DBTypeAuditPlan' + type: array + message: + example: ok type: string type: object - v1.ParseProjectRuleTemplateFileResDataV1: + v1.StatisticRiskWorkflowResV1: properties: - db_type: - type: string - desc: - type: string - name: - type: string - rule_list: + code: + example: 0 + type: integer + data: items: - $ref: '#/definitions/v1.RuleResV1' + $ref: '#/definitions/v1.RiskWorkflow' type: array + message: + example: ok + type: string type: object - v1.ParseProjectRuleTemplateFileResV1: + v1.StatisticsAuditedSQLResV1: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.ParseProjectRuleTemplateFileResDataV1' + $ref: '#/definitions/v1.AuditedSQLCount' type: object message: example: ok type: string + risk_rate: + type: integer type: object - v1.PartialSyncAuditPlanSQLsReqV1: + v1.SystemVariablesResV1: properties: - audit_plan_sql_list: - items: - $ref: '#/definitions/v1.AuditPlanSQLReqV1' - type: array + operation_record_expired_hours: + type: integer + url: + type: string + workflow_expired_hours: + type: integer type: object - v1.PatchUserGroupReqV1: + v1.Table: properties: - is_disabled: - type: boolean - user_group_desc: - example: this is a group + name: type: string - user_name_list: - items: - type: string - type: array type: object - v1.PerformanceStatistics: + v1.TableColumns: properties: - affect_rows: - $ref: '#/definitions/v1.AffectRows' - type: object + head: + items: + $ref: '#/definitions/v1.TableMetaItemHeadResV1' + type: array + rows: + items: + additionalProperties: + type: string + type: object + type: array type: object - v1.PersonaliseReqV1: + v1.TableIndexes: properties: - title: - type: string + head: + items: + $ref: '#/definitions/v1.TableMetaItemHeadResV1' + type: array + rows: + items: + additionalProperties: + type: string + type: object + type: array type: object - v1.ProjectDetailItem: + v1.TableMeta: properties: - archived: - type: boolean - create_time: - type: string - create_user_name: + columns: + $ref: '#/definitions/v1.TableColumns' + type: object + create_table_sql: type: string - desc: + indexes: + $ref: '#/definitions/v1.TableIndexes' + type: object + message: type: string name: type: string + schema: + type: string type: object - v1.ProjectListItem: + v1.TableMetaItemHeadResV1: properties: - archived: - type: boolean - create_time: - type: string - create_user_name: - type: string desc: type: string - name: - type: string - type: object - v1.ProjectRuleTemplateInstance: - properties: - name: + field_name: type: string type: object - v1.ProjectRuleTemplateResV1: + v1.TableMetas: properties: - db_type: - type: string - desc: + err_message: type: string - instance_list: + table_meta_items: items: - $ref: '#/definitions/v1.ProjectRuleTemplateInstance' + $ref: '#/definitions/v1.TableMeta' type: array - rule_template_name: + type: object + v1.TestAuditPlanNotifyConfigResDataV1: + properties: + is_notify_send_normal: + type: boolean + send_error_message: type: string type: object - v1.ProjectScore: + v1.TestAuditPlanNotifyConfigResV1: properties: - score: + code: + example: 0 type: integer + data: + $ref: '#/definitions/v1.TestAuditPlanNotifyConfigResDataV1' + type: object + message: + example: ok + type: string type: object - v1.ProjectTipResV1: + v1.TestDingTalkConfigResDataV1: properties: - project_name: + is_ding_talk_send_normal: + type: boolean + send_error_message: type: string type: object - v1.RejectWorkflowReqV1: + v1.TestDingTalkConfigResV1: properties: - reason: + code: + example: 0 + type: integer + data: + $ref: '#/definitions/v1.TestDingTalkConfigResDataV1' + type: object + message: + example: ok type: string type: object - v1.RiskAuditPlan: + v1.TestFeishuConfigResDataV1: properties: - audit_plan_name: - type: string - audit_plan_report_id: - type: integer - audit_plan_report_timestamp: - type: string - risk_sql_count: - type: integer - trigger_audit_plan_time: + error_message: type: string + is_message_sent_normally: + type: boolean type: object - v1.RiskWorkflow: + v1.TestFeishuConfigResV1: properties: - create_user_name: - type: string - update_time: - type: string - workflow_id: - type: string - workflow_name: - type: string - workflow_status: + code: + example: 0 + type: integer + data: + $ref: '#/definitions/v1.TestFeishuConfigResDataV1' + type: object + message: + example: ok type: string type: object - v1.RoleResV1: + v1.TestFeishuConfigurationReqV1: properties: - is_disabled: - type: boolean - operation_list: - items: - $ref: '#/definitions/v1.Operation' - type: array - role_desc: + account: type: string - role_name: + account_type: + enum: + - email + - phone type: string type: object - v1.RoleTipResV1: + v1.TimeResV1: properties: - operations: - items: - $ref: '#/definitions/v1.Operation' - type: array - role_name: - type: string + hour: + type: integer + minute: + type: integer type: object - v1.RoleUserCount: + v1.TriggerAuditPlanResV1: properties: - count: + code: + example: 0 type: integer - role: + data: + $ref: '#/definitions/v1.AuditPlanReportResV1' + type: object + message: + example: ok type: string type: object - v1.RuleInfo: + v1.UpdateAuditPlanNotifyConfigReqV1: properties: - annotation: - example: this is test rule + enable_email_notify: + type: boolean + enable_web_hook_notify: + type: boolean + notify_interval: + default: 10 + type: integer + notify_level: + default: warn + enum: + - normal + - notice + - warn + - error type: string - desc: - example: this is test rule + web_hook_template: + type: string + web_hook_url: type: string type: object - v1.RuleKnowledgeResV1: + v1.UpdateAuditPlanReqV1: properties: - knowledge_content: + audit_plan_cron: + example: 0 */2 * * * + type: string + audit_plan_instance_database: + example: app1 + type: string + audit_plan_instance_name: + example: test_mysql + type: string + audit_plan_params: + items: + $ref: '#/definitions/v1.AuditPlanParamReqV1' + type: array + rule_template_name: + example: default_MySQL type: string - rule: - $ref: '#/definitions/v1.RuleInfo' - type: object type: object - v1.RuleParamReqV1: + v1.UpdateAuditTaskSQLsReqV1: properties: - key: - type: string - value: + description: type: string type: object - v1.RuleParamResV1: + v1.UpdateAuditWhitelistReqV1: properties: desc: + example: used for rapid release type: string - key: - type: string - type: + match_type: enum: - - string - - int - - bool + - exact_match + - fp_match + example: exact_match type: string value: + example: create table type: string type: object - v1.RuleProjectTemplateDetailResV1: - properties: - db_type: - type: string - desc: - type: string - instance_list: - items: - $ref: '#/definitions/v1.ProjectRuleTemplateInstance' - type: array - rule_list: - items: - $ref: '#/definitions/v1.RuleResV1' - type: array - rule_template_name: - type: string - type: object - v1.RuleReqV1: + v1.UpdateCompanyNoticeReq: properties: - is_custom_rule: - type: boolean - level: - example: error - type: string - name: - example: ddl_check_index_count + notice_str: type: string - params: - items: - $ref: '#/definitions/v1.RuleParamReqV1' - type: array type: object - v1.RuleResV1: + v1.UpdateCustomRuleReqV1: properties: annotation: - example: 避免多次 table rebuild 带来的消耗、以及对线上业务的影响 - type: string - db_type: - example: mysql + example: this is test rule type: string desc: + example: this is test rule type: string - is_custom_rule: - type: boolean level: enum: - normal - notice - warn - error - example: error + example: notice type: string - params: - items: - $ref: '#/definitions/v1.RuleParamResV1' - type: array - rule_name: + rule_script: type: string type: - example: 全局配置 + example: DDL规则 type: string type: object - v1.RuleRespV1: + v1.UpdateDingTalkConfigurationReqV1: properties: - desc: + app_key: type: string - rule_name: + app_secret: type: string + is_enable_ding_talk_notify: + type: boolean + required: + - app_key + - app_secret + - is_enable_ding_talk_notify type: object - v1.RuleTemplateDetailResV1: + v1.UpdateFeishuConfigurationReqV1: properties: - db_type: + app_id: + type: string + app_secret: type: string + is_feishu_notification_enabled: + type: boolean + required: + - app_id + - app_secret + - is_feishu_notification_enabled + type: object + v1.UpdateProjectRuleTemplateReqV1: + properties: desc: type: string - instance_list: - items: - $ref: '#/definitions/v1.GlobalRuleTemplateInstance' - type: array rule_list: items: - $ref: '#/definitions/v1.RuleResV1' + $ref: '#/definitions/v1.RuleReqV1' type: array - rule_template_name: - type: string type: object - v1.RuleTemplateResV1: + v1.UpdateRuleKnowledgeReq: properties: - db_type: + knowledge_content: type: string + type: object + v1.UpdateRuleTemplateReqV1: + properties: desc: type: string - instance_list: + rule_list: items: - $ref: '#/definitions/v1.GlobalRuleTemplateInstance' + $ref: '#/definitions/v1.RuleReqV1' type: array - rule_template_name: - type: string - type: object - v1.RuleTemplateTipResV1: - properties: - db_type: - type: string - rule_template_name: - type: string type: object - v1.RuleTips: + v1.UpdateSQLAuditRecordReqV1: properties: - db_type: - type: string - rule: + tags: items: - $ref: '#/definitions/v1.RuleRespV1' + type: string type: array type: object - v1.RuleTypeV1: + v1.UpdateSystemVariablesReqV1: properties: - is_custom_rule_type: - type: boolean - rule_count: + operation_record_expired_hours: + example: 2160 type: integer - rule_type: - type: string - type: object - v1.SMTPConfigurationResV1: - properties: - enable_smtp_notify: - type: boolean - is_skip_verify: - type: boolean - smtp_host: - type: string - smtp_port: - type: string - smtp_username: + url: + example: http://10.186.61.32:8080 type: string + workflow_expired_hours: + example: 720 + type: integer type: object - v1.SQLAuditRecord: + v1.UpdateWorkflowReqV1: properties: - created_at: - type: string - creator: - type: string - instance: - $ref: '#/definitions/v1.SQLAuditRecordInstance' - type: object - sql_audit_record_id: - type: string - sql_audit_status: - type: string - tags: + task_ids: items: - type: string + type: integer type: array - task: - $ref: '#/definitions/v1.AuditTaskResV1' - type: object - type: object - v1.SQLAuditRecordInstance: - properties: - db_host: - example: 10.10.10.10 - type: string - db_port: - example: "3306" - type: string - type: object - v1.SQLAuditRecordResData: - properties: - sql_audit_record_id: - type: string - task: - $ref: '#/definitions/v1.AuditTaskResV1' - type: object type: object - v1.SQLExplain: + v1.UpdateWorkflowScheduleReqV1: properties: - classic_result: - $ref: '#/definitions/v1.ExplainClassicResult' - description: explain result in table format - type: object - message: - type: string - sql: + schedule_time: type: string type: object - v1.SQLQueryConfigReqV1: + v1.UpdateWorkflowTemplateReqV1: properties: - allow_query_when_less_than_audit_level: + allow_submit_when_less_audit_level: enum: - normal - notice - warn - error - example: error type: string - audit_enabled: - example: false - type: boolean - max_pre_query_rows: - example: 100 - type: integer - query_timeout_second: - example: 10 - type: integer + desc: + type: string + workflow_step_template_list: + items: + $ref: '#/definitions/v1.WorkFlowStepTemplateReqV1' + type: array type: object - v1.SQLQueryConfigResV1: + v1.UserTipResV1: properties: - allow_query_when_less_than_audit_level: - enum: - - normal - - notice - - warn - - error + user_id: + type: string + user_name: type: string - audit_enabled: - type: boolean - max_pre_query_rows: - type: integer - query_timeout_second: - type: integer type: object - v1.Source: + v1.WorkFlowStepTemplateReqV1: properties: - audit_plan_name: - type: string - sql_audit_record_ids: + approved_by_authorized: + type: boolean + assignee_user_id_list: items: type: string type: array + desc: + type: string + execute_by_authorized: + type: boolean type: enum: - - audit_plan - - sql_audit_record + - sql_review + - sql_execute type: string type: object - v1.SqlAnalysis: - properties: - performance_statistics: - $ref: '#/definitions/v1.PerformanceStatistics' - type: object - sql_explain: - $ref: '#/definitions/v1.SQLExplain' - type: object - table_metas: - $ref: '#/definitions/v1.TableMetas' - type: object - type: object - v1.SqlAnalysisResDataV1: + v1.WorkFlowStepTemplateResV1: properties: - sql_explain: - $ref: '#/definitions/v1.SQLExplain' - type: object - table_metas: + approved_by_authorized: + type: boolean + assignee_user_id_list: items: - $ref: '#/definitions/v1.TableMeta' + type: string type: array - type: object - v1.SqlAverageExecutionTime: - properties: - average_execution_seconds: + desc: + type: string + execute_by_authorized: + type: boolean + number: type: integer - instance_name: + type: type: string - max_execution_seconds: + type: object + v1.WorkflowAuditPassPercentV1: + properties: + audit_pass_percent: + type: number + type: object + v1.WorkflowCountsV1: + properties: + today_count: type: integer - min_execution_seconds: + total: type: integer type: object - v1.SqlExecutionFailPercent: + v1.WorkflowCreatedCountsEachDayItem: properties: - instance_name: + date: + example: "2022-08-24" type: string - percent: - type: number + value: + type: integer type: object - v1.SqlManage: + v1.WorkflowCreatedCountsEachDayV1: properties: - appear_num: - type: integer - assignees: - items: - type: string - type: array - audit_result: + samples: items: - $ref: '#/definitions/v1.AuditResult' + $ref: '#/definitions/v1.WorkflowCreatedCountsEachDayItem' type: array - endpoint: - type: string - first_appear_time: - type: string - id: - type: integer - instance_name: - type: string - last_appear_time: + type: object + v1.WorkflowDetailResV1: + properties: + create_time: type: string - remark: + create_user_name: type: string - schema_name: + current_step_assignee_user_name_list: + items: + type: string + type: array + current_step_type: + enum: + - sql_review + - sql_execute type: string - source: - $ref: '#/definitions/v1.Source' - type: object - sql: + desc: type: string - sql_fingerprint: + project_name: type: string status: enum: - - unhandled - - solved - - ignored - - manual_audited + - wait_for_audit + - wait_for_execution + - rejected + - canceled + - exec_failed + - executing + - finished + type: string + workflow_id: + type: string + workflow_name: type: string type: object - v1.StatisticAuditPlanResV1: + v1.WorkflowPassPercentV1: properties: - code: - example: 0 + audit_pass_percent: + type: number + execution_success_percent: + type: number + type: object + v1.WorkflowPercentCountedByInstanceType: + properties: + count: type: integer - data: - items: - $ref: '#/definitions/v1.DBTypeAuditPlan' - type: array - message: - example: ok + instance_type: type: string + percent: + type: number type: object - v1.StatisticRiskWorkflowResV1: + v1.WorkflowPercentCountedByInstanceTypeV1: properties: - code: - example: 0 - type: integer - data: + workflow_percents: items: - $ref: '#/definitions/v1.RiskWorkflow' + $ref: '#/definitions/v1.WorkflowPercentCountedByInstanceType' type: array - message: - example: ok - type: string + workflow_total_num: + type: integer type: object - v1.StatisticsAuditedSQLResV1: + v1.WorkflowRecordResV1: properties: - code: - example: 0 + current_step_number: type: integer - data: - $ref: '#/definitions/v1.AuditedSQLCount' - type: object - message: - example: ok - type: string - risk_rate: - type: integer - type: object - v1.SyncInstanceResV1: - properties: - is_sync_instance_success: - example: true - type: boolean - sync_error_message: + status: + enum: + - wait_for_audit + - wait_for_execution + - rejected + - canceled + - exec_failed + - executing + - finished type: string - type: object - v1.SyncTaskTipsResV1: - properties: - db_types: + tasks: items: - type: string + $ref: '#/definitions/v1.WorkflowTaskItem' + type: array + workflow_step_list: + items: + $ref: '#/definitions/v1.WorkflowStepResV1' type: array - source: - example: actiontech-dmp - type: string type: object - v1.SystemVariablesResV1: + v1.WorkflowRejectedPercentGroupByCreator: properties: - operation_record_expired_hours: - type: integer - url: + creator: type: string - workflow_expired_hours: + rejected_percent: + type: number + workflow_total_num: type: integer type: object - v1.Table: + v1.WorkflowRejectedPercentGroupByInstance: properties: - name: + instance_name: type: string + rejected_percent: + type: number + workflow_total_num: + type: integer type: object - v1.TableColumns: - properties: - head: - items: - $ref: '#/definitions/v1.TableMetaItemHeadResV1' - type: array - rows: - items: - additionalProperties: - type: string - type: object - type: array - type: object - v1.TableIndexes: - properties: - head: - items: - $ref: '#/definitions/v1.TableMetaItemHeadResV1' - type: array - rows: - items: - additionalProperties: - type: string - type: object - type: array - type: object - v1.TableMeta: + v1.WorkflowResV1: properties: - columns: - $ref: '#/definitions/v1.TableColumns' - type: object - create_table_sql: - type: string - indexes: - $ref: '#/definitions/v1.TableIndexes' - type: object - message: - type: string - name: + create_time: type: string - schema: + create_user_name: type: string - type: object - v1.TableMetaItemHeadResV1: - properties: desc: type: string - field_name: - type: string - type: object - v1.TableMetas: - properties: - err_message: + mode: + enum: + - same_sqls + - different_sqls type: string - table_meta_items: + record: + $ref: '#/definitions/v1.WorkflowRecordResV1' + type: object + record_history_list: items: - $ref: '#/definitions/v1.TableMeta' + $ref: '#/definitions/v1.WorkflowRecordResV1' type: array - type: object - v1.TestAuditPlanNotifyConfigResDataV1: - properties: - is_notify_send_normal: - type: boolean - send_error_message: + workflow_name: type: string type: object - v1.TestAuditPlanNotifyConfigResV1: + v1.WorkflowStageDuration: properties: - code: - example: 0 + minutes: type: integer - data: - $ref: '#/definitions/v1.TestAuditPlanNotifyConfigResDataV1' - type: object - message: - example: ok - type: string type: object - v1.TestDingTalkConfigResDataV1: + v1.WorkflowStatisticsResV1: properties: - is_ding_talk_send_normal: - type: boolean - send_error_message: - type: string + my_need_execute_workflow_number: + type: integer + my_need_review_workflow_number: + type: integer + my_on_process_workflow_number: + type: integer + my_rejected_workflow_number: + type: integer + need_me_to_execute_workflow_number: + type: integer + need_me_to_review_workflow_number: + type: integer type: object - v1.TestDingTalkConfigResV1: + v1.WorkflowStatusCountV1: properties: - code: - example: 0 + closed_count: + type: integer + executing_count: + type: integer + executing_failed_count: + type: integer + execution_success_count: + type: integer + rejected_count: + type: integer + waiting_for_audit_count: + type: integer + waiting_for_execution_count: type: integer - data: - $ref: '#/definitions/v1.TestDingTalkConfigResDataV1' - type: object - message: - example: ok - type: string type: object - v1.TestFeishuConfigResDataV1: + v1.WorkflowStepResV1: properties: - error_message: + assignee_user_name_list: + items: + type: string + type: array + desc: type: string - is_message_sent_normally: - type: boolean - type: object - v1.TestFeishuConfigResV1: - properties: - code: - example: 0 + number: type: integer - data: - $ref: '#/definitions/v1.TestFeishuConfigResDataV1' - type: object - message: - example: ok + operation_time: type: string - type: object - v1.TestFeishuConfigurationReqV1: - properties: - account: + operation_user_name: type: string - account_type: + reason: + type: string + state: enum: - - email - - phone + - initialized + - approved + - rejected + type: string + type: + enum: + - create_workflow + - update_workflow + - sql_review + - sql_execute type: string + workflow_step_id: + type: integer type: object - v1.TestSMTPConfigurationReqV1: + v1.WorkflowTaskItem: properties: - recipient_addr: - type: string + task_id: + type: integer type: object - v1.TestSMTPConfigurationResDataV1: + v1.WorkflowTemplateDetailResV1: properties: - is_smtp_send_normal: - type: boolean - send_error_message: + allow_submit_when_less_audit_level: + enum: + - normal + - notice + - warn + - error + type: string + desc: + type: string + update_time: + type: string + workflow_step_template_list: + items: + $ref: '#/definitions/v1.WorkFlowStepTemplateResV1' + type: array + workflow_template_name: type: string type: object - v1.TestSMTPConfigurationResV1: + v2.AffectRows: properties: - code: - example: 0 + count: type: integer - data: - $ref: '#/definitions/v1.TestSMTPConfigurationResDataV1' - type: object - message: - example: ok + err_message: type: string type: object - v1.TestWeChatConfigurationReqV1: + v2.AuditPlanReportSQLResV2: properties: - recipient_id: + audit_plan_report_sql: + example: select * from t1 where id = 1 type: string + audit_plan_report_sql_audit_result: + items: + $ref: '#/definitions/v2.AuditResult' + type: array + number: + example: 1 + type: integer type: object - v1.TestWeChatConfigurationResDataV1: - properties: - is_wechat_send_normal: - type: boolean - send_error_message: - type: string - type: object - v1.TestWeChatConfigurationResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.TestWeChatConfigurationResDataV1' - type: object - message: - example: ok - type: string - type: object - v1.TestWorkflowWebHookConfigResDataV1: - properties: - send_error_message: - type: string - type: object - v1.TestWorkflowWebHookConfigResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.TestWorkflowWebHookConfigResDataV1' - type: object - message: - example: ok - type: string - type: object - v1.TimeReqV1: - properties: - hour: - type: integer - minute: - type: integer - type: object - v1.TimeResV1: - properties: - hour: - type: integer - minute: - type: integer - type: object - v1.TriggerAuditPlanResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.AuditPlanReportResV1' - type: object - message: - example: ok - type: string - type: object - v1.TriggerSyncInstanceResV1: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v1.SyncInstanceResV1' - type: object - message: - example: ok - type: string - type: object - v1.UpdateAuditPlanNotifyConfigReqV1: - properties: - enable_email_notify: - type: boolean - enable_web_hook_notify: - type: boolean - notify_interval: - default: 10 - type: integer - notify_level: - default: warn - enum: - - normal - - notice - - warn - - error - type: string - web_hook_template: - type: string - web_hook_url: - type: string - type: object - v1.UpdateAuditPlanReqV1: + v2.AuditPlanResV2: properties: audit_plan_cron: example: 0 */2 * * * type: string + audit_plan_db_type: + example: mysql + type: string audit_plan_instance_database: example: app1 type: string audit_plan_instance_name: example: test_mysql type: string - audit_plan_params: - items: - $ref: '#/definitions/v1.AuditPlanParamReqV1' - type: array - rule_template_name: - example: default_MySQL + audit_plan_meta: + $ref: '#/definitions/v1.AuditPlanMetaV1' + type: object + audit_plan_name: + example: audit_for_java_app1 type: string - type: object - v1.UpdateAuditTaskSQLsReqV1: - properties: - description: + audit_plan_token: + example: it's a JWT Token for scanner type: string + rule_template: + $ref: '#/definitions/v2.RuleTemplateV2' + type: object type: object - v1.UpdateAuditWhitelistReqV1: + v2.AuditPlanSQLReqV2: properties: - desc: - example: used for rapid release - type: string - match_type: - enum: - - exact_match - - fp_match - example: exact_match - type: string - value: - example: create table + audit_plan_sql_counter: + example: "6" type: string - type: object - v1.UpdateCompanyNoticeReq: - properties: - notice_str: + audit_plan_sql_fingerprint: + example: select * from t1 where id = ? type: string - type: object - v1.UpdateCurrentUserPasswordReqV1: - properties: - new_password: + audit_plan_sql_last_receive_text: + example: select * from t1 where id = 1 type: string - password: + audit_plan_sql_last_receive_timestamp: + example: RFC3339 type: string - type: object - v1.UpdateCurrentUserReqV1: - properties: - email: + audit_plan_sql_schema: + example: db1 type: string - phone: + db_user: + example: database_user001 type: string - wechat_id: - example: UserID + endpoints: + items: + type: string + type: array + first_query_at: + example: "2023-09-12T02:48:01.317880Z" type: string + query_time_avg: + example: 3.22 + type: number + query_time_max: + example: 5.22 + type: number type: object - v1.UpdateCustomRuleReqV1: + v2.AuditResDataV2: properties: - annotation: - example: this is test rule - type: string - desc: - example: this is test rule - type: string - level: + audit_level: enum: - normal - notice - warn - error - example: notice - type: string - rule_script: - type: string - type: - example: DDL规则 + - "" type: string + pass_rate: + type: number + score: + type: integer + sql_results: + items: + $ref: '#/definitions/v2.AuditSQLResV2' + type: array type: object - v1.UpdateDingTalkConfigurationReqV1: + v2.AuditResult: properties: - app_key: + db_type: type: string - app_secret: + level: + example: warn + type: string + message: + example: 避免使用不必要的内置函数md5() + type: string + rule_name: type: string - is_enable_ding_talk_notify: - type: boolean - required: - - app_key - - app_secret - - is_enable_ding_talk_notify type: object - v1.UpdateFeishuConfigurationReqV1: + v2.AuditSQLResV2: properties: - app_id: + audit_level: type: string - app_secret: + audit_result: + items: + $ref: '#/definitions/v2.AuditResult' + type: array + exec_sql: type: string - is_feishu_notification_enabled: - type: boolean - required: - - app_id - - app_secret - - is_feishu_notification_enabled + number: + type: integer type: object - v1.UpdateInstanceReqV1: + v2.AuditTaskSQLResV2: properties: - additional_params: + audit_level: + type: string + audit_result: items: - $ref: '#/definitions/v1.InstanceAdditionalParamReqV1' + $ref: '#/definitions/v2.AuditResult' type: array - db_host: - example: 10.10.10.10 + audit_status: type: string - db_password: - example: "123456" + description: type: string - db_port: - example: "3306" + exec_result: type: string - db_type: - example: mysql + exec_sql: type: string - db_user: - example: root + exec_status: type: string - desc: - example: this is a test instance + number: + type: integer + rollback_sql: type: string - maintenance_times: - items: - $ref: '#/definitions/v1.MaintenanceTimeReqV1' - type: array - rule_template_name: + sql_source_file: type: string - sql_query_config: - $ref: '#/definitions/v1.SQLQueryConfigReqV1' - type: object type: object - v1.UpdateMemberGroupReqV1: + v2.BatchCancelWorkflowsReqV2: properties: - roles: + workflow_id_list: items: - $ref: '#/definitions/v1.BindRoleReqV1' + type: string type: array type: object - v1.UpdateMemberReqV1: + v2.BatchCompleteWorkflowsReqV2: properties: - is_manager: - type: boolean - roles: + workflow_id_list: items: - $ref: '#/definitions/v1.BindRoleReqV1' + type: string type: array type: object - v1.UpdateOtherUserPasswordReqV1: - properties: - password: - type: string - type: object - v1.UpdateProjectReqV1: + v2.CreateWorkflowReqV2: properties: desc: type: string - type: object - v1.UpdateProjectRuleTemplateReqV1: - properties: - desc: - type: string - instance_name_list: - example: - - mysql-xxx - items: - type: string - type: array - rule_list: - items: - $ref: '#/definitions/v1.RuleReqV1' - type: array - type: object - v1.UpdateRoleReqV1: - properties: - is_disabled: - type: boolean - operation_code_list: + task_ids: items: type: integer type: array - role_desc: - type: string - type: object - v1.UpdateRuleKnowledgeReq: - properties: - knowledge_content: + workflow_subject: type: string type: object - v1.UpdateRuleTemplateReqV1: + v2.CreateWorkflowResV2: properties: - desc: + code: + example: 0 + type: integer + data: + $ref: '#/definitions/v2.CreateWorkflowResV2Data' + type: object + message: + example: ok type: string - rule_list: - items: - $ref: '#/definitions/v1.RuleReqV1' - type: array type: object - v1.UpdateSMTPConfigurationReqV1: + v2.CreateWorkflowResV2Data: properties: - enable_smtp_notify: - type: boolean - is_skip_verify: - type: boolean - smtp_host: - example: smtp.email.qq.com - type: string - smtp_password: - example: "123" - type: string - smtp_port: - example: "465" - type: string - smtp_username: - example: test@qq.com + workflow_id: type: string type: object - v1.UpdateSQLAuditRecordReqV1: + v2.DirectAuditFileReqV2: properties: - tags: + file_contents: + description: |- + 调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现 + 每个数组元素是一个文件内容 + example: + - select * from t1; select * from t2; items: type: string type: array - type: object - v1.UpdateSyncInstanceTaskReqV1: - properties: - global_rule_template: - example: default_mysql + instance_name: + example: instance1 type: string - sync_instance_interval: - example: 0 0 * * * + instance_type: + example: MySQL type: string - url: - example: http://10.186.62.56:10000 + project_name: + example: project1 type: string - version: - example: 5.23.01.0 + schema_name: + example: schema1 type: string - type: object - v1.UpdateSystemVariablesReqV1: - properties: - operation_record_expired_hours: - example: 2160 - type: integer - url: - example: http://10.186.61.32:8080 + sql_type: + enum: + - sql + - mybatis + - "" + example: sql type: string - workflow_expired_hours: - example: 720 - type: integer type: object - v1.UpdateUserReqV1: + v2.DirectAuditReqV2: properties: - email: + instance_type: + example: MySQL type: string - is_disabled: - type: boolean - management_permission_code_list: - items: - type: integer - type: array - phone: + sql_content: + description: 调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现 + example: select * from t1; select * from t2; type: string - user_group_name_list: - items: - type: string - type: array - wechat_id: - example: UserID + sql_type: + enum: + - sql + - mybatis + - "" + example: sql type: string type: object - v1.UpdateWeChatConfigurationReqV1: + v2.DirectAuditResV2: properties: - agent_id: + code: + example: 0 type: integer - corp_id: - type: string - corp_secret: - type: string - enable_wechat_notify: - type: boolean - proxy_ip: + data: + $ref: '#/definitions/v2.AuditResDataV2' + type: object + message: + example: ok type: string - safe_enabled: - type: boolean - type: object - v1.UpdateWorkflowReqV1: - properties: - task_ids: - items: - type: integer - type: array type: object - v1.UpdateWorkflowScheduleReqV1: + v2.DriverMeta: properties: - schedule_time: + default_port: + type: integer + driver_name: + type: string + logo_url: type: string type: object - v1.UpdateWorkflowTemplateReqV1: + v2.FullSyncAuditPlanSQLsReqV2: properties: - allow_submit_when_less_audit_level: - enum: - - normal - - notice - - warn - - error - type: string - desc: - type: string - instance_name_list: - items: - type: string - type: array - workflow_step_template_list: + audit_plan_sql_list: items: - $ref: '#/definitions/v1.WorkFlowStepTemplateReqV1' + $ref: '#/definitions/v2.AuditPlanSQLReqV2' type: array type: object - v1.UploadLogoResDataV1: - properties: - logo_url: - type: string - type: object - v1.UploadLogoResV1: + v2.GetAuditPlanAnalysisDataResV2: properties: code: example: 0 type: integer data: - $ref: '#/definitions/v1.UploadLogoResDataV1' + $ref: '#/definitions/v2.TaskAnalysisDataV2' type: object message: example: ok type: string type: object - v1.UserBindProjectResV1: + v2.GetAuditPlanReportSQLsResV2: properties: - is_manager: - type: boolean - project_name: + code: + example: 0 + type: integer + data: + items: + $ref: '#/definitions/v2.AuditPlanReportSQLResV2' + type: array + message: + example: ok type: string + total_nums: + type: integer type: object - v1.UserDetailResV1: + v2.GetAuditPlansResV2: properties: - bind_projects: + code: + example: 0 + type: integer + data: items: - $ref: '#/definitions/v1.UserBindProjectResV1' + $ref: '#/definitions/v2.AuditPlanResV2' type: array - email: - type: string - is_admin: - type: boolean - is_disabled: - type: boolean - login_type: + message: + example: ok type: string - management_permission_list: + total_nums: + type: integer + type: object + v2.GetAuditTaskSQLsResV2: + properties: + code: + example: 0 + type: integer + data: items: - $ref: '#/definitions/v1.ManagementPermissionResV1' + $ref: '#/definitions/v2.AuditTaskSQLResV2' type: array - phone: + message: + example: ok type: string - user_group_name_list: + total_nums: + type: integer + type: object + v2.GetDriversRes: + properties: + code: + example: 0 + type: integer + data: items: - type: string + $ref: '#/definitions/v2.DriverMeta' type: array - user_name: - type: string - wechat_id: + message: + example: ok type: string type: object - v1.UserGroupListItemResV1: + v2.GetInstanceResV2: properties: - is_disabled: - type: boolean - user_group_desc: - type: string - user_group_name: + code: + example: 0 + type: integer + data: + $ref: '#/definitions/v2.InstanceResV2' + type: object + message: + example: ok type: string - user_name_list: - items: - type: string - type: array type: object - v1.UserGroupTipListItem: + v2.GetSqlManageListResp: properties: - user_group_name: - type: string - user_names: + code: + example: 0 + type: integer + data: items: - type: string + $ref: '#/definitions/v2.SqlManage' type: array + message: + example: ok + type: string + sql_manage_bad_num: + type: integer + sql_manage_optimized_num: + type: integer + sql_manage_total_num: + type: integer type: object - v1.UserLoginReqV1: + v2.GetTaskAnalysisDataResV2: properties: - password: - example: "123456" - type: string - username: - example: test + code: + example: 0 + type: integer + data: + $ref: '#/definitions/v2.TaskAnalysisDataV2' + type: object + message: + example: ok type: string type: object - v1.UserLoginResV1: + v2.GetWorkflowResV2: properties: - token: - example: this is a jwt token string + code: + example: 0 + type: integer + data: + $ref: '#/definitions/v2.WorkflowResV2' + type: object + message: + example: ok type: string type: object - v1.UserResV1: + v2.GetWorkflowTasksItemV2: properties: - email: - type: string - is_disabled: - type: boolean - login_type: - type: string - management_permission_list: + current_step_assignee_user_name_list: items: - $ref: '#/definitions/v1.ManagementPermissionResV1' + type: string type: array - phone: + exec_end_time: + type: string + exec_start_time: + type: string + execution_user_name: type: string - user_group_name_list: + instance_maintenance_times: items: - type: string + $ref: '#/definitions/v1.MaintenanceTimeResV1' type: array - user_name: + instance_name: type: string - wechat_id: + schedule_time: type: string - type: object - v1.UserTipResV1: - properties: - user_name: + status: + enum: + - wait_for_audit + - wait_for_execution + - exec_scheduled + - exec_failed + - exec_succeeded + - executing + - manually_executed + - terminating + - terminate_succeeded + - terminate_failed type: string - type: object - v1.WeChatConfigurationResV1: - properties: - agent_id: + task_id: + type: integer + task_pass_rate: + type: number + task_score: type: integer - corp_id: - type: string - enable_wechat_notify: - type: boolean - proxy_ip: - type: string - safe_enabled: - type: boolean type: object - v1.WebHookConfigV1: + v2.GetWorkflowTasksResV2: properties: - enable: - type: boolean - max_retry_times: - type: integer - retry_interval_seconds: + code: + example: 0 type: integer - token: - type: string - url: + data: + items: + $ref: '#/definitions/v2.GetWorkflowTasksItemV2' + type: array + message: + example: ok type: string type: object - v1.WorkFlowStepTemplateReqV1: + v2.InstanceResV2: properties: - approved_by_authorized: - type: boolean - assignee_user_name_list: + additional_params: items: - type: string + $ref: '#/definitions/v1.InstanceAdditionalParamResV1' type: array + db_host: + example: 10.10.10.10 + type: string + db_port: + example: "3306" + type: string + db_type: + example: mysql + type: string + db_user: + example: root + type: string desc: + example: this is a instance type: string - execute_by_authorized: - type: boolean - type: - enum: - - sql_review - - sql_execute + instance_name: type: string - type: object - v1.WorkFlowStepTemplateResV1: - properties: - approved_by_authorized: - type: boolean - assignee_user_name_list: + maintenance_times: items: - type: string + $ref: '#/definitions/v1.MaintenanceTimeResV1' type: array - desc: - type: string - execute_by_authorized: - type: boolean - number: - type: integer - type: + rule_template: + $ref: '#/definitions/v2.RuleTemplateV2' + type: object + source: + example: SQLE type: string + sql_query_config: + $ref: '#/definitions/v1.SQLQueryConfigResV1' + type: object type: object - v1.WorkflowAuditPassPercentV1: + v2.PartialSyncAuditPlanSQLsReqV2: properties: - audit_pass_percent: - type: number + audit_plan_sql_list: + items: + $ref: '#/definitions/v2.AuditPlanSQLReqV2' + type: array type: object - v1.WorkflowCountsV1: + v2.PerformanceStatistics: properties: - today_count: - type: integer - total: - type: integer + affect_rows: + $ref: '#/definitions/v2.AffectRows' + type: object type: object - v1.WorkflowCreatedCountsEachDayItem: + v2.RejectWorkflowReqV2: properties: - date: - example: "2022-08-24" + reason: type: string - value: - type: integer type: object - v1.WorkflowCreatedCountsEachDayV1: + v2.RuleTemplateV2: properties: - samples: - items: - $ref: '#/definitions/v1.WorkflowCreatedCountsEachDayItem' - type: array + is_global_rule_template: + type: boolean + name: + type: string type: object - v1.WorkflowDetailResV1: + v2.SQLExplain: properties: - create_time: + classic_result: + $ref: '#/definitions/v1.ExplainClassicResult' + type: object + err_message: type: string - create_user_name: + sql: type: string - current_step_assignee_user_name_list: + type: object + v2.SqlManage: + properties: + assignees: items: type: string type: array - current_step_type: - enum: - - sql_review - - sql_execute + audit_result: + items: + $ref: '#/definitions/v1.AuditResult' + type: array + endpoints: + items: + type: string + type: array + first_appear_timestamp: type: string - desc: + fp_count: + type: integer + id: + type: integer + instance_name: type: string - project_name: + last_receive_timestamp: type: string - status: - enum: - - wait_for_audit - - wait_for_execution - - rejected - - canceled - - exec_failed - - executing - - finished + remark: type: string - workflow_id: + schema_name: type: string - workflow_name: + source: + $ref: '#/definitions/v1.Source' + type: object + sql: + type: string + sql_fingerprint: + type: string + status: + enum: + - unhandled + - solved + - ignored + - manual_audited type: string type: object - v1.WorkflowPassPercentV1: + v2.TableMetas: properties: - audit_pass_percent: - type: number - execution_success_percent: - type: number + err_message: + type: string + table_meta_items: + items: + $ref: '#/definitions/v1.TableMeta' + type: array type: object - v1.WorkflowPercentCountedByInstanceType: + v2.TaskAnalysisDataV2: properties: - count: - type: integer - instance_type: - type: string - percent: - type: number + performance_statistics: + $ref: '#/definitions/v2.PerformanceStatistics' + type: object + sql_explain: + $ref: '#/definitions/v2.SQLExplain' + type: object + table_metas: + $ref: '#/definitions/v2.TableMetas' + type: object type: object - v1.WorkflowPercentCountedByInstanceTypeV1: + v2.UpdateWorkflowReqV2: properties: - workflow_percents: + task_ids: items: - $ref: '#/definitions/v1.WorkflowPercentCountedByInstanceType' + type: integer type: array - workflow_total_num: - type: integer type: object - v1.WorkflowRecordResV1: + v2.UpdateWorkflowScheduleReqV2: + properties: + schedule_time: + type: string + type: object + v2.WorkflowRecordResV2: properties: current_step_number: type: integer @@ -4311,34 +3628,16 @@ definitions: type: string tasks: items: - $ref: '#/definitions/v1.WorkflowTaskItem' + $ref: '#/definitions/v2.WorkflowTaskItem' type: array workflow_step_list: items: - $ref: '#/definitions/v1.WorkflowStepResV1' + $ref: '#/definitions/v2.WorkflowStepResV2' type: array type: object - v1.WorkflowRejectedPercentGroupByCreator: + v2.WorkflowResV2: properties: - creator: - type: string - rejected_percent: - type: number - workflow_total_num: - type: integer - type: object - v1.WorkflowRejectedPercentGroupByInstance: - properties: - instance_name: - type: string - rejected_percent: - type: number - workflow_total_num: - type: integer - type: object - v1.WorkflowResV1: - properties: - create_time: + create_time: type: string create_user_name: type: string @@ -4350,53 +3649,18 @@ definitions: - different_sqls type: string record: - $ref: '#/definitions/v1.WorkflowRecordResV1' + $ref: '#/definitions/v2.WorkflowRecordResV2' type: object record_history_list: items: - $ref: '#/definitions/v1.WorkflowRecordResV1' + $ref: '#/definitions/v2.WorkflowRecordResV2' type: array + workflow_id: + type: string workflow_name: type: string type: object - v1.WorkflowStageDuration: - properties: - minutes: - type: integer - type: object - v1.WorkflowStatisticsResV1: - properties: - my_need_execute_workflow_number: - type: integer - my_need_review_workflow_number: - type: integer - my_on_process_workflow_number: - type: integer - my_rejected_workflow_number: - type: integer - need_me_to_execute_workflow_number: - type: integer - need_me_to_review_workflow_number: - type: integer - type: object - v1.WorkflowStatusCountV1: - properties: - closed_count: - type: integer - executing_count: - type: integer - executing_failed_count: - type: integer - execution_success_count: - type: integer - rejected_count: - type: integer - waiting_for_audit_count: - type: integer - waiting_for_execution_count: - type: integer - type: object - v1.WorkflowStepResV1: + v2.WorkflowStepResV2: properties: assignee_user_name_list: items: @@ -4420,2034 +3684,106 @@ definitions: type: string type: enum: - - create_workflow - - update_workflow - - sql_review - - sql_execute - type: string - workflow_step_id: - type: integer - type: object - v1.WorkflowTaskItem: - properties: - task_id: - type: integer - type: object - v1.WorkflowTemplateDetailResV1: - properties: - allow_submit_when_less_audit_level: - enum: - - normal - - notice - - warn - - error - type: string - desc: - type: string - instance_name_list: - items: - type: string - type: array - workflow_step_template_list: - items: - $ref: '#/definitions/v1.WorkFlowStepTemplateResV1' - type: array - workflow_template_name: - type: string - type: object - v2.AffectRows: - properties: - count: - type: integer - err_message: - type: string - type: object - v2.AuditPlanReportSQLResV2: - properties: - audit_plan_report_sql: - example: select * from t1 where id = 1 - type: string - audit_plan_report_sql_audit_result: - items: - $ref: '#/definitions/v2.AuditResult' - type: array - number: - example: 1 - type: integer - type: object - v2.AuditPlanResV2: - properties: - audit_plan_cron: - example: 0 */2 * * * - type: string - audit_plan_db_type: - example: mysql - type: string - audit_plan_instance_database: - example: app1 - type: string - audit_plan_instance_name: - example: test_mysql - type: string - audit_plan_meta: - $ref: '#/definitions/v1.AuditPlanMetaV1' - type: object - audit_plan_name: - example: audit_for_java_app1 - type: string - audit_plan_token: - example: it's a JWT Token for scanner - type: string - rule_template: - $ref: '#/definitions/v2.RuleTemplateV2' - type: object - type: object - v2.AuditPlanSQLReqV2: - properties: - audit_plan_sql_counter: - example: "6" - type: string - audit_plan_sql_fingerprint: - example: select * from t1 where id = ? - type: string - audit_plan_sql_last_receive_text: - example: select * from t1 where id = 1 - type: string - audit_plan_sql_last_receive_timestamp: - example: RFC3339 - type: string - audit_plan_sql_schema: - example: db1 - type: string - db_user: - example: database_user001 - type: string - endpoints: - items: - type: string - type: array - first_query_at: - example: "2023-09-12T02:48:01.317880Z" - type: string - query_time_avg: - example: 3.22 - type: number - query_time_max: - example: 5.22 - type: number - type: object - v2.AuditResDataV2: - properties: - audit_level: - enum: - - normal - - notice - - warn - - error - - "" - type: string - pass_rate: - type: number - score: - type: integer - sql_results: - items: - $ref: '#/definitions/v2.AuditSQLResV2' - type: array - type: object - v2.AuditResult: - properties: - db_type: - type: string - level: - example: warn - type: string - message: - example: 避免使用不必要的内置函数md5() - type: string - rule_name: - type: string - type: object - v2.AuditSQLResV2: - properties: - audit_level: - type: string - audit_result: - items: - $ref: '#/definitions/v2.AuditResult' - type: array - exec_sql: - type: string - number: - type: integer - type: object - v2.AuditTaskSQLResV2: - properties: - audit_level: - type: string - audit_result: - items: - $ref: '#/definitions/v2.AuditResult' - type: array - audit_status: - type: string - description: - type: string - exec_result: - type: string - exec_sql: - type: string - exec_status: - type: string - number: - type: integer - rollback_sql: - type: string - type: object - v2.BatchCancelWorkflowsReqV2: - properties: - workflow_id_list: - items: - type: string - type: array - type: object - v2.BatchCompleteWorkflowsReqV2: - properties: - workflow_id_list: - items: - type: string - type: array - type: object - v2.CreateInstanceReqV2: - properties: - additional_params: - items: - $ref: '#/definitions/v1.InstanceAdditionalParamReqV1' - type: array - db_host: - example: 10.10.10.10 - type: string - db_password: - example: "123456" - type: string - db_port: - example: "3306" - type: string - db_type: - example: mysql - type: string - db_user: - example: root - type: string - desc: - example: this is a test instance - type: string - instance_name: - example: test - type: string - maintenance_times: - items: - $ref: '#/definitions/v1.MaintenanceTimeReqV1' - type: array - rule_template_name: - type: string - sql_query_config: - $ref: '#/definitions/v1.SQLQueryConfigReqV1' - type: object - type: object - v2.CreateWorkflowReqV2: - properties: - desc: - type: string - task_ids: - items: - type: integer - type: array - workflow_subject: - type: string - type: object - v2.CreateWorkflowResV2: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v2.CreateWorkflowResV2Data' - type: object - message: - example: ok - type: string - type: object - v2.CreateWorkflowResV2Data: - properties: - workflow_id: - type: string - type: object - v2.DirectAuditFileReqV2: - properties: - file_contents: - description: |- - 调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现 - 每个数组元素是一个文件内容 - example: - - select * from t1; select * from t2; - items: - type: string - type: array - instance_name: - example: instance1 - type: string - instance_type: - example: MySQL - type: string - project_name: - example: project1 - type: string - schema_name: - example: schema1 - type: string - sql_type: - enum: - - sql - - mybatis - - "" - example: sql - type: string - type: object - v2.DirectAuditReqV2: - properties: - instance_type: - example: MySQL - type: string - sql_content: - description: 调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现 - example: select * from t1; select * from t2; - type: string - sql_type: - enum: - - sql - - mybatis - - "" - example: sql - type: string - type: object - v2.DirectAuditResV2: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v2.AuditResDataV2' - type: object - message: - example: ok - type: string - type: object - v2.DriverMeta: - properties: - default_port: - type: integer - driver_name: - type: string - logo_url: - type: string - type: object - v2.FullSyncAuditPlanSQLsReqV2: - properties: - audit_plan_sql_list: - items: - $ref: '#/definitions/v2.AuditPlanSQLReqV2' - type: array - type: object - v2.GetAuditPlanAnalysisDataResV2: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v2.TaskAnalysisDataV2' - type: object - message: - example: ok - type: string - type: object - v2.GetAuditPlanReportSQLsResV2: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v2.AuditPlanReportSQLResV2' - type: array - message: - example: ok - type: string - total_nums: - type: integer - type: object - v2.GetAuditPlansResV2: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v2.AuditPlanResV2' - type: array - message: - example: ok - type: string - total_nums: - type: integer - type: object - v2.GetAuditTaskSQLsResV2: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v2.AuditTaskSQLResV2' - type: array - message: - example: ok - type: string - total_nums: - type: integer - type: object - v2.GetDriversRes: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v2.DriverMeta' - type: array - message: - example: ok - type: string - type: object - v2.GetInstanceResV2: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v2.InstanceResV2' - type: object - message: - example: ok - type: string - type: object - v2.GetInstancesResV2: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v2.InstanceResV2' - type: array - message: - example: ok - type: string - total_nums: - type: integer - type: object - v2.GetSqlManageListResp: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v2.SqlManage' - type: array - message: - example: ok - type: string - sql_manage_bad_num: - type: integer - sql_manage_optimized_num: - type: integer - sql_manage_total_num: - type: integer - type: object - v2.GetTaskAnalysisDataResV2: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v2.TaskAnalysisDataV2' - type: object - message: - example: ok - type: string - type: object - v2.GetWorkflowResV2: - properties: - code: - example: 0 - type: integer - data: - $ref: '#/definitions/v2.WorkflowResV2' - type: object - message: - example: ok - type: string - type: object - v2.GetWorkflowTasksItemV2: - properties: - current_step_assignee_user_name_list: - items: - type: string - type: array - exec_end_time: - type: string - exec_start_time: - type: string - execution_user_name: - type: string - instance_maintenance_times: - items: - $ref: '#/definitions/v1.MaintenanceTimeResV1' - type: array - instance_name: - type: string - schedule_time: - type: string - status: - enum: - - wait_for_audit - - wait_for_execution - - exec_scheduled - - exec_failed - - exec_succeeded - - executing - - manually_executed - - terminating - - terminate_succeeded - - terminate_failed - type: string - task_id: - type: integer - task_pass_rate: - type: number - task_score: - type: integer - type: object - v2.GetWorkflowTasksResV2: - properties: - code: - example: 0 - type: integer - data: - items: - $ref: '#/definitions/v2.GetWorkflowTasksItemV2' - type: array - message: - example: ok - type: string - type: object - v2.InstanceResV2: - properties: - additional_params: - items: - $ref: '#/definitions/v1.InstanceAdditionalParamResV1' - type: array - db_host: - example: 10.10.10.10 - type: string - db_port: - example: "3306" - type: string - db_type: - example: mysql - type: string - db_user: - example: root - type: string - desc: - example: this is a instance - type: string - instance_name: - type: string - maintenance_times: - items: - $ref: '#/definitions/v1.MaintenanceTimeResV1' - type: array - rule_template: - $ref: '#/definitions/v2.RuleTemplateV2' - type: object - source: - example: SQLE - type: string - sql_query_config: - $ref: '#/definitions/v1.SQLQueryConfigResV1' - type: object - type: object - v2.PartialSyncAuditPlanSQLsReqV2: - properties: - audit_plan_sql_list: - items: - $ref: '#/definitions/v2.AuditPlanSQLReqV2' - type: array - type: object - v2.PerformanceStatistics: - properties: - affect_rows: - $ref: '#/definitions/v2.AffectRows' - type: object - type: object - v2.RejectWorkflowReqV2: - properties: - reason: - type: string - type: object - v2.RuleTemplateV2: - properties: - is_global_rule_template: - type: boolean - name: - type: string - type: object - v2.SQLExplain: - properties: - classic_result: - $ref: '#/definitions/v1.ExplainClassicResult' - type: object - err_message: - type: string - sql: - type: string - type: object - v2.SqlManage: - properties: - assignees: - items: - type: string - type: array - audit_result: - items: - $ref: '#/definitions/v1.AuditResult' - type: array - endpoints: - items: - type: string - type: array - first_appear_timestamp: - type: string - fp_count: - type: integer - id: - type: integer - instance_name: - type: string - last_receive_timestamp: - type: string - remark: - type: string - schema_name: - type: string - source: - $ref: '#/definitions/v1.Source' - type: object - sql: - type: string - sql_fingerprint: - type: string - status: - enum: - - unhandled - - solved - - ignored - - manual_audited - type: string - type: object - v2.TableMetas: - properties: - err_message: - type: string - table_meta_items: - items: - $ref: '#/definitions/v1.TableMeta' - type: array - type: object - v2.TaskAnalysisDataV2: - properties: - performance_statistics: - $ref: '#/definitions/v2.PerformanceStatistics' - type: object - sql_explain: - $ref: '#/definitions/v2.SQLExplain' - type: object - table_metas: - $ref: '#/definitions/v2.TableMetas' - type: object - type: object - v2.UpdateWorkflowReqV2: - properties: - task_ids: - items: - type: integer - type: array - type: object - v2.UpdateWorkflowScheduleReqV2: - properties: - schedule_time: - type: string - type: object - v2.WorkflowRecordResV2: - properties: - current_step_number: - type: integer - status: - enum: - - wait_for_audit - - wait_for_execution - - rejected - - canceled - - exec_failed - - executing - - finished - type: string - tasks: - items: - $ref: '#/definitions/v2.WorkflowTaskItem' - type: array - workflow_step_list: - items: - $ref: '#/definitions/v2.WorkflowStepResV2' - type: array - type: object - v2.WorkflowResV2: - properties: - create_time: - type: string - create_user_name: - type: string - desc: - type: string - mode: - enum: - - same_sqls - - different_sqls - type: string - record: - $ref: '#/definitions/v2.WorkflowRecordResV2' - type: object - record_history_list: - items: - $ref: '#/definitions/v2.WorkflowRecordResV2' - type: array - workflow_id: - type: string - workflow_name: - type: string - type: object - v2.WorkflowStepResV2: - properties: - assignee_user_name_list: - items: - type: string - type: array - desc: - type: string - number: - type: integer - operation_time: - type: string - operation_user_name: - type: string - reason: - type: string - state: - enum: - - initialized - - approved - - rejected - type: string - type: - enum: - - create_workflow - - update_workflow - - sql_review - - sql_execute - type: string - workflow_step_id: - type: integer - type: object - v2.WorkflowTaskItem: - properties: - task_id: - type: integer - type: object -info: - contact: {} - description: This is a sample server for dev. - license: {} - title: Sqle API Docs - version: "1.0" -paths: - /v1/audit_files: - post: - description: Direct audit sql from SQL files and MyBatis files - operationId: directAuditFilesV1 - parameters: - - description: files that should be audited - in: body - name: req - required: true - schema: - $ref: '#/definitions/v1.DirectAuditFileReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.DirectAuditResV1' - security: - - ApiKeyAuth: [] - summary: 直接从文件内容提取SQL并审核,SQL文件暂时只支持一次解析一个文件 - tags: - - sql_audit - /v1/audit_plan_metas: - get: - description: get audit plan metas - operationId: getAuditPlanMetasV1 - parameters: - - description: filter instance type - in: query - name: filter_instance_type - type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetAuditPlanMetasResV1' - security: - - ApiKeyAuth: [] - summary: 获取扫描任务元信息 - tags: - - audit_plan - /v1/audit_plan_types: - get: - description: get audit plan types - operationId: getAuditPlanTypesV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetAuditPlanTypesResV1' - security: - - ApiKeyAuth: [] - summary: 获取扫描任务类型 - tags: - - audit_plan - /v1/basic_info: - get: - description: get sqle basic info - operationId: getSQLEInfoV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetSQLEInfoResV1' - summary: 获取 sqle 基本信息 - tags: - - global - /v1/company_notice: - get: - description: get company notice info - operationId: getCompanyNotice - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetCompanyNoticeResp' - security: - - ApiKeyAuth: [] - summary: 获取企业公告 - tags: - - companyNotice - patch: - consumes: - - application/json - description: update company notice info - operationId: updateCompanyNotice - parameters: - - description: company notice - in: body - name: companyNotice - required: true - schema: - $ref: '#/definitions/v1.UpdateCompanyNoticeReq' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 更新企业公告 - tags: - - companyNotice - /v1/configurations/ding_talk: - get: - description: get dingTalk configuration - operationId: getDingTalkConfigurationV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetDingTalkConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 获取 dingTalk 配置 - tags: - - configuration - patch: - consumes: - - application/json - description: update DingTalk configuration - operationId: updateDingTalkConfigurationV1 - parameters: - - description: update DingTalk configuration req - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateDingTalkConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加或更新 DingTalk 配置 - tags: - - configuration - /v1/configurations/ding_talk/test: - post: - consumes: - - application/json - description: test DingTalk configuration - operationId: testDingTalkConfigV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.TestDingTalkConfigResV1' - security: - - ApiKeyAuth: [] - summary: 测试 DingTalk 配置 - tags: - - configuration - /v1/configurations/drivers: - get: - description: get drivers - operationId: getDriversV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetDriversResV1' - security: - - ApiKeyAuth: [] - summary: 获取当前 server 支持的审核类型 - tags: - - configuration - /v1/configurations/feishu: - get: - description: get feishu configuration - operationId: getFeishuConfigurationV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetFeishuConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 获取飞书配置 - tags: - - configuration - patch: - consumes: - - application/json - description: update feishu configuration - operationId: updateFeishuConfigurationV1 - parameters: - - description: update feishu configuration req - in: body - name: param - required: true - schema: - $ref: '#/definitions/v1.UpdateFeishuConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加或更新飞书配置 - tags: - - configuration - /v1/configurations/feishu/test: - post: - consumes: - - application/json - description: test feishu configuration - operationId: testFeishuConfigV1 - parameters: - - description: test feishu configuration req - in: body - name: req - required: true - schema: - $ref: '#/definitions/v1.TestFeishuConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.TestFeishuConfigResV1' - security: - - ApiKeyAuth: [] - summary: 测试飞书配置 - tags: - - configuration - /v1/configurations/feishu_audit: - get: - description: get feishu audit configuration - operationId: getFeishuAuditConfigurationV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetFeishuAuditConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 获取飞书审核配置 - tags: - - configuration - patch: - consumes: - - application/json - description: update feishu audit configuration - operationId: updateFeishuAuditConfigurationV1 - parameters: - - description: update feishu audit configuration req - in: body - name: param - required: true - schema: - $ref: '#/definitions/v1.UpdateFeishuConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加或更新飞书配置 - tags: - - configuration - /v1/configurations/feishu_audit/test: - post: - consumes: - - application/json - description: test feishu audit configuration - operationId: testFeishuAuditConfigV1 - parameters: - - description: test feishu configuration req - in: body - name: req - required: true - schema: - $ref: '#/definitions/v1.TestFeishuConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.TestFeishuConfigResV1' - security: - - ApiKeyAuth: [] - summary: 测试飞书审批配置 - tags: - - configuration - /v1/configurations/ldap: - get: - description: get LDAP configuration - operationId: getLDAPConfigurationV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetLDAPConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 获取 LDAP 配置 - tags: - - configuration - patch: - consumes: - - application/json - description: update LDAP configuration - operationId: updateLDAPConfigurationV1 - parameters: - - description: update LDAP configuration req - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.LDAPConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加 LDAP 配置 - tags: - - configuration - /v1/configurations/license: - get: - description: get sqle license - operationId: getSQLELicenseV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetLicenseResV1' - security: - - ApiKeyAuth: [] - summary: 获取 sqle license - tags: - - configuration - post: - consumes: - - multipart/form-data - description: set sqle license - operationId: setSQLELicenseV1 - parameters: - - description: SQLE license file - in: formData - name: license_file - required: true - type: file - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 导入 sqle license - tags: - - configuration - /v1/configurations/license/check: - post: - consumes: - - multipart/form-data - description: parse and check sqle license - operationId: checkSQLELicenseV1 - parameters: - - description: SQLE license file - in: formData - name: license_file - required: true - type: file - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.CheckLicenseResV1' - security: - - ApiKeyAuth: [] - summary: 解析和校验 sqle license - tags: - - configuration - /v1/configurations/license/info: - get: - description: get the information needed to generate the sqle license - operationId: GetSQLELicenseInfoV1 - responses: - "200": - description: server info - schema: - type: file - security: - - ApiKeyAuth: [] - summary: 获取生成 sqle license需要的的信息 - tags: - - configuration - /v1/configurations/oauth2: - get: - description: get Oauth2 configuration - operationId: getOauth2ConfigurationV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetOauth2ConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 获取 Oauth2 配置 - tags: - - configuration - patch: - consumes: - - application/json - description: update Oauth2 configuration - operationId: updateOauth2ConfigurationV1 - parameters: - - description: update Oauth2 configuration req - in: body - name: conf - required: true - schema: - $ref: '#/definitions/v1.Oauth2ConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 修改 Oauth2 配置 - tags: - - configuration - /v1/configurations/oauth2/tips: - get: - description: get Oauth2 tips - operationId: getOauth2Tips - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetOauth2TipsResV1' - summary: 获取 Oauth2 基本信息 - tags: - - configuration - /v1/configurations/personalise: - patch: - description: update personalise config - operationId: personalise - parameters: - - description: personalise req - in: body - name: conf - required: true - schema: - $ref: '#/definitions/v1.PersonaliseReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 更新个性化设置 - tags: - - configuration - /v1/configurations/personalise/logo: - post: - consumes: - - multipart/form-data - description: upload logo - operationId: uploadLogo - parameters: - - description: logo file - in: formData - name: logo - required: true - type: file - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.UploadLogoResV1' - security: - - ApiKeyAuth: [] - summary: 上传Logo - tags: - - configuration - /v1/configurations/smtp: - get: - description: get SMTP configuration - operationId: getSMTPConfigurationV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetSMTPConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 获取 SMTP 配置 - tags: - - configuration - patch: - consumes: - - application/json - description: update SMTP configuration - operationId: updateSMTPConfigurationV1 - parameters: - - description: update SMTP configuration req - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateSMTPConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加 SMTP 配置 - tags: - - configuration - /v1/configurations/smtp/test: - post: - consumes: - - application/json - description: test SMTP configuration - operationId: testSMTPConfigurationV1 - parameters: - - description: test SMTP configuration req - in: body - name: req - required: true - schema: - $ref: '#/definitions/v1.TestSMTPConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.TestSMTPConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 测试 邮箱 配置 - tags: - - configuration - /v1/configurations/sql_query: - get: - description: get sqle query configuration - operationId: getSQLQueryConfiguration - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetSQLQueryConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 获取SQL查询配置信息 - tags: - - configuration - /v1/configurations/system_variables: - get: - description: get system variables - operationId: getSystemVariablesV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetSystemVariablesResV1' - security: - - ApiKeyAuth: [] - summary: 获取系统变量 - tags: - - configuration - patch: - consumes: - - application/json - description: update system variables - operationId: updateSystemVariablesV1 - parameters: - - description: update system variables request - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateSystemVariablesReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 修改系统变量 - tags: - - configuration - /v1/configurations/webhook: - get: - description: get workflow webhook config - operationId: getGlobalWorkflowWebHookConfig - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetWorkflowWebHookConfigResV1' - security: - - ApiKeyAuth: [] - summary: 获取全局工单 WebHook 配置 - tags: - - configuration - patch: - description: update webhook config - operationId: updateGlobalWebHookConfig - parameters: - - description: update webhook config - in: body - name: request - required: true - schema: - $ref: '#/definitions/v1.WebHookConfigV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 更新工单 WebHook 配置 - tags: - - configuration - /v1/configurations/webhook/test: - post: - description: test workflow webhook config - operationId: testGlobalWorkflowWebHookConfig - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.TestWorkflowWebHookConfigResV1' - security: - - ApiKeyAuth: [] - summary: 测试全局工单 WebHook 配置 - tags: - - configuration - /v1/configurations/wechat: - get: - description: get WeChat configuration - operationId: getWeChatConfigurationV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetWeChatConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 获取 企业微信 配置 - tags: - - configuration - patch: - consumes: - - application/json - description: update WeChat configuration - operationId: updateWeChatConfigurationV1 - parameters: - - description: update WeChat configuration req - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateWeChatConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加 企业微信 配置 - tags: - - configuration - /v1/configurations/wechat/test: - post: - consumes: - - application/json - description: test WeChat configuration - operationId: testWeChatConfigurationV1 - parameters: - - description: test WeChat configuration req - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.TestWeChatConfigurationReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.TestWeChatConfigurationResV1' - security: - - ApiKeyAuth: [] - summary: 测试 企业微信 配置 - tags: - - configuration - /v1/custom_rules: - get: - description: get all custom rule template - operationId: getCustomRulesV1 - parameters: - - description: filter db type - in: query - name: filter_db_type - type: string - - description: filter desc - in: query - name: filter_desc - type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetCustomRulesResV1' - security: - - ApiKeyAuth: [] - summary: 自定义规则列表 - tags: - - rule_template - post: - description: create custom rule - operationId: createCustomRuleV1 - parameters: - - description: add custom rule - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.CreateCustomRuleReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加自定义规则 - tags: - - rule_template - /v1/custom_rules/{db_type}/rule_types: - get: - description: get rule type by db type - operationId: getRuleTypeByDBTypeV1 - parameters: - - description: db type - in: query - name: db_type - required: true - type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetRuleTypeByDBTypeResV1' - security: - - ApiKeyAuth: [] - summary: 获取规则分类 - tags: - - rule_template - /v1/custom_rules/{rule_id}: - delete: - description: delete custom rule - operationId: deleteCustomRuleV1 - parameters: - - description: rule id - in: path - name: rule_id - required: true - type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 删除自定义规则 - tags: - - rule_template - get: - description: get custom rule by rule_id - operationId: getCustomRuleV1 - parameters: - - description: rule id - in: path - name: rule_id - required: true - type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetCustomRuleResV1' - security: - - ApiKeyAuth: [] - summary: 获取自定义规则 - tags: - - rule_template - patch: - description: update custom rule - operationId: updateCustomRuleV1 - parameters: - - description: rule id - in: path - name: rule_id - required: true - type: string - - description: update custom rule - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateCustomRuleReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 更新自定义规则 - tags: - - rule_template - /v1/dashboard: - get: - description: get dashboard info - operationId: getDashboardV1 - parameters: - - description: filter project name - in: query - name: filter_project_name - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetDashboardResV1' - security: - - ApiKeyAuth: [] - summary: 获取 dashboard 信息 - tags: - - dashboard - /v1/dashboard/project_tips: - get: - description: get dashboard project tips - operationId: getDashboardProjectTipsV1 - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetDashboardProjectTipsResV1' - security: - - ApiKeyAuth: [] - summary: 获取dashboard项目提示列表 - tags: - - dashboard - /v1/instance_additional_metas: - get: - description: get instance additional metas - operationId: getInstanceAdditionalMetas - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetInstanceAdditionalMetasResV1' - security: - - ApiKeyAuth: [] - summary: 获取实例的额外属性列表 - tags: - - instance - /v1/instance_connection: - post: - consumes: - - application/json - description: test instance db connection 注:可直接提交创建实例接口的body,该接口的json 内容是创建实例的 - json 的子集 - operationId: checkInstanceIsConnectableV1 - parameters: - - description: instance info - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.GetInstanceConnectableReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetInstanceConnectableResV1' - security: - - ApiKeyAuth: [] - summary: 实例连通性测试(实例提交前) - tags: - - instance - /v1/login: - post: - description: user login - operationId: loginV1 - parameters: - - description: user login request - in: body - name: user - required: true - schema: - $ref: '#/definitions/v1.UserLoginReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetUserLoginResV1' - summary: 用户登录 - tags: - - user - /v1/logout: - post: - description: user logout - operationId: logoutV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - summary: 用户登出 - tags: - - user - /v1/management_permissions: - get: - description: get platform management permissions - operationId: GetManagementPermissionsV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetManagementPermissionsResV1' - security: - - ApiKeyAuth: [] - summary: 获取平台管理权限列表 - tags: - - management_permission - /v1/oauth2/link: - get: - description: oauth2 link - operationId: Oauth2Link - summary: oauth2通过此链接跳转到第三方登录网址 - tags: - - oauth2 - /v1/oauth2/user/bind: - post: - description: bind Oauth2 user to sqle - operationId: bindOauth2User - parameters: - - description: bind oauth2 user req - in: body - name: conf - required: true - schema: - $ref: '#/definitions/v1.BindOauth2UserReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.BindOauth2UserResV1' - summary: 绑定 Oauth2 和 sqle用户 - tags: - - oauth2 - /v1/operation_records: - get: - description: Get operation record list - operationId: getOperationRecordListV1 - parameters: - - description: filter_operate_time_from - in: query - name: filter_operate_time_from - type: string - - description: filter_operate_time_to - in: query - name: filter_operate_time_to - type: string - - description: filter_operate_project_name - in: query - name: filter_operate_project_name - type: string - - description: fuzzy_search_operate_user_name - in: query - name: fuzzy_search_operate_user_name - type: string - - description: filter_operate_type_name - in: query - name: filter_operate_type_name - type: string - - description: filter_operate_action - in: query - name: filter_operate_action - type: string - - description: page_index - in: query - name: page_index - required: true - type: integer - - description: page_size - in: query - name: page_size - required: true - type: integer - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetOperationRecordListResV1' - security: - - ApiKeyAuth: [] - summary: 获取操作记录列表 - tags: - - OperationRecord - /v1/operation_records/exports: - get: - description: Export operation record list - operationId: getExportOperationRecordListV1 - parameters: - - description: filter_operate_time_from - in: query - name: filter_operate_time_from - type: string - - description: filter_operate_time_to - in: query - name: filter_operate_time_to - type: string - - description: filter_operate_project_name - in: query - name: filter_operate_project_name - type: string - - description: fuzzy_search_operate_user_name - in: query - name: fuzzy_search_operate_user_name - type: string - - description: filter_operate_type_name - in: query - name: filter_operate_type_name - type: string - - description: filter_operate_action - in: query - name: filter_operate_action - type: string - responses: - "200": - description: get export operation record list - schema: - type: file - security: - - ApiKeyAuth: [] - summary: 导出操作记录列表 - tags: - - OperationRecord - /v1/operation_records/operation_actions: - get: - description: Get operation action list - operationId: getOperationActionList - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetOperationActionListResV1' - security: - - ApiKeyAuth: [] - summary: 获取操作内容列表 - tags: - - OperationRecord - /v1/operation_records/operation_type_names: - get: - description: Get operation type name list - operationId: GetOperationTypeNameList - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetOperationTypeNamesListResV1' - security: - - ApiKeyAuth: [] - summary: 获取操作类型名列表 - tags: - - OperationRecord - /v1/operations: - get: - description: get permission operations - operationId: GetOperationsV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetOperationsResV1' - security: - - ApiKeyAuth: [] - summary: 获取权限动作列表 - tags: - - operation - /v1/project_tips: - get: - description: get project tip list - operationId: getProjectTipsV1 - parameters: - - description: functional module - enum: - - operation_record - in: query - name: functional_module + - create_workflow + - update_workflow + - sql_review + - sql_execute type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetProjectTipsResV1' - security: - - ApiKeyAuth: [] - summary: 获取项目提示列表 - tags: - - project - /v1/projects: - get: - description: get project list - operationId: getProjectListV1 - parameters: - - description: page index - in: query - name: page_index - required: true + workflow_step_id: type: integer - - default: 50 - description: size of per page - in: query - name: page_size - required: true + type: object + v2.WorkflowTaskItem: + properties: + task_id: type: integer - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetProjectResV1' - security: - - ApiKeyAuth: [] - summary: 获取项目列表 - tags: - - project + type: object +info: + contact: {} + description: This is a sample server for dev. + license: {} + title: Sqle API Docs + version: "1.0" +paths: + /v1/audit_files: post: - consumes: - - application/json - description: create project - operationId: createProjectV1 + description: Direct audit sql from SQL files and MyBatis files + operationId: directAuditFilesV1 parameters: - - description: create project request + - description: files that should be audited in: body - name: project + name: req required: true schema: - $ref: '#/definitions/v1.CreateProjectReqV1' - produces: - - application/json + $ref: '#/definitions/v1.DirectAuditFileReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.DirectAuditResV1' security: - ApiKeyAuth: [] - summary: 创建项目 + summary: 直接从文件内容提取SQL并审核,SQL文件暂时只支持一次解析一个文件 tags: - - project - /v1/projects/{project_name}/: - delete: - description: delete project - operationId: deleteProjectV1 + - sql_audit + /v1/audit_plan_metas: + get: + description: get audit plan metas + operationId: getAuditPlanMetasV1 parameters: - - description: project name - in: path - name: project_name - required: true + - description: filter instance type + in: query + name: filter_instance_type type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetAuditPlanMetasResV1' security: - ApiKeyAuth: [] - summary: 删除项目 + summary: 获取扫描任务元信息 tags: - - project + - audit_plan + /v1/audit_plan_types: get: - description: get project detail - operationId: getProjectDetailV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string + description: get audit plan types + operationId: getAuditPlanTypesV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetProjectDetailResV1' + $ref: '#/definitions/v1.GetAuditPlanTypesResV1' security: - ApiKeyAuth: [] - summary: 获取项目详情 + summary: 获取扫描任务类型 tags: - - project - patch: - consumes: - - application/json - description: update project - operationId: updateProjectV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: create project request - in: body - name: project - required: true - schema: - $ref: '#/definitions/v1.UpdateProjectReqV1' - produces: - - application/json + - audit_plan + /v1/company_notice: + get: + description: get company notice info + operationId: getCompanyNotice responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetCompanyNoticeResp' security: - ApiKeyAuth: [] - summary: 更新项目 + summary: 获取企业公告 tags: - - project - /v1/projects/{project_name}/archive: - post: + - companyNotice + patch: consumes: - application/json - description: archive project - operationId: archiveProjectV1 + description: update company notice info + operationId: updateCompanyNotice parameters: - - description: project name - in: path - name: project_name + - description: company notice + in: body + name: companyNotice required: true - type: string + schema: + $ref: '#/definitions/v1.UpdateCompanyNoticeReq' produces: - application/json responses: @@ -6457,97 +3793,35 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 归档项目 + summary: 更新企业公告 tags: - - project - /v1/projects/{project_name}/audit_plans: + - companyNotice + /v1/configurations/ding_talk: get: - description: get audit plan info list - operationId: getAuditPlansV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: filter audit plan db type - in: query - name: filter_audit_plan_db_type - type: string - - description: fuzzy search audit plan name - in: query - name: fuzzy_search_audit_plan_name - type: string - - description: filter audit plan type - in: query - name: filter_audit_plan_type - type: string - - description: filter audit plan instance name - in: query - name: filter_audit_plan_instance_name - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size - required: true - type: integer + description: get dingTalk configuration + operationId: getDingTalkConfigurationV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditPlansResV1' + $ref: '#/definitions/v1.GetDingTalkConfigurationResV1' security: - ApiKeyAuth: [] - summary: 获取扫描任务信息列表 + summary: 获取 dingTalk 配置 tags: - - audit_plan - post: + - configuration + patch: consumes: - application/json - description: create audit plan - operationId: createAuditPlanV1 + description: update DingTalk configuration + operationId: updateDingTalkConfigurationV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: create audit plan + - description: update DingTalk configuration req in: body - name: audit_plan + name: instance required: true schema: - $ref: '#/definitions/v1.CreateAuditPlanReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加扫描任务 - tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/: - delete: - description: delete audit plan - operationId: deleteAuditPlanV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string + $ref: '#/definitions/v1.UpdateDingTalkConfigurationReqV1' responses: "200": description: OK @@ -6555,108 +3829,65 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 删除扫描任务 + summary: 添加或更新 DingTalk 配置 tags: - - audit_plan - get: - description: get audit plan - operationId: getAuditPlanV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string + - configuration + /v1/configurations/ding_talk/test: + post: + consumes: + - application/json + description: test DingTalk configuration + operationId: testDingTalkConfigV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditPlanResV1' + $ref: '#/definitions/v1.TestDingTalkConfigResV1' security: - ApiKeyAuth: [] - summary: 获取指定扫描任务 - tags: - - audit_plan - patch: - description: update audit plan - operationId: updateAuditPlanV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: update audit plan - in: body - name: audit_plan - required: true - schema: - $ref: '#/definitions/v1.UpdateAuditPlanReqV1' + summary: 测试 DingTalk 配置 + tags: + - configuration + /v1/configurations/drivers: + get: + description: get drivers + operationId: getDriversV1 responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetDriversResV1' security: - ApiKeyAuth: [] - summary: 更新扫描任务 + summary: 获取当前 server 支持的审核类型 tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config: + - configuration + /v1/configurations/feishu_audit: get: - description: get audit plan notify config - operationId: getAuditPlanNotifyConfigV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string + description: get feishu audit configuration + operationId: getFeishuAuditConfigurationV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditPlanNotifyConfigResV1' + $ref: '#/definitions/v1.GetFeishuAuditConfigurationResV1' security: - ApiKeyAuth: [] - summary: 获取扫描任务消息推送设置 + summary: 获取飞书审核配置 tags: - - audit_plan + - configuration patch: - description: update audit plan notify config - operationId: updateAuditPlanNotifyConfigV1 + consumes: + - application/json + description: update feishu audit configuration + operationId: updateFeishuAuditConfigurationV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: update audit plan notify config + - description: update feishu audit configuration req in: body - name: config + name: param required: true schema: - $ref: '#/definitions/v1.UpdateAuditPlanNotifyConfigReqV1' + $ref: '#/definitions/v1.UpdateFeishuConfigurationReqV1' responses: "200": description: OK @@ -6664,261 +3895,129 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 更新扫描任务通知设置 + summary: 添加或更新飞书配置 tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config/test: - get: - description: Test audit task message push - operationId: testAuditPlanNotifyConfigV1 + - configuration + /v1/configurations/feishu_audit/test: + post: + consumes: + - application/json + description: test feishu audit configuration + operationId: testFeishuAuditConfigV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name + - description: test feishu configuration req + in: body + name: req required: true - type: string + schema: + $ref: '#/definitions/v1.TestFeishuConfigurationReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.TestAuditPlanNotifyConfigResV1' + $ref: '#/definitions/v1.TestFeishuConfigResV1' security: - ApiKeyAuth: [] - summary: 测试扫描任务消息推送 + summary: 测试飞书审批配置 tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports: + - configuration + /v1/configurations/license: get: - description: get audit plan report list - operationId: getAuditPlanReportsV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size - required: true - type: integer + description: get sqle license + operationId: getSQLELicenseV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditPlanReportsResV1' + $ref: '#/definitions/v1.GetLicenseResV1' security: - ApiKeyAuth: [] - summary: 获取指定扫描任务的报告列表 + summary: 获取 sqle license tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/: - get: - description: get audit plan report - operationId: getAuditPlanReportV1 + - configuration + post: + consumes: + - multipart/form-data + description: set sqle license + operationId: setSQLELicenseV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: audit plan report id - in: path - name: audit_plan_report_id + - description: SQLE license file + in: formData + name: license_file required: true - type: string + type: file responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditPlanReportResV1' - security: - - ApiKeyAuth: [] - summary: 获取指定扫描任务的SQL扫描记录统计信息 - tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/export: - get: - description: export audit plan report as csv - operationId: exportAuditPlanReportV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: audit plan report id - in: path - name: audit_plan_report_id - required: true - type: string - responses: - "200": - description: get export audit plan report - schema: - type: file + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 以csv的形式导出扫描报告 + summary: 导入 sqle license tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls: - get: - description: get audit plan report SQLs - operationId: getAuditPlanReportsSQLsV1 + - configuration + /v1/configurations/license/check: + post: + consumes: + - multipart/form-data + description: parse and check sqle license + operationId: checkSQLELicenseV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: audit plan report id - in: path - name: audit_plan_report_id - required: true - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size + - description: SQLE license file + in: formData + name: license_file required: true - type: integer + type: file responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditPlanReportSQLsResV1' + $ref: '#/definitions/v1.CheckLicenseResV1' security: - ApiKeyAuth: [] - summary: 获取指定扫描任务的SQL扫描详情 - tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis: - get: - description: get SQL explain and related table metadata for analysis - operationId: getTaskAnalysisData - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: audit plan report id - in: path - name: audit_plan_report_id - required: true - type: string - - description: sql number - in: path - name: number - required: true - type: string + summary: 解析和校验 sqle license + tags: + - configuration + /v1/configurations/license/info: + get: + description: get the information needed to generate the sqle license + operationId: GetSQLELicenseInfoV1 responses: "200": - description: OK + description: server info schema: - $ref: '#/definitions/v1.GetAuditPlanAnalysisDataResV1' + type: file security: - ApiKeyAuth: [] - summary: 获取task相关的SQL执行计划和表元数据 + summary: 获取生成 sqle license需要的的信息 tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls: + - configuration + /v1/configurations/system_variables: get: - description: get audit plan SQLs - operationId: getAuditPlanSQLsV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size - required: true - type: integer + description: get system variables + operationId: getSystemVariablesV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditPlanSQLsResV1' + $ref: '#/definitions/v1.GetSystemVariablesResV1' security: - ApiKeyAuth: [] - summary: 获取指定扫描任务的SQLs信息(不包括扫描结果) + summary: 获取系统变量 tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full: - post: - deprecated: true - description: full sync audit plan SQLs - operationId: fullSyncAuditPlanSQLsV1 + - configuration + patch: + consumes: + - application/json + description: update system variables + operationId: updateSystemVariablesV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true - type: string - - description: full sync audit plan SQLs request + - description: update system variables request in: body - name: sqls + name: instance required: true schema: - $ref: '#/definitions/v1.FullSyncAuditPlanSQLsReqV1' + $ref: '#/definitions/v1.UpdateSystemVariablesReqV1' responses: "200": description: OK @@ -6926,113 +4025,82 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 全量同步SQL到扫描任务 + summary: 修改系统变量 tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial: - post: - deprecated: true - description: partial sync audit plan SQLs - operationId: partialSyncAuditPlanSQLsV1 + - configuration + /v1/custom_rules: + get: + description: get all custom rule template + operationId: getCustomRulesV1 parameters: - - description: project name - in: path - name: project_name - required: true + - description: filter db type + in: query + name: filter_db_type type: string - - description: audit plan name - in: path - name: audit_plan_name - required: true + - description: filter desc + in: query + name: filter_desc type: string - - description: partial sync audit plan SQLs request - in: body - name: sqls - required: true - schema: - $ref: '#/definitions/v1.PartialSyncAuditPlanSQLsReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetCustomRulesResV1' security: - ApiKeyAuth: [] - summary: 增量同步SQL到扫描任务 + summary: 自定义规则列表 tags: - - audit_plan - /v1/projects/{project_name}/audit_plans/{audit_plan_name}/trigger: + - rule_template post: - description: trigger audit plan - operationId: triggerAuditPlanV1 + description: create custom rule + operationId: createCustomRuleV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit plan name - in: path - name: audit_plan_name + - description: add custom rule + in: body + name: instance required: true - type: string + schema: + $ref: '#/definitions/v1.CreateCustomRuleReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.TriggerAuditPlanResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 触发扫描任务 + summary: 添加自定义规则 tags: - - audit_plan - /v1/projects/{project_name}/audit_whitelist: + - rule_template + /v1/custom_rules/{db_type}/rule_types: get: - description: get all whitelist - operationId: getAuditWhitelistV1 + description: get rule type by db type + operationId: getRuleTypeByDBTypeV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: page index - in: query - name: page_index - required: true - type: string - - description: page size + - description: db type in: query - name: page_size + name: db_type required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditWhitelistResV1' + $ref: '#/definitions/v1.GetRuleTypeByDBTypeResV1' security: - ApiKeyAuth: [] - summary: 获取Sql审核白名单 + summary: 获取规则分类 tags: - - audit_whitelist - post: - consumes: - - application/json - description: create a sql whitelist - operationId: createAuditWhitelistV1 + - rule_template + /v1/custom_rules/{rule_id}: + delete: + description: delete custom rule + operationId: deleteCustomRuleV1 parameters: - - description: project name + - description: rule id in: path - name: project_name + name: rule_id required: true type: string - - description: add sql whitelist req - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.CreateAuditWhitelistReqV1' responses: "200": description: OK @@ -7040,56 +4108,43 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 添加SQL白名单 + summary: 删除自定义规则 tags: - - audit_whitelist - /v1/projects/{project_name}/audit_whitelist/{audit_whitelist_id}/: - delete: - description: remove sql white - operationId: deleteAuditWhitelistByIdV1 + - rule_template + get: + description: get custom rule by rule_id + operationId: getCustomRuleV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: audit whitelist id + - description: rule id in: path - name: audit_whitelist_id + name: rule_id required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetCustomRuleResV1' security: - ApiKeyAuth: [] - summary: 删除SQL白名单信息 + summary: 获取自定义规则 tags: - - audit_whitelist + - rule_template patch: - consumes: - - application/json - description: update sql whitelist by id - operationId: UpdateAuditWhitelistByIdV1 + description: update custom rule + operationId: updateCustomRuleV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: sql audit whitelist id + - description: rule id in: path - name: audit_whitelist_id + name: rule_id required: true type: string - - description: update sql whitelist req + - description: update custom rule in: body name: instance required: true schema: - $ref: '#/definitions/v1.UpdateAuditWhitelistReqV1' + $ref: '#/definitions/v1.UpdateCustomRuleReqV1' responses: "200": description: OK @@ -7097,85 +4152,65 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 更新SQL白名单 + summary: 更新自定义规则 tags: - - audit_whitelist - /v1/projects/{project_name}/instance_tips: + - rule_template + /v1/dashboard: get: - description: get instance tip list - operationId: getInstanceTipListV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: filter db type - in: query - name: filter_db_type - type: string - - description: filter workflow template id - in: query - name: filter_workflow_template_id - type: string - - description: functional module - enum: - - create_audit_plan - - create_workflow - - sql_manage + description: get dashboard info + operationId: getDashboardV1 + parameters: + - description: filter project name in: query - name: functional_module + name: filter_project_name type: string + produces: + - application/json responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetInstanceTipsResV1' + $ref: '#/definitions/v1.GetDashboardResV1' security: - ApiKeyAuth: [] - summary: 获取实例提示列表 + summary: 获取 dashboard 信息 tags: - - instance - /v1/projects/{project_name}/instances: + - dashboard + /v1/operation_records: get: - description: get instance info list - operationId: getInstanceListV1 + description: Get operation record list + operationId: getOperationRecordListV1 parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: filter instance name + - description: filter_operate_time_from in: query - name: filter_instance_name + name: filter_operate_time_from type: string - - description: filter db type + - description: filter_operate_time_to in: query - name: filter_db_type + name: filter_operate_time_to type: string - - description: filter db host + - description: filter_operate_project_name in: query - name: filter_db_host + name: filter_operate_project_name type: string - - description: filter db port + - description: fuzzy_search_operate_user_name in: query - name: filter_db_port + name: fuzzy_search_operate_user_name type: string - - description: filter db user + - description: filter_operate_type_name in: query - name: filter_db_user + name: filter_operate_type_name type: string - - description: filter rule template name + - description: filter_operate_action in: query - name: filter_rule_template_name + name: filter_operate_action type: string - - description: page index + - description: page_index in: query name: page_index required: true type: integer - - description: size of per page + - description: page_size in: query name: page_size required: true @@ -7184,342 +4219,290 @@ paths: "200": description: OK schema: - $ref: '#/definitions/v1.GetInstancesResV1' + $ref: '#/definitions/v1.GetOperationRecordListResV1' security: - ApiKeyAuth: [] - summary: 获取实例信息列表 + summary: 获取操作记录列表 tags: - - instance - post: - consumes: - - application/json - deprecated: true - description: create a instance - operationId: createInstanceV1 + - OperationRecord + /v1/operation_records/exports: + get: + description: Export operation record list + operationId: getExportOperationRecordListV1 parameters: - - description: project name - in: path - name: project_name - required: true + - description: filter_operate_time_from + in: query + name: filter_operate_time_from type: string - - description: add instance - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.CreateInstanceReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加实例 - tags: - - instance - /v1/projects/{project_name}/instances/{instance_name}/: - delete: - description: delete instance db - operationId: deleteInstanceV1 - parameters: - - description: project name - in: path - name: project_name - required: true + - description: filter_operate_time_to + in: query + name: filter_operate_time_to type: string - - description: instance name - in: path - name: instance_name - required: true + - description: filter_operate_project_name + in: query + name: filter_operate_project_name + type: string + - description: fuzzy_search_operate_user_name + in: query + name: fuzzy_search_operate_user_name + type: string + - description: filter_operate_type_name + in: query + name: filter_operate_type_name + type: string + - description: filter_operate_action + in: query + name: filter_operate_action type: string responses: "200": - description: OK + description: get export operation record list schema: - $ref: '#/definitions/controller.BaseRes' + type: file security: - ApiKeyAuth: [] - summary: 删除实例 + summary: 导出操作记录列表 tags: - - instance + - OperationRecord + /v1/operation_records/operation_actions: get: - description: get instance db - operationId: getInstanceV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: instance name - in: path - name: instance_name - required: true - type: string + description: Get operation action list + operationId: getOperationActionList responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetInstanceResV1' + $ref: '#/definitions/v1.GetOperationActionListResV1' security: - ApiKeyAuth: [] - summary: 获取实例信息 + summary: 获取操作内容列表 tags: - - instance - patch: - description: update instance - operationId: updateInstanceV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: instance name - in: path - name: instance_name - required: true - type: string - - description: update instance request - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateInstanceReqV1' + - OperationRecord + /v1/operation_records/operation_type_names: + get: + description: Get operation type name list + operationId: GetOperationTypeNameList responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetOperationTypeNamesListResV1' security: - ApiKeyAuth: [] - summary: 更新实例 + summary: 获取操作类型名列表 tags: - - instance - /v1/projects/{project_name}/instances/{instance_name}/connection: + - OperationRecord + /v1/operations: get: - description: test instance db connection - operationId: checkInstanceIsConnectableByNameV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: instance name - in: path - name: instance_name - required: true - type: string + description: get permission operations + operationId: GetOperationsV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetInstanceConnectableResV1' + $ref: '#/definitions/v1.GetOperationsResV1' security: - ApiKeyAuth: [] - summary: 实例连通性测试(实例提交后) + summary: 获取权限动作列表 tags: - - instance - /v1/projects/{project_name}/instances/{instance_name}/rules: + - operation + /v1/projects/{project_name}/audit_plans: get: - description: get instance all rule - operationId: getInstanceRuleListV1 + description: get audit plan info list + operationId: getAuditPlansV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: instance name - in: path - name: instance_name - required: true + - description: filter audit plan db type + in: query + name: filter_audit_plan_db_type + type: string + - description: fuzzy search audit plan name + in: query + name: fuzzy_search_audit_plan_name + type: string + - description: filter audit plan type + in: query + name: filter_audit_plan_type + type: string + - description: filter audit plan instance name + in: query + name: filter_audit_plan_instance_name type: string + - description: page index + in: query + name: page_index + required: true + type: integer + - description: size of per page + in: query + name: page_size + required: true + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetRulesResV1' + $ref: '#/definitions/v1.GetAuditPlansResV1' security: - ApiKeyAuth: [] - summary: 获取实例应用的规则列表 + summary: 获取扫描任务信息列表 tags: - - instance - /v1/projects/{project_name}/instances/{instance_name}/schemas: - get: - description: instance schema list - operationId: getInstanceSchemasV1 + - audit_plan + post: + consumes: + - application/json + description: create audit plan + operationId: createAuditPlanV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: instance name - in: path - name: instance_name + - description: create audit plan + in: body + name: audit_plan required: true - type: string + schema: + $ref: '#/definitions/v1.CreateAuditPlanReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetInstanceSchemaResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 实例 Schema 列表 + summary: 添加扫描任务 tags: - - instance - /v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables: - get: - description: list table by schema - operationId: listTableBySchema - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: instance name + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/: + delete: + description: delete audit plan + operationId: deleteAuditPlanV1 + parameters: + - description: project name in: path - name: instance_name + name: project_name required: true type: string - - description: schema name + - description: audit plan name in: path - name: schema_name + name: audit_plan_name required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.ListTableBySchemaResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取数据库下的所有表 + summary: 删除扫描任务 tags: - - instance - /v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables/{table_name}/metadata: + - audit_plan get: - description: get table metadata - operationId: getTableMetadata + description: get audit plan + operationId: getAuditPlanV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: instance name - in: path - name: instance_name - required: true - type: string - - description: schema name - in: path - name: schema_name - required: true - type: string - - description: table name + - description: audit plan name in: path - name: table_name + name: audit_plan_name required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetTableMetadataResV1' + $ref: '#/definitions/v1.GetAuditPlanResV1' security: - ApiKeyAuth: [] - summary: 获取表元数据 + summary: 获取指定扫描任务 tags: - - instance - /v1/projects/{project_name}/instances/connections: - post: - description: batch test instance db connections - operationId: batchCheckInstanceIsConnectableByName + - audit_plan + patch: + description: update audit plan + operationId: updateAuditPlanV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: instances + - description: audit plan name + in: path + name: audit_plan_name + required: true + type: string + - description: update audit plan in: body - name: instances + name: audit_plan required: true schema: - $ref: '#/definitions/v1.BatchCheckInstanceConnectionsReqV1' + $ref: '#/definitions/v1.UpdateAuditPlanReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.BatchGetInstanceConnectionsResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 批量测试实例连通性(实例提交后) + summary: 更新扫描任务 tags: - - instance - /v1/projects/{project_name}/member_groups: + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config: get: - description: get member groups - operationId: getMemberGroupsV1 + description: get audit plan notify config + operationId: getAuditPlanNotifyConfigV1 parameters: - - description: filter user group name - in: query - name: filter_user_group_name - type: string - - description: filter instance name - in: query - name: filter_instance_name - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size - required: true - type: integer - description: project name in: path name: project_name required: true type: string + - description: audit plan name + in: path + name: audit_plan_name + required: true + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetMemberGroupsRespV1' + $ref: '#/definitions/v1.GetAuditPlanNotifyConfigResV1' security: - ApiKeyAuth: [] - summary: 获取成员组列表 + summary: 获取扫描任务消息推送设置 tags: - - user_group - post: - consumes: - - application/json - description: add member group - operationId: addMemberGroupV1 + - audit_plan + patch: + description: update audit plan notify config + operationId: updateAuditPlanNotifyConfigV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: add member group + - description: audit plan name + in: path + name: audit_plan_name + required: true + type: string + - description: update audit plan notify config in: body - name: data + name: config required: true schema: - $ref: '#/definitions/v1.CreateMemberGroupReqV1' - produces: - - application/json + $ref: '#/definitions/v1.UpdateAuditPlanNotifyConfigReqV1' responses: "200": description: OK @@ -7527,124 +4510,148 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 添加成员组 + summary: 更新扫描任务通知设置 tags: - - user_group - /v1/projects/{project_name}/member_groups/{user_group_name}/: - delete: - description: delete member group - operationId: deleteMemberGroupV1 + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/notify_config/test: + get: + description: Test audit task message push + operationId: testAuditPlanNotifyConfigV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: user group name + - description: audit plan name in: path - name: user_group_name + name: audit_plan_name required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.TestAuditPlanNotifyConfigResV1' security: - ApiKeyAuth: [] - summary: 删除成员组 + summary: 测试扫描任务消息推送 tags: - - user_group + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports: get: - description: get member group - operationId: getMemberGroupV1 + description: get audit plan report list + operationId: getAuditPlanReportsV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: user group name + - description: audit plan name in: path - name: user_group_name + name: audit_plan_name required: true type: string + - description: page index + in: query + name: page_index + required: true + type: integer + - description: size of per page + in: query + name: page_size + required: true + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetMemberGroupRespV1' + $ref: '#/definitions/v1.GetAuditPlanReportsResV1' security: - ApiKeyAuth: [] - summary: 获取成员组信息 + summary: 获取指定扫描任务的报告列表 tags: - - user_group - patch: - consumes: - - application/json - description: update member group - operationId: updateMemberGroupV1 + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/: + get: + description: get audit plan report + operationId: getAuditPlanReportV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: user group name + - description: audit plan name in: path - name: user_group_name + name: audit_plan_name required: true type: string - - description: update member_group - in: body - name: data + - description: audit plan report id + in: path + name: audit_plan_report_id required: true - schema: - $ref: '#/definitions/v1.UpdateMemberGroupReqV1' - produces: - - application/json + type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetAuditPlanReportResV1' security: - ApiKeyAuth: [] - summary: 修改成员组 + summary: 获取指定扫描任务的SQL扫描记录统计信息 tags: - - user_group - /v1/projects/{project_name}/member_tips: + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/export: get: - description: get member tip list - operationId: getMemberTipListV1 + description: export audit plan report as csv + operationId: exportAuditPlanReportV1 parameters: - description: project name in: path name: project_name required: true type: string + - description: audit plan name + in: path + name: audit_plan_name + required: true + type: string + - description: audit plan report id + in: path + name: audit_plan_report_id + required: true + type: string responses: "200": - description: OK + description: get export audit plan report schema: - $ref: '#/definitions/v1.GetMemberTipsResV1' + type: file security: - ApiKeyAuth: [] - summary: 获取成员提示列表 + summary: 以csv的形式导出扫描报告 tags: - - user - /v1/projects/{project_name}/members: + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls: get: - description: get members - operationId: getMembersV1 + description: get audit plan report SQLs + operationId: getAuditPlanReportsSQLsV1 parameters: - - description: filter user name - in: query - name: filter_user_name + - description: project name + in: path + name: project_name + required: true type: string - - description: filter instance name - in: query - name: filter_instance_name + - description: audit plan name + in: path + name: audit_plan_name + required: true + type: string + - description: audit plan report id + in: path + name: audit_plan_report_id + required: true type: string - description: page index in: query @@ -7656,123 +4663,140 @@ paths: name: page_size required: true type: integer - - description: project name - in: path - name: project_name - required: true - type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetMembersRespV1' + $ref: '#/definitions/v1.GetAuditPlanReportSQLsResV1' security: - ApiKeyAuth: [] - summary: 获取成员列表 + summary: 获取指定扫描任务的SQL扫描详情 tags: - - user - post: - consumes: - - application/json - description: add member - operationId: addMemberV1 + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/reports/{audit_plan_report_id}/sqls/{number}/analysis: + get: + description: get SQL explain and related table metadata for analysis + operationId: getTaskAnalysisData parameters: - description: project name in: path name: project_name required: true type: string - - description: add member - in: body - name: data + - description: audit plan name + in: path + name: audit_plan_name required: true - schema: - $ref: '#/definitions/v1.CreateMemberReqV1' - produces: - - application/json + type: string + - description: audit plan report id + in: path + name: audit_plan_report_id + required: true + type: string + - description: sql number + in: path + name: number + required: true + type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetAuditPlanAnalysisDataResV1' security: - ApiKeyAuth: [] - summary: 添加成员 + summary: 获取task相关的SQL执行计划和表元数据 tags: - - user - /v1/projects/{project_name}/members/{user_name}/: - delete: - description: delete member - operationId: deleteMemberV1 + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls: + get: + description: get audit plan SQLs + operationId: getAuditPlanSQLsV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: user name + - description: audit plan name in: path - name: user_name + name: audit_plan_name + required: true + type: string + - description: page index + in: query + name: page_index + required: true + type: integer + - description: size of per page + in: query + name: page_size required: true - type: string + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetAuditPlanSQLsResV1' security: - ApiKeyAuth: [] - summary: 删除成员 + summary: 获取指定扫描任务的SQLs信息(不包括扫描结果) tags: - - user - get: - description: get member - operationId: getMemberV1 + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/full: + post: + deprecated: true + description: full sync audit plan SQLs + operationId: fullSyncAuditPlanSQLsV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: user name + - description: audit plan name in: path - name: user_name + name: audit_plan_name required: true type: string + - description: full sync audit plan SQLs request + in: body + name: sqls + required: true + schema: + $ref: '#/definitions/v1.FullSyncAuditPlanSQLsReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetMemberRespV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取成员信息 + summary: 全量同步SQL到扫描任务 tags: - - user - patch: - consumes: - - application/json - description: update member - operationId: updateMemberV1 + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/sqls/partial: + post: + deprecated: true + description: partial sync audit plan SQLs + operationId: partialSyncAuditPlanSQLsV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: user name + - description: audit plan name in: path - name: user_name + name: audit_plan_name required: true type: string - - description: update member + - description: partial sync audit plan SQLs request in: body - name: data + name: sqls required: true schema: - $ref: '#/definitions/v1.UpdateMemberReqV1' - produces: - - application/json + $ref: '#/definitions/v1.PartialSyncAuditPlanSQLsReqV1' responses: "200": description: OK @@ -7780,37 +4804,38 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 修改成员 + summary: 增量同步SQL到扫描任务 tags: - - user - /v1/projects/{project_name}/rule_template_tips: - get: - description: get rule template tips in project - operationId: getProjectRuleTemplateTipsV1 + - audit_plan + /v1/projects/{project_name}/audit_plans/{audit_plan_name}/trigger: + post: + description: trigger audit plan + operationId: triggerAuditPlanV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: filter db type - in: query - name: filter_db_type + - description: audit plan name + in: path + name: audit_plan_name + required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetRuleTemplateTipsResV1' + $ref: '#/definitions/v1.TriggerAuditPlanResV1' security: - ApiKeyAuth: [] - summary: 获取项目规则模板提示 + summary: 触发扫描任务 tags: - - rule_template - /v1/projects/{project_name}/rule_templates: + - audit_plan + /v1/projects/{project_name}/audit_whitelist: get: - description: get all rule template in a project - operationId: getProjectRuleTemplateListV1 + description: get all whitelist + operationId: getAuditWhitelistV1 parameters: - description: project name in: path @@ -7821,39 +4846,39 @@ paths: in: query name: page_index required: true - type: integer - - description: size of per page + type: string + - description: page size in: query name: page_size required: true - type: integer + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetProjectRuleTemplatesResV1' + $ref: '#/definitions/v1.GetAuditWhitelistResV1' security: - ApiKeyAuth: [] - summary: 项目规则模板列表 + summary: 获取Sql审核白名单 tags: - - rule_template + - audit_whitelist post: consumes: - application/json - description: create a rule template in project - operationId: createProjectRuleTemplateV1 + description: create a sql whitelist + operationId: createAuditWhitelistV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: add rule template request + - description: add sql whitelist req in: body - name: req + name: instance required: true schema: - $ref: '#/definitions/v1.CreateProjectRuleTemplateReqV1' + $ref: '#/definitions/v1.CreateAuditWhitelistReqV1' responses: "200": description: OK @@ -7861,22 +4886,22 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 添加项目规则模板 + summary: 添加SQL白名单 tags: - - rule_template - /v1/projects/{project_name}/rule_templates/{rule_template_name}/: + - audit_whitelist + /v1/projects/{project_name}/audit_whitelist/{audit_whitelist_id}/: delete: - description: delete rule template in project - operationId: deleteProjectRuleTemplateV1 + description: remove sql white + operationId: deleteAuditWhitelistByIdV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: rule template name + - description: audit whitelist id in: path - name: rule_template_name + name: audit_whitelist_id required: true type: string responses: @@ -7886,53 +4911,31 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 删除项目规则模板 - tags: - - rule_template - get: - description: get rule template detail in project - operationId: getProjectRuleTemplateV1 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: rule template name - in: path - name: rule_template_name - required: true - type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetProjectRuleTemplateResV1' - security: - - ApiKeyAuth: [] - summary: 获取项目规则模板信息 + summary: 删除SQL白名单信息 tags: - - rule_template + - audit_whitelist patch: - description: update rule template in project - operationId: updateProjectRuleTemplateV1 + consumes: + - application/json + description: update sql whitelist by id + operationId: UpdateAuditWhitelistByIdV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: rule template name + - description: sql audit whitelist id in: path - name: rule_template_name + name: audit_whitelist_id required: true type: string - - description: update rule template request + - description: update sql whitelist req in: body - name: req + name: instance required: true schema: - $ref: '#/definitions/v1.UpdateProjectRuleTemplateReqV1' + $ref: '#/definitions/v1.UpdateAuditWhitelistReqV1' responses: "200": description: OK @@ -7940,137 +4943,99 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 更新项目规则模板 + summary: 更新SQL白名单 tags: - - rule_template - /v1/projects/{project_name}/rule_templates/{rule_template_name}/clone: - post: - consumes: - - application/json - description: clone a rule template in project - operationId: cloneProjectRuleTemplateV1 + - audit_whitelist + /v1/projects/{project_name}/instance_tips: + get: + description: get instance tip list + operationId: getInstanceTipListV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: rule template name - in: path - name: rule_template_name - required: true + - description: filter db type + in: query + name: filter_db_type + type: string + - description: filter workflow template id + in: query + name: filter_workflow_template_id + type: string + - description: functional module + enum: + - create_audit_plan + - create_workflow + - sql_manage + in: query + name: functional_module type: string - - description: clone rule template request - in: body - name: req - required: true - schema: - $ref: '#/definitions/v1.CloneProjectRuleTemplateReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetInstanceTipsResV1' security: - ApiKeyAuth: [] - summary: 克隆项目规则模板 + summary: 获取实例提示列表 tags: - - rule_template - /v1/projects/{project_name}/rule_templates/{rule_template_name}/export: + - instance + /v1/projects/{project_name}/instances/{instance_name}/connection: get: - description: export rule template in a project - operationId: exportProjectRuleTemplateV1 + description: test instance db connection + operationId: checkInstanceIsConnectableByNameV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: rule template name + - description: instance name in: path - name: rule_template_name + name: instance_name required: true type: string responses: "200": - description: sqle rule template file + description: OK schema: - type: file + $ref: '#/definitions/v1.GetInstanceConnectableResV1' security: - ApiKeyAuth: [] - summary: 导出项目规则模板 + summary: 实例连通性测试(实例提交后) tags: - - rule_template - /v1/projects/{project_name}/sql_audit_records: - get: - description: get sql audit records - operationId: getSQLAuditRecordsV1 - parameters: - - description: fuzzy search tags - in: query - name: fuzzy_search_tags - type: string - - description: filter sql audit status - enum: - - auditing - - successfully - in: query - name: filter_sql_audit_status - type: string - - description: filter instance name - in: query - name: filter_instance_name - type: string - - description: filter create time from - in: query - name: filter_create_time_from - type: string - - description: filter create time to - in: query - name: filter_create_time_to - type: string - - description: filter sql audit record ids - in: query - name: filter_sql_audit_record_ids - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size - required: true - type: integer + - instance + /v1/projects/{project_name}/instances/{instance_name}/rules: + get: + description: get instance all rule + operationId: getInstanceRuleListV1 + parameters: - description: project name in: path name: project_name required: true type: string + - description: instance name + in: path + name: instance_name + required: true + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetSQLAuditRecordsResV1' + $ref: '#/definitions/v1.GetRulesResV1' security: - ApiKeyAuth: [] - summary: 获取SQL审核记录列表 + summary: 获取实例应用的规则列表 tags: - - sql_audit_record - post: - consumes: - - multipart/form-data - description: |- - SQL audit - 1. formData[sql]: sql content; - 2. file[input_sql_file]: it is a sql file; - 3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it. - 4. file[input_zip_file]: it is ZIP file that sql will be parsed from xml or sql file inside it. - 5. formData[git_http_url]:the url which scheme is http(s) and end with .git. - 6. formData[git_user_name]:The name of the user who owns the repository read access. - 7. formData[git_user_password]:The password corresponding to git_user_name. - operationId: CreateSQLAuditRecordV1 + - instance + /v1/projects/{project_name}/instances/{instance_name}/schemas: + get: + description: instance schema list + operationId: getInstanceSchemasV1 parameters: - description: project name in: path @@ -8078,282 +5043,182 @@ paths: required: true type: string - description: instance name - in: formData + in: path name: instance_name + required: true type: string - - description: schema of instance - in: formData - name: instance_schema - type: string - - description: db type of instance - in: formData - name: db_type - type: string - - description: sqls for audit - in: formData - name: sqls - type: string - - description: input SQL file - in: formData - name: input_sql_file - type: file - - description: input mybatis XML file - in: formData - name: input_mybatis_xml_file - type: file - - description: input ZIP file - in: formData - name: input_zip_file - type: file - - description: git repository url - in: formData - name: git_http_url - type: string - - description: the name of user to clone the repository - in: formData - name: git_user_name - type: string - - description: the password corresponding to git_user_name - in: formData - name: git_user_password - type: string - produces: - - application/json responses: "200": description: OK schema: - $ref: '#/definitions/v1.CreateSQLAuditRecordResV1' + $ref: '#/definitions/v1.GetInstanceSchemaResV1' security: - ApiKeyAuth: [] - summary: SQL审核 + summary: 实例 Schema 列表 tags: - - sql_audit_record - /v1/projects/{project_name}/sql_audit_records/{sql_audit_record_id}/: + - instance + /v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables: get: - description: get sql audit record info - operationId: getSQLAuditRecordV1 + description: list table by schema + operationId: listTableBySchema parameters: - description: project name in: path name: project_name required: true type: string - - description: sql audit record id + - description: instance name in: path - name: sql_audit_record_id + name: instance_name + required: true + type: string + - description: schema name + in: path + name: schema_name required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetSQLAuditRecordResV1' + $ref: '#/definitions/v1.ListTableBySchemaResV1' security: - ApiKeyAuth: [] - summary: 获取SQL审核记录信息 + summary: 获取数据库下的所有表 tags: - - sql_audit_record - patch: - consumes: - - application/json - description: update SQL audit record - operationId: updateSQLAuditRecordV1 + - instance + /v1/projects/{project_name}/instances/{instance_name}/schemas/{schema_name}/tables/{table_name}/metadata: + get: + description: get table metadata + operationId: getTableMetadata parameters: - description: project name in: path name: project_name required: true type: string - - description: sql audit record id + - description: instance name in: path - name: sql_audit_record_id + name: instance_name required: true type: string - - description: update SQL audit record - in: body - name: param + - description: schema name + in: path + name: schema_name required: true - schema: - $ref: '#/definitions/v1.UpdateSQLAuditRecordReqV1' + type: string + - description: table name + in: path + name: table_name + required: true + type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetTableMetadataResV1' security: - ApiKeyAuth: [] - summary: 更新SQL审核记录 + summary: 获取表元数据 tags: - - sql_audit_record - /v1/projects/{project_name}/sql_audit_records/tag_tips: - get: - description: get sql audit record tag tips - operationId: GetSQLAuditRecordTagTipsV1 + - instance + /v1/projects/{project_name}/instances/connections: + post: + description: batch test instance db connections + operationId: batchCheckInstanceIsConnectableByName parameters: - description: project name in: path name: project_name required: true type: string + - description: instances + in: body + name: instances + required: true + schema: + $ref: '#/definitions/v1.BatchCheckInstanceConnectionsReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetSQLAuditRecordTagTipsResV1' + $ref: '#/definitions/v1.BatchGetInstanceConnectionsResV1' security: - ApiKeyAuth: [] - summary: 获取SQL审核记录标签列表 + summary: 批量测试实例连通性(实例提交后) tags: - - sql_audit_record - /v1/projects/{project_name}/sql_manages: + - instance + /v1/projects/{project_name}/rule_template_tips: get: - deprecated: true - description: get sql manage list - operationId: GetSqlManageList + description: get rule template tips in project + operationId: getProjectRuleTemplateTipsV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: fuzzy search sql fingerprint - in: query - name: fuzzy_search_sql_fingerprint - type: string - - description: assignee - in: query - name: filter_assignee - type: string - - description: instance name - in: query - name: filter_instance_name - type: string - - description: source - enum: - - audit_plan - - sql_audit_record - in: query - name: filter_source - type: string - - description: audit level - enum: - - normal - - notice - - warn - - error - in: query - name: filter_audit_level - type: string - - description: last audit start time from - in: query - name: filter_last_audit_start_time_from - type: string - - description: last audit start time to - in: query - name: filter_last_audit_start_time_to - type: string - - description: status - enum: - - unhandled - - solved - - ignored - - manual_audited - in: query - name: filter_status - type: string - - description: rule name - in: query - name: filter_rule_name - type: string - - description: db type + - description: filter db type in: query name: filter_db_type type: string - - description: fuzzy search endpoint - in: query - name: fuzzy_search_endpoint - type: string - - description: fuzzy search schema name - in: query - name: fuzzy_search_schema_name - type: string - - description: sort field - enum: - - first_appear_timestamp - - last_receive_timestamp - - fp_count - in: query - name: sort_field - type: string - - description: sort order - enum: - - asc - - desc - in: query - name: sort_order - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size - required: true - type: integer responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetSqlManageListResp' + $ref: '#/definitions/v1.GetRuleTemplateTipsResV1' security: - ApiKeyAuth: [] - summary: 获取管控sql列表 + summary: 获取项目规则模板提示 tags: - - SqlManage - /v1/projects/{project_name}/sql_manages/{sql_manage_id}/sql_analysis: - get: - description: get sql manage analysis - operationId: GetSqlManageSqlAnalysisV1 + - rule_template + /v1/projects/{project_name}/rule_templates: + get: + description: get all rule template in a project + operationId: getProjectRuleTemplateListV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: sql manage id - in: path - name: sql_manage_id + - description: page index + in: query + name: page_index required: true - type: string + type: integer + - description: size of per page + in: query + name: page_size + required: true + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetSqlManageSqlAnalysisResp' + $ref: '#/definitions/v1.GetProjectRuleTemplatesResV1' security: - ApiKeyAuth: [] - summary: 获取SQL管控SQL分析 + summary: 项目规则模板列表 tags: - - SqlManage - /v1/projects/{project_name}/sql_manages/batch: - patch: - description: batch update sql manage - operationId: BatchUpdateSqlManage + - rule_template + post: + consumes: + - application/json + description: create a rule template in project + operationId: createProjectRuleTemplateV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: batch update sql manage request + - description: add rule template request in: body - name: BatchUpdateSqlManageReq + name: req required: true schema: - $ref: '#/definitions/v1.BatchUpdateSqlManageReq' + $ref: '#/definitions/v1.CreateProjectRuleTemplateReqV1' responses: "200": description: OK @@ -8361,190 +5226,192 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 批量更新SQL管控 + summary: 添加项目规则模板 tags: - - SqlManage - /v1/projects/{project_name}/sql_manages/exports: - get: - description: export sql manage - operationId: exportSqlManageV1 + - rule_template + /v1/projects/{project_name}/rule_templates/{rule_template_name}/: + delete: + description: delete rule template in project + operationId: deleteProjectRuleTemplateV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: fuzzy search sql fingerprint - in: query - name: fuzzy_search_sql_fingerprint - type: string - - description: assignee - in: query - name: filter_assignee - type: string - - description: instance name - in: query - name: filter_instance_name - type: string - - description: source - enum: - - audit_plan - - sql_audit_record - in: query - name: filter_source - type: string - - description: audit level - enum: - - normal - - notice - - warn - - error - in: query - name: filter_audit_level - type: string - - description: last audit start time from - in: query - name: filter_last_audit_start_time_from - type: string - - description: last audit start time to - in: query - name: filter_last_audit_start_time_to - type: string - - description: status - enum: - - unhandled - - solved - - ignored - - manual_audited - in: query - name: filter_status - type: string - - description: db type - in: query - name: filter_db_type - type: string - - description: rule name - in: query - name: filter_rule_name - type: string - - description: fuzzy search endpoint - in: query - name: fuzzy_search_endpoint - type: string - - description: fuzzy search schema name - in: query - name: fuzzy_search_schema_name - type: string - - description: sort field - enum: - - first_appear_timestamp - - last_receive_timestamp - - fp_count - in: query - name: sort_field - type: string - - description: sort order - enum: - - asc - - desc - in: query - name: sort_order + - description: rule template name + in: path + name: rule_template_name + required: true type: string responses: "200": - description: export sql manage + description: OK schema: - type: file + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 导出SQL管控 + summary: 删除项目规则模板 tags: - - SqlManage - /v1/projects/{project_name}/sql_manages/rule_tips: + - rule_template get: - description: get sql manage rule tips - operationId: GetSqlManageRuleTips + description: get rule template detail in project + operationId: getProjectRuleTemplateV1 parameters: - description: project name in: path name: project_name required: true type: string + - description: rule template name + in: path + name: rule_template_name + required: true + type: string + - description: fuzzy rule,keyword for desc and annotation + in: query + name: fuzzy_keyword_rule + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetSqlManageRuleTipsResp' + $ref: '#/definitions/v1.GetProjectRuleTemplateResV1' security: - ApiKeyAuth: [] - summary: 获取管控规则tips + summary: 获取项目规则模板信息 tags: - - SqlManage - /v1/projects/{project_name}/statistic/audit_plans: - get: - description: statistic audit plan - operationId: statisticAuditPlanV1 + - rule_template + patch: + description: update rule template in project + operationId: updateProjectRuleTemplateV1 parameters: - description: project name in: path name: project_name required: true type: string + - description: rule template name + in: path + name: rule_template_name + required: true + type: string + - description: update rule template request + in: body + name: req + required: true + schema: + $ref: '#/definitions/v1.UpdateProjectRuleTemplateReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.StatisticAuditPlanResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取各类型数据源上的扫描任务数量 + summary: 更新项目规则模板 tags: - - statistic - /v1/projects/{project_name}/statistic/audited_sqls: - get: - description: statistics audited sql - operationId: statisticsAuditedSQLV1 + - rule_template + /v1/projects/{project_name}/rule_templates/{rule_template_name}/clone: + post: + consumes: + - application/json + description: clone a rule template in project + operationId: cloneProjectRuleTemplateV1 parameters: - description: project name in: path name: project_name required: true type: string + - description: rule template name + in: path + name: rule_template_name + required: true + type: string + - description: clone rule template request + in: body + name: req + required: true + schema: + $ref: '#/definitions/v1.CloneProjectRuleTemplateReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.StatisticsAuditedSQLResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取审核SQL总数,以及触发审核规则的SQL数量 + summary: 克隆项目规则模板 tags: - - statistic - /v1/projects/{project_name}/statistic/instance_health: + - rule_template + /v1/projects/{project_name}/rule_templates/{rule_template_name}/export: get: - description: get instance health - operationId: GetInstanceHealthV1 + description: export rule template in a project + operationId: exportProjectRuleTemplateV1 parameters: - description: project name in: path name: project_name required: true type: string + - description: rule template name + in: path + name: rule_template_name + required: true + type: string responses: "200": - description: OK + description: sqle rule template file schema: - $ref: '#/definitions/v1.GetInstanceHealthResV1' + type: file security: - ApiKeyAuth: [] - summary: 获取各类型数据源的健康情况 + summary: 导出项目规则模板 tags: - - statistic - /v1/projects/{project_name}/statistic/project_score: + - rule_template + /v1/projects/{project_name}/sql_audit_records: get: - description: get project score - operationId: GetProjectScoreV1 + description: get sql audit records + operationId: getSQLAuditRecordsV1 parameters: + - description: fuzzy search tags + in: query + name: fuzzy_search_tags + type: string + - description: filter sql audit status + enum: + - auditing + - successfully + in: query + name: filter_sql_audit_status + type: string + - description: filter instance id + in: query + name: filter_instance_id + type: integer + - description: filter create time from + in: query + name: filter_create_time_from + type: string + - description: filter create time to + in: query + name: filter_create_time_to + type: string + - description: filter sql audit record ids + in: query + name: filter_sql_audit_record_ids + type: string + - description: page index + in: query + name: page_index + required: true + type: integer + - description: size of per page + in: query + name: page_size + required: true + type: integer - description: project name in: path name: project_name @@ -8554,258 +5421,308 @@ paths: "200": description: OK schema: - $ref: '#/definitions/v1.GetProjectScoreResV1' + $ref: '#/definitions/v1.GetSQLAuditRecordsResV1' security: - ApiKeyAuth: [] - summary: 获取项目分数 + summary: 获取SQL审核记录列表 tags: - - statistic - /v1/projects/{project_name}/statistic/risk_audit_plans: - get: - description: get risk audit plan - operationId: getRiskAuditPlanV1 + - sql_audit_record + post: + consumes: + - multipart/form-data + description: |- + SQL audit + 1. formData[sql]: sql content; + 2. file[input_sql_file]: it is a sql file; + 3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it. + 4. file[input_zip_file]: it is ZIP file that sql will be parsed from xml or sql file inside it. + 5. formData[git_http_url]:the url which scheme is http(s) and end with .git. + 6. formData[git_user_name]:The name of the user who owns the repository read access. + 7. formData[git_user_password]:The password corresponding to git_user_name. + operationId: CreateSQLAuditRecordV1 parameters: - description: project name in: path name: project_name required: true type: string + - description: instance name + in: formData + name: instance_name + type: string + - description: schema of instance + in: formData + name: instance_schema + type: string + - description: db type of instance + in: formData + name: db_type + type: string + - description: sqls for audit + in: formData + name: sqls + type: string + - description: input SQL file + in: formData + name: input_sql_file + type: file + - description: input mybatis XML file + in: formData + name: input_mybatis_xml_file + type: file + - description: input ZIP file + in: formData + name: input_zip_file + type: file + - description: git repository url + in: formData + name: git_http_url + type: string + - description: the name of user to clone the repository + in: formData + name: git_user_name + type: string + - description: the password corresponding to git_user_name + in: formData + name: git_user_password + type: string + produces: + - application/json responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetRiskAuditPlanResV1' + $ref: '#/definitions/v1.CreateSQLAuditRecordResV1' security: - ApiKeyAuth: [] - summary: 获取扫描任务报告评分低于60的扫描任务 + summary: SQL审核 tags: - - statistic - /v1/projects/{project_name}/statistic/risk_workflow: + - sql_audit_record + /v1/projects/{project_name}/sql_audit_records/{sql_audit_record_id}/: get: - description: statistic risk workflow - operationId: statisticRiskWorkflowV1 + description: get sql audit record info + operationId: getSQLAuditRecordV1 parameters: - description: project name in: path name: project_name required: true type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.StatisticRiskWorkflowResV1' - security: - - ApiKeyAuth: [] - summary: 获取存在风险的工单 - tags: - - statistic - /v1/projects/{project_name}/statistic/role_user: - get: - description: get role user count - operationId: getRoleUserCountV1 - parameters: - - description: project name + - description: sql audit record id in: path - name: project_name + name: sql_audit_record_id required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetRoleUserCountResV1' + $ref: '#/definitions/v1.GetSQLAuditRecordResV1' security: - ApiKeyAuth: [] - summary: 获取各角色类型对应的成员数量 + summary: 获取SQL审核记录信息 tags: - - statistic - /v1/projects/{project_name}/statistic/workflow_status: - get: - description: statistic workflow status - operationId: statisticWorkflowStatusV1 + - sql_audit_record + patch: + consumes: + - application/json + description: update SQL audit record + operationId: updateSQLAuditRecordV1 parameters: - description: project name in: path name: project_name required: true type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetWorkflowStatusCountResV1' - security: - - ApiKeyAuth: [] - summary: 获取项目下工单各个状态的数量 - tags: - - statistic - /v1/projects/{project_name}/statistics: - get: - description: get project statistics - operationId: getProjectStatisticsV1 - parameters: - - description: project name + - description: sql audit record id in: path - name: project_name + name: sql_audit_record_id required: true type: string + - description: update SQL audit record + in: body + name: param + required: true + schema: + $ref: '#/definitions/v1.UpdateSQLAuditRecordReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetProjectStatisticsResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取项目统计信息 + summary: 更新SQL审核记录 tags: - - statistic - /v1/projects/{project_name}/task_groups: - post: - consumes: - - application/json - description: create tasks group. - operationId: createAuditTasksV1 + - sql_audit_record + /v1/projects/{project_name}/sql_audit_records/tag_tips: + get: + description: get sql audit record tag tips + operationId: GetSQLAuditRecordTagTipsV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: parameters for creating audit tasks group - in: body - name: req - required: true - schema: - $ref: '#/definitions/v1.CreateAuditTasksGroupReqV1' - produces: - - application/json responses: "200": description: OK schema: - $ref: '#/definitions/v1.CreateAuditTasksGroupResV1' + $ref: '#/definitions/v1.GetSQLAuditRecordTagTipsResV1' security: - ApiKeyAuth: [] - summary: 创建审核任务组 + summary: 获取SQL审核记录标签列表 tags: - - task - /v1/projects/{project_name}/tasks/audits: - post: - consumes: - - multipart/form-data - description: |- - create and audit a task, you can upload sql content in three ways, any one can be used, but only one is effective. - 1. formData[sql]: sql content; - 2. file[input_sql_file]: it is a sql file; - 3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it. - operationId: createAndAuditTaskV1 + - sql_audit_record + /v1/projects/{project_name}/sql_manages: + get: + deprecated: true + description: get sql manage list + operationId: GetSqlManageList parameters: - description: project name in: path name: project_name required: true type: string + - description: fuzzy search sql fingerprint + in: query + name: fuzzy_search_sql_fingerprint + type: string + - description: assignee + in: query + name: filter_assignee + type: string - description: instance name - in: formData - name: instance_name - required: true + in: query + name: filter_instance_name type: string - - description: schema of instance - in: formData - name: instance_schema + - description: source + enum: + - audit_plan + - sql_audit_record + in: query + name: filter_source + type: string + - description: audit level + enum: + - normal + - notice + - warn + - error + in: query + name: filter_audit_level + type: string + - description: last audit start time from + in: query + name: filter_last_audit_start_time_from + type: string + - description: last audit start time to + in: query + name: filter_last_audit_start_time_to + type: string + - description: status + enum: + - unhandled + - solved + - ignored + - manual_audited + in: query + name: filter_status + type: string + - description: rule name + in: query + name: filter_rule_name + type: string + - description: db type + in: query + name: filter_db_type + type: string + - description: fuzzy search endpoint + in: query + name: fuzzy_search_endpoint + type: string + - description: fuzzy search schema name + in: query + name: fuzzy_search_schema_name + type: string + - description: sort field + enum: + - first_appear_timestamp + - last_receive_timestamp + - fp_count + in: query + name: sort_field type: string - - description: sqls for audit - in: formData - name: sql + - description: sort order + enum: + - asc + - desc + in: query + name: sort_order type: string - - description: input SQL file - in: formData - name: input_sql_file - type: file - - description: input mybatis XML file - in: formData - name: input_mybatis_xml_file - type: file - - description: input ZIP file - in: formData - name: input_zip_file - type: file - produces: - - application/json + - description: page index + in: query + name: page_index + required: true + type: integer + - description: size of per page + in: query + name: page_size + required: true + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditTaskResV1' + $ref: '#/definitions/v1.GetSqlManageListResp' security: - ApiKeyAuth: [] - summary: 创建Sql扫描任务并提交审核 + summary: 获取管控sql列表 tags: - - task - /v1/projects/{project_name}/unarchive: - post: - consumes: - - application/json - description: archive project - operationId: unarchiveProjectV1 + - SqlManage + /v1/projects/{project_name}/sql_manages/{sql_manage_id}/sql_analysis: + get: + description: get sql manage analysis + operationId: GetSqlManageSqlAnalysisV1 parameters: - description: project name in: path name: project_name required: true type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 取消归档项目 - tags: - - project - /v1/projects/{project_name}/workflow_template: - get: - description: get workflow template detail - operationId: getWorkflowTemplateV1 - parameters: - - description: project name + - description: sql manage id in: path - name: project_name + name: sql_manage_id required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowTemplateResV1' + $ref: '#/definitions/v1.GetSqlManageSqlAnalysisResp' security: - ApiKeyAuth: [] - summary: 获取审批流程模板详情 + summary: 获取SQL管控SQL分析 tags: - - workflow + - SqlManage + /v1/projects/{project_name}/sql_manages/batch: patch: - consumes: - - application/json - description: update the workflow template - operationId: updateWorkflowTemplateV1 + description: batch update sql manage + operationId: BatchUpdateSqlManage parameters: - description: project name in: path name: project_name required: true type: string - - description: create workflow template + - description: batch update sql manage request in: body - name: instance + name: BatchUpdateSqlManageReq required: true schema: - $ref: '#/definitions/v1.UpdateWorkflowTemplateReqV1' - produces: - - application/json + $ref: '#/definitions/v1.BatchUpdateSqlManageReq' responses: "200": description: OK @@ -8813,161 +5730,150 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 更新Sql审批流程模板 + summary: 批量更新SQL管控 tags: - - workflow - /v1/projects/{project_name}/workflows: + - SqlManage + /v1/projects/{project_name}/sql_manages/exports: get: - description: get workflow list - operationId: getWorkflowsV1 + description: export sql manage + operationId: exportSqlManageV1 parameters: - - description: filter subject - in: query - name: filter_subject + - description: project name + in: path + name: project_name + required: true type: string - - description: filter by workflow_id + - description: fuzzy search sql fingerprint in: query - name: filter_workflow_id + name: fuzzy_search_sql_fingerprint type: string - - description: fuzzy search by workflow description + - description: assignee in: query - name: fuzzy_search_workflow_desc + name: filter_assignee type: string - - description: filter create time from + - description: instance name in: query - name: filter_create_time_from + name: filter_instance_name type: string - - description: filter create time to + - description: source + enum: + - audit_plan + - sql_audit_record in: query - name: filter_create_time_to + name: filter_source type: string - - description: filter_task_execute_start_time_from + - description: audit level + enum: + - normal + - notice + - warn + - error in: query - name: filter_task_execute_start_time_from + name: filter_audit_level type: string - - description: filter_task_execute_start_time_to + - description: last audit start time from in: query - name: filter_task_execute_start_time_to + name: filter_last_audit_start_time_from type: string - - description: filter create user name + - description: last audit start time to in: query - name: filter_create_user_name + name: filter_last_audit_start_time_to type: string - - description: filter workflow status + - description: status enum: - - wait_for_audit - - wait_for_execution - - rejected - - executing - - canceled - - exec_failed - - finished + - unhandled + - solved + - ignored + - manual_audited in: query name: filter_status type: string - - description: filter current step assignee user name + - description: db type in: query - name: filter_current_step_assignee_user_name + name: filter_db_type type: string - - description: filter instance name + - description: rule name in: query - name: filter_task_instance_name + name: filter_rule_name type: string - - description: page index + - description: fuzzy search endpoint in: query - name: page_index - required: true - type: integer - - description: size of per page + name: fuzzy_search_endpoint + type: string + - description: fuzzy search schema name in: query - name: page_size - required: true - type: integer - - description: project name - in: path - name: project_name - required: true + name: fuzzy_search_schema_name + type: string + - description: sort field + enum: + - first_appear_timestamp + - last_receive_timestamp + - fp_count + in: query + name: sort_field + type: string + - description: sort order + enum: + - asc + - desc + in: query + name: sort_order type: string responses: "200": - description: OK + description: export sql manage schema: - $ref: '#/definitions/v1.GetWorkflowsResV1' + type: file security: - ApiKeyAuth: [] - summary: 获取工单列表 + summary: 导出SQL管控 tags: - - workflow - post: - consumes: - - application/json - deprecated: true - description: create workflow - operationId: createWorkflowV1 + - SqlManage + /v1/projects/{project_name}/sql_manages/rule_tips: + get: + description: get sql manage rule tips + operationId: GetSqlManageRuleTips parameters: - - description: create workflow request - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.CreateWorkflowReqV1' - description: project name in: path name: project_name required: true type: string - produces: - - application/json responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetSqlManageRuleTipsResp' security: - ApiKeyAuth: [] - summary: 创建工单 + summary: 获取管控规则tips tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/terminate: - post: - description: execute one task on workflow - operationId: terminateSingleTaskByWorkflowV1 + - SqlManage + /v1/projects/{project_name}/statistic/audit_plans: + get: + description: statistic audit plan + operationId: statisticAuditPlanV1 parameters: - - description: workflow id - in: path - name: workflow_id - required: true - type: string - description: project name in: path name: project_name required: true type: string - - description: task id - in: path - name: task_id - required: true - type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.StatisticAuditPlanResV1' security: - ApiKeyAuth: [] - summary: 终止单个上线任务 + summary: 获取各类型数据源上的扫描任务数量 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_id}/tasks/terminate: - post: - description: terminate multiple task by project and workflow - operationId: terminateMultipleTaskByWorkflowV1 + - statistic + /v1/projects/{project_name}/statistic/audited_sqls: + get: + description: statistics audited sql + operationId: statisticsAuditedSQLV1 parameters: - - description: workflow id - in: path - name: workflow_id - required: true - type: string - description: project name in: path name: project_name @@ -8977,23 +5883,17 @@ paths: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.StatisticsAuditedSQLResV1' security: - ApiKeyAuth: [] - summary: 终止工单下多个上线任务 + summary: 获取审核SQL总数,以及触发审核规则的SQL数量 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_name}/: + - statistic + /v1/projects/{project_name}/statistic/instance_health: get: - deprecated: true - description: get workflow detail - operationId: getWorkflowV1 + description: get instance health + operationId: GetInstanceHealthV1 parameters: - - description: workflow name - in: path - name: workflow_name - required: true - type: string - description: project name in: path name: project_name @@ -9003,89 +5903,57 @@ paths: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowResV1' + $ref: '#/definitions/v1.GetInstanceHealthResV1' security: - ApiKeyAuth: [] - summary: 获取工单详情 + summary: 获取各类型数据源的健康情况 tags: - - workflow - patch: - consumes: - - application/json - deprecated: true - description: update workflow when it is rejected to creator. - operationId: updateWorkflowV1 + - statistic + /v1/projects/{project_name}/statistic/project_score: + get: + description: get project score + operationId: GetProjectScoreV1 parameters: - - description: workflow name - in: path - name: workflow_name - required: true - type: string - description: project name in: path name: project_name required: true type: string - - description: update workflow request - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateWorkflowReqV1' - produces: - - application/json responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetProjectScoreResV1' security: - ApiKeyAuth: [] - summary: 更新工单(驳回后才可更新) + summary: 获取项目分数 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_name}/cancel: - post: - deprecated: true - description: cancel workflow - operationId: cancelWorkflowV1 + - statistic + /v1/projects/{project_name}/statistic/risk_audit_plans: + get: + description: get risk audit plan + operationId: getRiskAuditPlanV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: workflow name - in: path - name: workflow_name - required: true - type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetRiskAuditPlanResV1' security: - ApiKeyAuth: [] - summary: 审批关闭(中止) + summary: 获取扫描任务报告评分低于60的扫描任务 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/approve: - post: - deprecated: true - description: approve workflow - operationId: approveWorkflowV1 + - statistic + /v1/projects/{project_name}/statistic/risk_workflow: + get: + description: statistic risk workflow + operationId: statisticRiskWorkflowV1 parameters: - - description: workflow name - in: path - name: workflow_name - required: true - type: string - - description: workflow step id - in: path - name: workflow_step_id - required: true - type: string - description: project name in: path name: project_name @@ -9095,60 +5963,37 @@ paths: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.StatisticRiskWorkflowResV1' security: - ApiKeyAuth: [] - summary: 审批通过 + summary: 获取存在风险的工单 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/reject: - post: - deprecated: true - description: reject workflow - operationId: rejectWorkflowV1 + - statistic + /v1/projects/{project_name}/statistic/role_user: + get: + description: get role user count + operationId: getRoleUserCountV1 parameters: - - description: workflow name - in: path - name: workflow_name - required: true - type: string - description: project name in: path name: project_name required: true type: string - - description: workflow step id - in: path - name: workflow_step_id - required: true - type: string - - description: workflow approve request - in: body - name: workflow_approve - required: true - schema: - $ref: '#/definitions/v1.RejectWorkflowReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetRoleUserCountResV1' security: - ApiKeyAuth: [] - summary: 审批驳回 + summary: 获取各角色类型对应的成员数量 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_name}/tasks: + - statistic + /v1/projects/{project_name}/statistic/workflow_status: get: - deprecated: true - description: get summary of workflow instance tasks - operationId: getSummaryOfInstanceTasksV1 + description: statistic workflow status + operationId: statisticWorkflowStatusV1 parameters: - - description: workflow name - in: path - name: workflow_name - required: true - type: string - description: project name in: path name: project_name @@ -9158,155 +6003,154 @@ paths: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowTasksResV1' + $ref: '#/definitions/v1.GetWorkflowStatusCountResV1' security: - ApiKeyAuth: [] - summary: 获取工单数据源任务概览 + summary: 获取项目下工单各个状态的数量 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/execute: - post: - deprecated: true - description: execute one task on workflow - operationId: executeOneTaskOnWorkflowV1 + - statistic + /v1/projects/{project_name}/statistics: + get: + description: get project statistics + operationId: getProjectStatisticsV1 parameters: - - description: workflow name - in: path - name: workflow_name - required: true - type: string - description: project name in: path name: project_name required: true type: string - - description: task id - in: path - name: task_id - required: true - type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetProjectStatisticsResV1' security: - ApiKeyAuth: [] - summary: 工单提交单个数据源上线 + summary: 获取项目统计信息 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/schedule: - put: + - statistic + /v1/projects/{project_name}/task_groups: + post: consumes: - application/json - deprecated: true - description: update workflow schedule. - operationId: updateWorkflowScheduleV1 + description: create tasks group. + operationId: createAuditTasksV1 parameters: - - description: workflow name - in: path - name: workflow_name - required: true - type: string - - description: task id - in: path - name: task_id - required: true - type: string - description: project name in: path name: project_name required: true type: string - - description: update workflow schedule request + - description: parameters for creating audit tasks group in: body - name: instance + name: req required: true schema: - $ref: '#/definitions/v1.UpdateWorkflowScheduleReqV1' + $ref: '#/definitions/v1.CreateAuditTasksGroupReqV1' produces: - application/json responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.CreateAuditTasksGroupResV1' security: - ApiKeyAuth: [] - summary: 设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置) + summary: 创建审核任务组 tags: - - workflow - /v1/projects/{project_name}/workflows/{workflow_name}/tasks/execute: + - task + /v1/projects/{project_name}/tasks/audits: post: - deprecated: true - description: execute tasks on workflow - operationId: executeTasksOnWorkflowV1 + consumes: + - multipart/form-data + description: |- + create and audit a task, you can upload sql content in three ways, any one can be used, but only one is effective. + 1. formData[sql]: sql content; + 2. file[input_sql_file]: it is a sql file; + 3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it. + operationId: createAndAuditTaskV1 parameters: - - description: workflow name - in: path - name: workflow_name - required: true - type: string - description: project name in: path name: project_name required: true type: string + - description: instance name + in: formData + name: instance_name + required: true + type: string + - description: schema of instance + in: formData + name: instance_schema + type: string + - description: sqls for audit + in: formData + name: sql + type: string + - description: input SQL file + in: formData + name: input_sql_file + type: file + - description: input mybatis XML file + in: formData + name: input_mybatis_xml_file + type: file + - description: input ZIP file + in: formData + name: input_zip_file + type: file + produces: + - application/json responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetAuditTaskResV1' security: - ApiKeyAuth: [] - summary: 多数据源批量上线 + summary: 创建Sql扫描任务并提交审核 tags: - - workflow - /v1/projects/{project_name}/workflows/cancel: - post: - deprecated: true - description: batch cancel workflows - operationId: batchCancelWorkflowsV1 + - task + /v1/projects/{project_name}/workflow_template: + get: + description: get workflow template detail + operationId: getWorkflowTemplateV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: batch cancel workflows request - in: body - name: BatchCancelWorkflowsReqV1 - required: true - schema: - $ref: '#/definitions/v1.BatchCancelWorkflowsReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetWorkflowTemplateResV1' security: - ApiKeyAuth: [] - summary: 批量取消工单 + summary: 获取审批流程模板详情 tags: - workflow - /v1/projects/{project_name}/workflows/complete: - post: - deprecated: true - description: this api will directly change the work order status to finished - without real online operation - operationId: batchCompleteWorkflowsV1 + patch: + consumes: + - application/json + description: update the workflow template + operationId: updateWorkflowTemplateV1 parameters: - description: project name in: path name: project_name required: true type: string - - description: batch complete workflows request + - description: create workflow template in: body - name: data + name: instance required: true schema: - $ref: '#/definitions/v1.BatchCompleteWorkflowsReqV1' + $ref: '#/definitions/v1.UpdateWorkflowTemplateReqV1' + produces: + - application/json responses: "200": description: OK @@ -9314,18 +6158,22 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 批量完成工单 + summary: 更新Sql审批流程模板 tags: - workflow - /v1/projects/{project_name}/workflows/exports: + /v1/projects/{project_name}/workflows: get: - description: export workflow - operationId: exportWorkflowV1 + description: get workflow list + operationId: getWorkflowsV1 parameters: - description: filter subject in: query name: filter_subject type: string + - description: filter by workflow_id + in: query + name: filter_workflow_id + type: string - description: fuzzy search by workflow description in: query name: fuzzy_search_workflow_desc @@ -9346,9 +6194,9 @@ paths: in: query name: filter_task_execute_start_time_to type: string - - description: filter create user name + - description: filter create user id in: query - name: filter_create_user_name + name: filter_create_user_id type: string - description: filter workflow status enum: @@ -9362,54 +6210,14 @@ paths: in: query name: filter_status type: string - - description: filter current step assignee user name + - description: filter current step assignee user id in: query - name: filter_current_step_assignee_user_name + name: filter_current_step_assignee_user_id type: string - description: filter instance name in: query name: filter_task_instance_name type: string - - description: project name - in: path - name: project_name - required: true - type: string - responses: - "200": - description: export workflow - schema: - type: file - security: - - ApiKeyAuth: [] - summary: 导出工单 - tags: - - workflow - /v1/role_tips: - get: - description: get role tip list - operationId: getRoleTipListV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetRoleTipsResV1' - security: - - ApiKeyAuth: [] - summary: 获取角色提示列表 - tags: - - role - /v1/roles: - get: - consumes: - - application/json - description: get role list - operationId: getRoleListV1 - parameters: - - description: filter role name - in: query - name: filter_role_name - type: string - description: page index in: query name: page_index @@ -9420,140 +6228,45 @@ paths: name: page_size required: true type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetRolesResV1' - security: - - ApiKeyAuth: [] - summary: 获取角色列表 - tags: - - role - post: - consumes: - - application/json - description: create role - operationId: createRoleV1 - parameters: - - description: create role - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.CreateRoleReqV1' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 创建角色 - tags: - - role - /v1/roles/{role_name}/: - delete: - consumes: - - application/json - description: delete role - operationId: deleteRoleV1 - parameters: - - description: role name + - description: project name in: path - name: role_name + name: project_name required: true type: string - produces: - - application/json + - description: fuzzy matching subject/workflow_id + in: query + name: fuzzy_keyword + type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetWorkflowsResV1' security: - ApiKeyAuth: [] - summary: 删除角色 + summary: 获取工单列表 tags: - - role - patch: + - workflow + post: consumes: - application/json - description: update role - operationId: updateRoleV1 + deprecated: true + description: create workflow + operationId: createWorkflowV1 parameters: - - description: role name - in: path - name: role_name - required: true - type: string - - description: update role request + - description: create workflow request in: body name: instance required: true schema: - $ref: '#/definitions/v1.UpdateRoleReqV1' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 更新角色信息 - tags: - - role - /v1/rule_knowledge/db_types/{db_type}/custom_rules/{rule_name}/: - get: - description: get custom rule knowledge - operationId: getCustomRuleKnowledgeV1 - parameters: - - description: rule name - in: path - name: rule_name - required: true - type: string - - description: db type of rule - in: path - name: db_type - required: true - type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetRuleKnowledgeResV1' - security: - - ApiKeyAuth: [] - summary: 查看自定义规则知识库 - tags: - - rule_template - patch: - description: update custom rule knowledge - operationId: updateCustomRuleKnowledge - parameters: - - description: rule name - in: path - name: rule_name - required: true - type: string - - description: db type of rule + $ref: '#/definitions/v1.CreateWorkflowReqV1' + - description: project name in: path - name: db_type + name: project_name required: true type: string - - description: update rule knowledge - in: body - name: req - required: true - schema: - $ref: '#/definitions/v1.UpdateRuleKnowledgeReq' + produces: + - application/json responses: "200": description: OK @@ -9561,54 +6274,29 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 更新自定义规则知识库 + summary: 创建工单 tags: - - rule_template - /v1/rule_knowledge/db_types/{db_type}/rules/{rule_name}/: - get: - description: get rule knowledge - operationId: getRuleKnowledgeV1 + - workflow + /v1/projects/{project_name}/workflows/{workflow_id}/tasks/{task_id}/terminate: + post: + description: execute one task on workflow + operationId: terminateSingleTaskByWorkflowV1 parameters: - - description: rule name - in: path - name: rule_name - required: true - type: string - - description: db type of rule + - description: workflow id in: path - name: db_type + name: workflow_id required: true type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetRuleKnowledgeResV1' - security: - - ApiKeyAuth: [] - summary: 查看规则知识库 - tags: - - rule_template - patch: - description: update rule knowledge - operationId: updateRuleKnowledge - parameters: - - description: rule name + - description: project name in: path - name: rule_name + name: project_name required: true type: string - - description: db type of rule + - description: task id in: path - name: db_type + name: task_id required: true type: string - - description: update rule knowledge - in: body - name: req - required: true - schema: - $ref: '#/definitions/v1.UpdateRuleKnowledgeReq' responses: "200": description: OK @@ -9616,65 +6304,85 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 更新规则知识库 + summary: 终止单个上线任务 tags: - - rule_template - /v1/rule_template_tips: - get: - description: get global rule template tips - operationId: getRuleTemplateTipsV1 + - workflow + /v1/projects/{project_name}/workflows/{workflow_id}/tasks/terminate: + post: + description: terminate multiple task by project and workflow + operationId: terminateMultipleTaskByWorkflowV1 parameters: - - description: filter db type - in: query - name: filter_db_type + - description: workflow id + in: path + name: workflow_id + required: true + type: string + - description: project name + in: path + name: project_name + required: true type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetRuleTemplateTipsResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取全局规则模板提示 + summary: 终止工单下多个上线任务 tags: - - rule_template - /v1/rule_templates: + - workflow + /v1/projects/{project_name}/workflows/{workflow_name}/: get: - description: get all global rule template - operationId: getRuleTemplateListV1 + deprecated: true + description: get workflow detail + operationId: getWorkflowV1 parameters: - - description: page index - in: query - name: page_index + - description: workflow name + in: path + name: workflow_name required: true - type: integer - - description: size of per page - in: query - name: page_size + type: string + - description: project name + in: path + name: project_name required: true - type: integer + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetRuleTemplatesResV1' + $ref: '#/definitions/v1.GetWorkflowResV1' security: - ApiKeyAuth: [] - summary: 全局规则模板列表 + summary: 获取工单详情 tags: - - rule_template - post: + - workflow + patch: consumes: - application/json - description: create a global rule template - operationId: createRuleTemplateV1 + deprecated: true + description: update workflow when it is rejected to creator. + operationId: updateWorkflowV1 parameters: - - description: add rule template request + - description: workflow name + in: path + name: workflow_name + required: true + type: string + - description: project name + in: path + name: project_name + required: true + type: string + - description: update workflow request in: body - name: req + name: instance required: true schema: - $ref: '#/definitions/v1.CreateRuleTemplateReqV1' + $ref: '#/definitions/v1.UpdateWorkflowReqV1' + produces: + - application/json responses: "200": description: OK @@ -9682,17 +6390,23 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 添加全局规则模板 + summary: 更新工单(驳回后才可更新) tags: - - rule_template - /v1/rule_templates/{rule_template_name}/: - delete: - description: delete global rule template - operationId: deleteRuleTemplateV1 + - workflow + /v1/projects/{project_name}/workflows/{workflow_name}/cancel: + post: + deprecated: true + description: cancel workflow + operationId: cancelWorkflowV1 parameters: - - description: rule template name + - description: project name in: path - name: rule_template_name + name: project_name + required: true + type: string + - description: workflow name + in: path + name: workflow_name required: true type: string responses: @@ -9702,43 +6416,30 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 删除全局规则模板 + summary: 审批关闭(中止) tags: - - rule_template - get: - description: get global rule template - operationId: getRuleTemplateV1 + - workflow + /v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/approve: + post: + deprecated: true + description: approve workflow + operationId: approveWorkflowV1 parameters: - - description: rule template name + - description: workflow name in: path - name: rule_template_name + name: workflow_name required: true type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetRuleTemplateResV1' - security: - - ApiKeyAuth: [] - summary: 获取全局规则模板信息 - tags: - - rule_template - patch: - description: update global rule template - operationId: updateRuleTemplateV1 - parameters: - - description: rule template name + - description: workflow step id in: path - name: rule_template_name + name: workflow_step_id required: true type: string - - description: update rule template request - in: body - name: req + - description: project name + in: path + name: project_name required: true - schema: - $ref: '#/definitions/v1.UpdateRuleTemplateReqV1' + type: string responses: "200": description: OK @@ -9746,27 +6447,36 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 更新全局规则模板 + summary: 审批通过 tags: - - rule_template - /v1/rule_templates/{rule_template_name}/clone: + - workflow + /v1/projects/{project_name}/workflows/{workflow_name}/steps/{workflow_step_id}/reject: post: - consumes: - - application/json - description: clone a rule template - operationId: CloneRuleTemplateV1 + deprecated: true + description: reject workflow + operationId: rejectWorkflowV1 parameters: - - description: rule template name + - description: workflow name in: path - name: rule_template_name + name: workflow_name required: true type: string - - description: clone rule template request + - description: project name + in: path + name: project_name + required: true + type: string + - description: workflow step id + in: path + name: workflow_step_id + required: true + type: string + - description: workflow approve request in: body - name: req + name: workflow_approve required: true schema: - $ref: '#/definitions/v1.CloneRuleTemplateReqV1' + $ref: '#/definitions/v1.RejectWorkflowReqV1' responses: "200": description: OK @@ -9774,432 +6484,522 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 克隆全局规则模板 + summary: 审批驳回 tags: - - rule_template - /v1/rule_templates/{rule_template_name}/export: + - workflow + /v1/projects/{project_name}/workflows/{workflow_name}/tasks: get: - description: export rule template - operationId: exportRuleTemplateV1 + deprecated: true + description: get summary of workflow instance tasks + operationId: getSummaryOfInstanceTasksV1 parameters: - - description: rule template name + - description: workflow name in: path - name: rule_template_name + name: workflow_name + required: true + type: string + - description: project name + in: path + name: project_name required: true type: string responses: "200": - description: sqle rule template file + description: OK schema: - type: file + $ref: '#/definitions/v1.GetWorkflowTasksResV1' security: - ApiKeyAuth: [] - summary: 导出全局规则模板 + summary: 获取工单数据源任务概览 tags: - - rule_template - /v1/rule_templates/parse: + - workflow + /v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/execute: post: - consumes: - - multipart/form-data - description: parse rule template - operationId: importProjectRuleTemplateV1 + deprecated: true + description: execute one task on workflow + operationId: executeOneTaskOnWorkflowV1 parameters: - - description: SQLE rule template file - in: formData - name: rule_template_file + - description: workflow name + in: path + name: workflow_name required: true - type: file + type: string + - description: project name + in: path + name: project_name + required: true + type: string + - description: task id + in: path + name: task_id + required: true + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.ParseProjectRuleTemplateFileResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 解析规则模板文件 + summary: 工单提交单个数据源上线 tags: - - rule_template - /v1/rules: - get: - description: get all rule template - operationId: getRuleListV1 + - workflow + /v1/projects/{project_name}/workflows/{workflow_name}/tasks/{task_id}/schedule: + put: + consumes: + - application/json + deprecated: true + description: update workflow schedule. + operationId: updateWorkflowScheduleV1 parameters: - - description: filter db type - in: query - name: filter_db_type + - description: workflow name + in: path + name: workflow_name + required: true type: string - - description: filter global rule template name - in: query - name: filter_global_rule_template_name + - description: task id + in: path + name: task_id + required: true type: string - - description: filter rule name list - in: query - name: filter_rule_names + - description: project name + in: path + name: project_name + required: true type: string + - description: update workflow schedule request + in: body + name: instance + required: true + schema: + $ref: '#/definitions/v1.UpdateWorkflowScheduleReqV1' + produces: + - application/json responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetRulesResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 规则列表 + summary: 设置工单数据源定时上线时间(设置为空则代表取消定时时间,需要SQL审核流程都通过后才可以设置) tags: - - rule_template - /v1/sql_analysis: - get: - description: Direct get sql analysis result - operationId: directGetSQLAnalysisV1 + - workflow + /v1/projects/{project_name}/workflows/{workflow_name}/tasks/execute: + post: + deprecated: true + description: execute tasks on workflow + operationId: executeTasksOnWorkflowV1 parameters: - - description: project name - in: query - name: project_name + - description: workflow name + in: path + name: workflow_name required: true type: string - - description: instance name - in: query - name: instance_name + - description: project name + in: path + name: project_name required: true type: string - - description: schema name - in: query - name: schema_name - type: string - - description: sql - in: query - name: sql - type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.DirectGetSQLAnalysisResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 直接获取SQL分析结果 + summary: 多数据源批量上线 tags: - - sql_analysis - /v1/sql_audit: + - workflow + /v1/projects/{project_name}/workflows/cancel: post: deprecated: true - description: Direct audit sql - operationId: directAuditV1 + description: batch cancel workflows + operationId: batchCancelWorkflowsV1 parameters: - - description: sqls that should be audited + - description: project name + in: path + name: project_name + required: true + type: string + - description: batch cancel workflows request in: body - name: req + name: BatchCancelWorkflowsReqV1 required: true schema: - $ref: '#/definitions/v1.DirectAuditReqV1' + $ref: '#/definitions/v1.BatchCancelWorkflowsReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.DirectAuditResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 直接审核SQL + summary: 批量取消工单 tags: - - sql_audit - /v1/static/instance_logo: - get: - description: get instance type logo - operationId: getInstanceTypeLogo + - workflow + /v1/projects/{project_name}/workflows/complete: + post: + deprecated: true + description: this api will directly change the work order status to finished + without real online operation + operationId: batchCompleteWorkflowsV1 parameters: - - description: instance type - in: query - name: instance_type + - description: project name + in: path + name: project_name required: true type: string + - description: batch complete workflows request + in: body + name: data + required: true + schema: + $ref: '#/definitions/v1.BatchCompleteWorkflowsReqV1' responses: "200": - description: get instance type logo + description: OK schema: - type: file + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取实例类型logo + summary: 批量完成工单 tags: - - instance - /v1/static/logo: + - workflow + /v1/projects/{project_name}/workflows/exports: get: - description: get logo - operationId: getLogo + description: export workflow + operationId: exportWorkflowV1 parameters: - - description: timestamp + - description: filter subject in: query - name: timestamp + name: filter_subject type: string - responses: - "200": - description: get logo - schema: - type: file - summary: 获取logo - tags: - - configuration - /v1/statistic/instances/sql_average_execution_time: - get: - description: get average execution time of sql - operationId: getSqlAverageExecutionTimeV1 - parameters: - - description: the limit of result item number + - description: fuzzy search by workflow description in: query - name: limit + name: fuzzy_search_workflow_desc + type: string + - description: filter create time from + in: query + name: filter_create_time_from + type: string + - description: filter create time to + in: query + name: filter_create_time_to + type: string + - description: filter_task_execute_start_time_from + in: query + name: filter_task_execute_start_time_from + type: string + - description: filter_task_execute_start_time_to + in: query + name: filter_task_execute_start_time_to + type: string + - description: filter create user id + in: query + name: filter_create_user_id + type: string + - description: filter workflow status + enum: + - wait_for_audit + - wait_for_execution + - rejected + - executing + - canceled + - exec_failed + - finished + in: query + name: filter_status + type: string + - description: filter current step assignee user id + in: query + name: filter_current_step_assignee_user_id + type: string + - description: filter instance name + in: query + name: filter_task_instance_name + type: string + - description: project name + in: path + name: project_name required: true - type: integer + type: string + - description: fuzzy matching subject/workflow_id/desc + in: query + name: fuzzy_keyword + type: string responses: "200": - description: OK + description: export workflow schema: - $ref: '#/definitions/v1.GetSqlAverageExecutionTimeResV1' + type: file security: - ApiKeyAuth: [] - summary: 获取sql上线平均耗时,按平均耗时降序排列 + summary: 导出工单 tags: - - statistic - /v1/statistic/instances/sql_execution_fail_percent: + - workflow + /v1/rule_knowledge/db_types/{db_type}/custom_rules/{rule_name}/: get: - description: get sql execution fail percent - operationId: getSqlExecutionFailPercentV1 + description: get custom rule knowledge + operationId: getCustomRuleKnowledgeV1 parameters: - - description: the limit of result item number - in: query - name: limit + - description: rule name + in: path + name: rule_name required: true - type: integer - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetSqlExecutionFailPercentResV1' - security: - - ApiKeyAuth: [] - summary: 获取SQL上线失败率,按失败率降序排列 - tags: - - statistic - /v1/statistic/instances/type_percent: - get: - description: get database instances' types percent - operationId: getInstancesTypePercentV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetInstancesTypePercentResV1' - security: - - ApiKeyAuth: [] - summary: 获取数据源类型百分比 - tags: - - statistic - /v1/statistic/license/usage: - get: - description: get usage of license - operationId: getLicenseUsageV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetLicenseUsageResV1' - security: - - ApiKeyAuth: [] - summary: 获取License使用情况 - tags: - - statistic - /v1/statistic/workflows/audit_pass_percent: - get: - description: get workflow audit pass percent - operationId: getWorkflowAuditPassPercentV1 - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetWorkflowAuditPassPercentResV1' - security: - - ApiKeyAuth: [] - summary: 获取工单审核通过率 - tags: - - statistic - /v1/statistic/workflows/counts: - get: - description: get workflow counts - operationId: getWorkflowCountV1 + type: string + - description: db type of rule + in: path + name: db_type + required: true + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowCountsResV1' - security: - - ApiKeyAuth: [] - summary: 获取工单数量统计数据 - tags: - - statistic - /v1/statistic/workflows/duration_of_waiting_for_audit: - get: - description: get duration from workflow being created to audited - operationId: getWorkflowDurationOfWaitingForAuditV1 + $ref: '#/definitions/v1.GetRuleKnowledgeResV1' + security: + - ApiKeyAuth: [] + summary: 查看自定义规则知识库 + tags: + - rule_template + patch: + description: update custom rule knowledge + operationId: updateCustomRuleKnowledge + parameters: + - description: rule name + in: path + name: rule_name + required: true + type: string + - description: db type of rule + in: path + name: db_type + required: true + type: string + - description: update rule knowledge + in: body + name: req + required: true + schema: + $ref: '#/definitions/v1.UpdateRuleKnowledgeReq' responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowDurationOfWaitingForAuditResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取工单从创建到审核结束的平均时长 + summary: 更新自定义规则知识库 tags: - - statistic - /v1/statistic/workflows/duration_of_waiting_for_execution: + - rule_template + /v1/rule_knowledge/db_types/{db_type}/rules/{rule_name}/: get: - deprecated: true - description: get duration from workflow being created to executed - operationId: getWorkflowDurationOfWaitingForExecutionV1 + description: get rule knowledge + operationId: getRuleKnowledgeV1 + parameters: + - description: rule name + in: path + name: rule_name + required: true + type: string + - description: db type of rule + in: path + name: db_type + required: true + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowDurationOfWaitingForExecutionResV1' + $ref: '#/definitions/v1.GetRuleKnowledgeResV1' security: - ApiKeyAuth: [] - summary: 获取工单各从审核完毕到执行上线的平均时长 + summary: 查看规则知识库 tags: - - statistic - /v1/statistic/workflows/each_day_counts: - get: - description: get counts of created workflow each day - operationId: getWorkflowCreatedCountEachDayV1 + - rule_template + patch: + description: update rule knowledge + operationId: updateRuleKnowledge parameters: - - description: filter date from.(format:yyyy-mm-dd) - in: query - name: filter_date_from + - description: rule name + in: path + name: rule_name required: true type: string - - description: filter date to.(format:yyyy-mm-dd) - in: query - name: filter_date_to + - description: db type of rule + in: path + name: db_type required: true type: string + - description: update rule knowledge + in: body + name: req + required: true + schema: + $ref: '#/definitions/v1.UpdateRuleKnowledgeReq' responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowCreatedCountsEachDayResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取每天工单创建数量 + summary: 更新规则知识库 tags: - - statistic - /v1/statistic/workflows/instance_type_percent: + - rule_template + /v1/rule_template_tips: get: - description: get workflows percent counted by instance type - operationId: getWorkflowPercentCountedByInstanceTypeV1 + description: get global rule template tips + operationId: getRuleTemplateTipsV1 + parameters: + - description: filter db type + in: query + name: filter_db_type + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowPercentCountedByInstanceTypeResV1' + $ref: '#/definitions/v1.GetRuleTemplateTipsResV1' security: - ApiKeyAuth: [] - summary: 获取按数据源类型统计的工单百分比 + summary: 获取全局规则模板提示 tags: - - statistic - /v1/statistic/workflows/pass_percent: + - rule_template + /v1/rule_templates: get: - deprecated: true - description: get workflow pass percent - operationId: getWorkflowPassPercentV1 + description: get all global rule template + operationId: getRuleTemplateListV1 + parameters: + - description: page index + in: query + name: page_index + required: true + type: integer + - description: size of per page + in: query + name: page_size + required: true + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowPassPercentResV1' + $ref: '#/definitions/v1.GetRuleTemplatesResV1' security: - ApiKeyAuth: [] - summary: 获取工单通过率 + summary: 全局规则模板列表 tags: - - statistic - /v1/statistic/workflows/rejected_percent_group_by_creator: - get: - description: get workflows rejected percent group by creator. The result will - be sorted by rejected percent in descending order - operationId: getWorkflowRejectedPercentGroupByCreatorV1 + - rule_template + post: + consumes: + - application/json + description: create a global rule template + operationId: createRuleTemplateV1 parameters: - - description: the limit of result item number - in: query - name: limit + - description: add rule template request + in: body + name: req required: true - type: integer + schema: + $ref: '#/definitions/v1.CreateRuleTemplateReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowRejectedPercentGroupByCreatorResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取各个用户提交的工单驳回率,按驳回率降序排列 + summary: 添加全局规则模板 tags: - - statistic - /v1/statistic/workflows/rejected_percent_group_by_instance: - get: - deprecated: true - description: get workflow rejected percent group by instance. The result will - be sorted by rejected percent in descending order - operationId: getWorkflowRejectedPercentGroupByInstanceV1 + - rule_template + /v1/rule_templates/{rule_template_name}/: + delete: + description: delete global rule template + operationId: deleteRuleTemplateV1 parameters: - - description: the limit of result item number - in: query - name: limit + - description: rule template name + in: path + name: rule_template_name required: true - type: integer + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowRejectedPercentGroupByInstanceResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取各个数据源相关的工单驳回率,按驳回率降序排列 + summary: 删除全局规则模板 tags: - - statistic - /v1/statistic/workflows/status_count: + - rule_template get: - description: get count of workflow status - operationId: getWorkflowStatusCountV1 + description: get global rule template + operationId: getRuleTemplateV1 + parameters: + - description: rule template name + in: path + name: rule_template_name + required: true + type: string + - description: fuzzy rule,keyword for desc and annotation + in: query + name: fuzzy_keyword_rule + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetWorkflowStatusCountResV1' + $ref: '#/definitions/v1.GetRuleTemplateResV1' security: - ApiKeyAuth: [] - summary: 获取各种状态工单的数量 + summary: 获取全局规则模板信息 tags: - - statistic - /v1/sync_instances: - get: - description: get sync instance task list - operationId: GetSyncInstanceTaskList + - rule_template + patch: + description: update global rule template + operationId: updateRuleTemplateV1 + parameters: + - description: rule template name + in: path + name: rule_template_name + required: true + type: string + - description: update rule template request + in: body + name: req + required: true + schema: + $ref: '#/definitions/v1.UpdateRuleTemplateReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetSyncInstanceTaskListResV1' + $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 获取同步实例任务列表 + summary: 更新全局规则模板 tags: - - sync_instance + - rule_template + /v1/rule_templates/{rule_template_name}/clone: post: consumes: - application/json - description: create sync instance task - operationId: createSyncInstanceTaskV1 + description: clone a rule template + operationId: CloneRuleTemplateV1 parameters: - - description: create sync instance task request + - description: rule template name + in: path + name: rule_template_name + required: true + type: string + - description: clone rule template request in: body - name: sync_task + name: req required: true schema: - $ref: '#/definitions/v1.CreateSyncInstanceTaskReqV1' + $ref: '#/definitions/v1.CloneRuleTemplateReqV1' responses: "200": description: OK @@ -10207,621 +7007,588 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 创建同步实例任务 + summary: 克隆全局规则模板 tags: - - sync_instance - /v1/sync_instances/{task_id}/: - delete: - description: delete sync instance task - operationId: deleteSyncInstanceTaskV1 + - rule_template + /v1/rule_templates/{rule_template_name}/export: + get: + description: export rule template + operationId: exportRuleTemplateV1 parameters: - - description: sync task id + - description: rule template name in: path - name: task_id + name: rule_template_name required: true type: string + responses: + "200": + description: sqle rule template file + schema: + type: file + security: + - ApiKeyAuth: [] + summary: 导出全局规则模板 + tags: + - rule_template + /v1/rule_templates/parse: + post: + consumes: + - multipart/form-data + description: parse rule template + operationId: importProjectRuleTemplateV1 + parameters: + - description: SQLE rule template file + in: formData + name: rule_template_file + required: true + type: file responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.ParseProjectRuleTemplateFileResV1' security: - ApiKeyAuth: [] - summary: 删除同步实例任务 + summary: 解析规则模板文件 tags: - - sync_instance + - rule_template + /v1/rules: get: - description: get sync task detail - operationId: GetSyncInstanceTask + description: get all rule template + operationId: getRuleListV1 parameters: - - description: sync task id - in: path - name: task_id - required: true + - description: filter db type + in: query + name: filter_db_type + type: string + - description: fuzzy rule,keyword for desc and annotation + in: query + name: fuzzy_keyword_rule + type: string + - description: filter global rule template name + in: query + name: filter_global_rule_template_name + type: string + - description: filter rule name list + in: query + name: filter_rule_names type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetSyncInstanceTaskResV1' + $ref: '#/definitions/v1.GetRulesResV1' security: - ApiKeyAuth: [] - summary: 获取同步任务详情 + summary: 规则列表 tags: - - sync_instance - patch: - description: update sync instance task - operationId: updateSyncInstanceTaskV1 + - rule_template + /v1/sql_analysis: + get: + description: Direct get sql analysis result + operationId: directGetSQLAnalysisV1 parameters: - - description: sync task id - in: path - name: task_id + - description: project name + in: query + name: project_name required: true type: string - - description: update sync instance request - in: body - name: sync_task + - description: instance name + in: query + name: instance_name required: true - schema: - $ref: '#/definitions/v1.UpdateSyncInstanceTaskReqV1' + type: string + - description: schema name + in: query + name: schema_name + type: string + - description: sql + in: query + name: sql + type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.DirectGetSQLAnalysisResV1' security: - ApiKeyAuth: [] - summary: 更新同步实例任务 + summary: 直接获取SQL分析结果 tags: - - sync_instance - /v1/sync_instances/{task_id}/trigger: + - sql_analysis + /v1/sql_audit: post: - description: trigger sync instance - operationId: triggerSyncInstanceV1 + deprecated: true + description: Direct audit sql + operationId: directAuditV1 parameters: - - description: sync task id - in: path - name: task_id + - description: sqls that should be audited + in: body + name: req required: true - type: string + schema: + $ref: '#/definitions/v1.DirectAuditReqV1' responses: "200": description: OK schema: - $ref: '#/definitions/v1.TriggerSyncInstanceResV1' + $ref: '#/definitions/v1.DirectAuditResV1' security: - ApiKeyAuth: [] - summary: 触发同步实例 + summary: 直接审核SQL tags: - - sync_instance - /v1/sync_instances/source_tips: + - sql_audit + /v1/statistic/instances/sql_average_execution_time: get: - description: get sync task tips - operationId: GetSyncTaskSourceTips - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetSyncTaskSourceTipsResV1' - security: - - ApiKeyAuth: [] - summary: 获取同步任务提示 - tags: - - sync_instance - /v1/task_groups/audit: - post: - consumes: - - multipart/form-data - description: |- - audit task group. - 1. formData[sql]: sql content; - 2. file[input_sql_file]: it is a sql file; - 3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it. - 4. file[input_zip_file]: it is zip file, sql will be parsed from it. - operationId: auditTaskGroupIdV1 + description: get average execution time of sql + operationId: getSqlAverageExecutionTimeV1 parameters: - - description: group id of tasks - in: formData - name: task_group_id + - description: the limit of result item number + in: query + name: limit required: true type: integer - - description: sqls for audit - in: formData - name: sql - type: string - - description: input SQL file - in: formData - name: input_sql_file - type: file - - description: input mybatis XML file - in: formData - name: input_mybatis_xml_file - type: file - - description: input ZIP file - in: formData - name: input_zip_file - type: file - produces: - - application/json responses: "200": description: OK schema: - $ref: '#/definitions/v1.AuditTaskGroupResV1' + $ref: '#/definitions/v1.GetSqlAverageExecutionTimeResV1' security: - ApiKeyAuth: [] - summary: 审核任务组 + summary: 获取sql上线平均耗时,按平均耗时降序排列 tags: - - task - /v1/tasks/audits/{task_id}/: + - statistic + /v1/statistic/instances/sql_execution_fail_percent: get: - description: get task - operationId: getAuditTaskV1 + description: get sql execution fail percent + operationId: getSqlExecutionFailPercentV1 parameters: - - description: task id - in: path - name: task_id + - description: the limit of result item number + in: query + name: limit required: true - type: string + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditTaskResV1' + $ref: '#/definitions/v1.GetSqlExecutionFailPercentResV1' security: - ApiKeyAuth: [] - summary: 获取Sql扫描任务信息 + summary: 获取SQL上线失败率,按失败率降序排列 tags: - - task - /v1/tasks/audits/{task_id}/sql_content: + - statistic + /v1/statistic/instances/type_percent: get: - description: get SQL content for the audit task - operationId: getAuditTaskSQLContentV1 - parameters: - - description: task id - in: path - name: task_id - required: true - type: string + description: get database instances' types percent + operationId: getInstancesTypePercentV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditTaskSQLContentResV1' + $ref: '#/definitions/v1.GetInstancesTypePercentResV1' security: - ApiKeyAuth: [] - summary: 获取指定扫描任务的SQL内容 + summary: 获取数据源类型百分比 tags: - - task - /v1/tasks/audits/{task_id}/sql_file: + - statistic + /v1/statistic/license/usage: get: - description: download SQL file for the audit task - operationId: downloadAuditTaskSQLFileV1 - parameters: - - description: task id - in: path - name: task_id - required: true - type: string + description: get usage of license + operationId: getLicenseUsageV1 responses: "200": - description: sql file + description: OK schema: - type: file + $ref: '#/definitions/v1.GetLicenseUsageResV1' security: - ApiKeyAuth: [] - summary: 下载指定扫描任务的SQL文件 + summary: 获取License使用情况 tags: - - task - /v1/tasks/audits/{task_id}/sql_report: + - statistic + /v1/statistic/workflows/audit_pass_percent: get: - description: download report file of all SQLs information belong to the specified - audit task - operationId: downloadAuditTaskSQLReportV1 - parameters: - - description: task id - in: path - name: task_id - required: true - type: string - - description: select unique (fingerprint and audit result) for task sql - in: query - name: no_duplicate - type: boolean + description: get workflow audit pass percent + operationId: getWorkflowAuditPassPercentV1 responses: "200": - description: sql report csv file + description: OK schema: - type: file - security: - - ApiKeyAuth: [] - summary: 下载指定扫描任务的SQLs信息报告 - tags: - - task - /v1/tasks/audits/{task_id}/sqls: - get: - description: get information of all SQLs belong to the specified audit task - operationId: getAuditTaskSQLsV1 - parameters: - - description: task id - in: path - name: task_id - required: true - type: string - - description: 'filter: exec status of task sql' - enum: - - initialized - - doing - - succeeded - - failed - - manually_executed - in: query - name: filter_exec_status - type: string - - description: 'filter: audit status of task sql' - enum: - - initialized - - doing - - finished - in: query - name: filter_audit_status - type: string - - description: 'filter: audit level of task sql' - enum: - - normal - - notice - - warn - - error - in: query - name: filter_audit_level - type: string - - description: select unique (fingerprint and audit result) for task sql - in: query - name: no_duplicate - type: boolean - - description: page index - in: query - name: page_index - required: true - type: string - - description: page size - in: query - name: page_size - required: true - type: string + $ref: '#/definitions/v1.GetWorkflowAuditPassPercentResV1' + security: + - ApiKeyAuth: [] + summary: 获取工单审核通过率 + tags: + - statistic + /v1/statistic/workflows/counts: + get: + description: get workflow counts + operationId: getWorkflowCountV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetAuditTaskSQLsResV1' + $ref: '#/definitions/v1.GetWorkflowCountsResV1' security: - ApiKeyAuth: [] - summary: 获取指定扫描任务的SQLs信息 + summary: 获取工单数量统计数据 tags: - - task - /v1/tasks/audits/{task_id}/sqls/{number}: - patch: - consumes: - - application/json - description: modify the relevant information of a certain SQL in the audit task - operationId: updateAuditTaskSQLsV1 - parameters: - - description: task id - in: path - name: task_id - required: true - type: string - - description: sql number - in: path - name: number - required: true - type: string - - description: modify the relevant information of a certain SQL in the audit - task - in: body - name: audit_plan - required: true - schema: - $ref: '#/definitions/v1.UpdateAuditTaskSQLsReqV1' + - statistic + /v1/statistic/workflows/duration_of_waiting_for_audit: + get: + description: get duration from workflow being created to audited + operationId: getWorkflowDurationOfWaitingForAuditV1 responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetWorkflowDurationOfWaitingForAuditResV1' security: - ApiKeyAuth: [] - summary: 修改扫描任务中某条SQL的相关信息 + summary: 获取工单从创建到审核结束的平均时长 tags: - - task - /v1/tasks/audits/{task_id}/sqls/{number}/analysis: + - statistic + /v1/statistic/workflows/duration_of_waiting_for_execution: get: - description: get SQL explain and related table metadata for analysis - operationId: getTaskAnalysisData + deprecated: true + description: get duration from workflow being created to executed + operationId: getWorkflowDurationOfWaitingForExecutionV1 + responses: + "200": + description: OK + schema: + $ref: '#/definitions/v1.GetWorkflowDurationOfWaitingForExecutionResV1' + security: + - ApiKeyAuth: [] + summary: 获取工单各从审核完毕到执行上线的平均时长 + tags: + - statistic + /v1/statistic/workflows/each_day_counts: + get: + description: get counts of created workflow each day + operationId: getWorkflowCreatedCountEachDayV1 parameters: - - description: task id - in: path - name: task_id + - description: filter date from.(format:yyyy-mm-dd) + in: query + name: filter_date_from required: true type: string - - description: sql number - in: path - name: number + - description: filter date to.(format:yyyy-mm-dd) + in: query + name: filter_date_to required: true - type: integer + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetTaskAnalysisDataResV1' + $ref: '#/definitions/v1.GetWorkflowCreatedCountsEachDayResV1' security: - ApiKeyAuth: [] - summary: 获取task相关的SQL执行计划和表元数据 + summary: 获取每天工单创建数量 tags: - - task - /v1/user: + - statistic + /v1/statistic/workflows/instance_type_percent: get: - description: get current user info - operationId: getCurrentUserV1 + description: get workflows percent counted by instance type + operationId: getWorkflowPercentCountedByInstanceTypeV1 responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetUserDetailResV1' + $ref: '#/definitions/v1.GetWorkflowPercentCountedByInstanceTypeResV1' security: - ApiKeyAuth: [] - summary: 获取当前用户信息 + summary: 获取按数据源类型统计的工单百分比 tags: - - user - patch: - consumes: - - application/json - description: update current user - operationId: updateCurrentUserV1 - parameters: - - description: update user - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateCurrentUserReqV1' - produces: - - application/json + - statistic + /v1/statistic/workflows/pass_percent: + get: + deprecated: true + description: get workflow pass percent + operationId: getWorkflowPassPercentV1 responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetWorkflowPassPercentResV1' security: - ApiKeyAuth: [] - summary: 更新个人信息 + summary: 获取工单通过率 tags: - - user - /v1/user/password: - put: - consumes: - - application/json - description: update current user's password - operationId: UpdateCurrentUserPasswordV1 + - statistic + /v1/statistic/workflows/rejected_percent_group_by_creator: + get: + description: get workflows rejected percent group by creator. The result will + be sorted by rejected percent in descending order + operationId: getWorkflowRejectedPercentGroupByCreatorV1 parameters: - - description: update user's password - in: body - name: instance + - description: the limit of result item number + in: query + name: limit required: true - schema: - $ref: '#/definitions/v1.UpdateCurrentUserPasswordReqV1' - produces: - - application/json + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetWorkflowRejectedPercentGroupByCreatorResV1' security: - ApiKeyAuth: [] - summary: 用户修改密码 + summary: 获取各个用户提交的工单驳回率,按驳回率降序排列 tags: - - user - /v1/user_group_tips: + - statistic + /v1/statistic/workflows/rejected_percent_group_by_instance: get: - description: get user group tip list - operationId: getUserGroupTipListV1 + deprecated: true + description: get workflow rejected percent group by instance. The result will + be sorted by rejected percent in descending order + operationId: getWorkflowRejectedPercentGroupByInstanceV1 parameters: - - description: project name + - description: the limit of result item number in: query - name: filter_project - type: string + name: limit + required: true + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetUserGroupTipsResV1' + $ref: '#/definitions/v1.GetWorkflowRejectedPercentGroupByInstanceResV1' security: - ApiKeyAuth: [] - summary: 获取用户组提示列表 + summary: 获取各个数据源相关的工单驳回率,按驳回率降序排列 tags: - - user_group - /v1/user_groups: + - statistic + /v1/statistic/workflows/status_count: get: - description: get user group info list - operationId: getUserGroupListV1 + description: get count of workflow status + operationId: getWorkflowStatusCountV1 + responses: + "200": + description: OK + schema: + $ref: '#/definitions/v1.GetWorkflowStatusCountResV1' + security: + - ApiKeyAuth: [] + summary: 获取各种状态工单的数量 + tags: + - statistic + /v1/task_groups/audit: + post: + consumes: + - multipart/form-data + description: |- + audit task group. + 1. formData[sql]: sql content; + 2. file[input_sql_file]: it is a sql file; + 3. file[input_mybatis_xml_file]: it is mybatis xml file, sql will be parsed from it. + 4. file[input_zip_file]: it is zip file, sql will be parsed from it. + operationId: auditTaskGroupIdV1 parameters: - - description: filter user group name - in: query - name: filter_user_group_name - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size + - description: group id of tasks + in: formData + name: task_group_id required: true type: integer + - description: sqls for audit + in: formData + name: sql + type: string + - description: input SQL file + in: formData + name: input_sql_file + type: file + - description: input mybatis XML file + in: formData + name: input_mybatis_xml_file + type: file + - description: input ZIP file + in: formData + name: input_zip_file + type: file produces: - application/json responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetUserGroupsResV1' + $ref: '#/definitions/v1.AuditTaskGroupResV1' security: - ApiKeyAuth: [] - summary: 获取用户组列表 + summary: 审核任务组 tags: - - user_group - post: - consumes: - - application/json - description: create user group - operationId: CreateUserGroupV1 + - task + /v1/tasks/audits/{task_id}/: + get: + description: get task + operationId: getAuditTaskV1 parameters: - - description: create user group - in: body - name: instance + - description: task id + in: path + name: task_id required: true - schema: - $ref: '#/definitions/v1.CreateUserGroupReqV1' - produces: - - application/json + type: string responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetAuditTaskResV1' security: - ApiKeyAuth: [] - summary: 创建用户组 + summary: 获取Sql扫描任务信息 tags: - - user_group - /v1/user_groups/{user_group_name}/: - delete: - description: delete user group - operationId: deleteUserGroupV1 + - task + /v1/tasks/audits/{task_id}/sql_content: + get: + description: get SQL content for the audit task + operationId: getAuditTaskSQLContentV1 + parameters: + - description: task id + in: path + name: task_id + required: true + type: string + responses: + "200": + description: OK + schema: + $ref: '#/definitions/v1.GetAuditTaskSQLContentResV1' + security: + - ApiKeyAuth: [] + summary: 获取指定扫描任务的SQL内容 + tags: + - task + /v1/tasks/audits/{task_id}/sql_file: + get: + description: download SQL file for the audit task + operationId: downloadAuditTaskSQLFileV1 parameters: - - description: user_group_name + - description: task id in: path - name: user_group_name + name: task_id required: true type: string responses: "200": - description: OK + description: sql file schema: - $ref: '#/definitions/controller.BaseRes' + type: file security: - ApiKeyAuth: [] - summary: 删除用户组 + summary: 下载指定扫描任务的SQL文件 tags: - - user_group - patch: - description: update user group - operationId: updateUserGroupV1 + - task + /v1/tasks/audits/{task_id}/sql_report: + get: + description: download report file of all SQLs information belong to the specified + audit task + operationId: downloadAuditTaskSQLReportV1 parameters: - - description: user_group_name + - description: task id in: path - name: user_group_name + name: task_id required: true type: string - - description: update user group - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.PatchUserGroupReqV1' + - description: select unique (fingerprint and audit result) for task sql + in: query + name: no_duplicate + type: boolean responses: "200": - description: OK + description: sql report csv file schema: - $ref: '#/definitions/controller.BaseRes' + type: file security: - ApiKeyAuth: [] - summary: 更新用户组 + summary: 下载指定扫描任务的SQLs信息报告 tags: - - user_group - /v1/user_tips: + - task + /v1/tasks/audits/{task_id}/sqls: get: - description: get user tip list - operationId: getUserTipListV1 + description: get information of all SQLs belong to the specified audit task + operationId: getAuditTaskSQLsV1 parameters: - - description: project name + - description: task id + in: path + name: task_id + required: true + type: string + - description: 'filter: exec status of task sql' + enum: + - initialized + - doing + - succeeded + - failed + - manually_executed in: query - name: filter_project + name: filter_exec_status type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetUserTipsResV1' - security: - - ApiKeyAuth: [] - summary: 获取用户提示列表 - tags: - - user - /v1/users: - get: - description: get user info list - operationId: getUserListV1 - parameters: - - description: filter user name + - description: 'filter: audit status of task sql' + enum: + - initialized + - doing + - finished + in: query + name: filter_audit_status + type: string + - description: 'filter: audit level of task sql' + enum: + - normal + - notice + - warn + - error in: query - name: filter_user_name + name: filter_audit_level type: string + - description: select unique (fingerprint and audit result) for task sql + in: query + name: no_duplicate + type: boolean - description: page index in: query name: page_index required: true - type: integer - - description: size of per page + type: string + - description: page size in: query name: page_size required: true - type: integer + type: string responses: "200": description: OK schema: - $ref: '#/definitions/v1.GetUsersResV1' + $ref: '#/definitions/v1.GetAuditTaskSQLsResV1' security: - ApiKeyAuth: [] - summary: 获取用户信息列表 + summary: 获取指定扫描任务的SQLs信息 tags: - - user - post: + - task + /v1/tasks/audits/{task_id}/sqls/{number}: + patch: consumes: - application/json - description: create user - operationId: createUserV1 + description: modify the relevant information of a certain SQL in the audit task + operationId: updateAuditTaskSQLsV1 parameters: - - description: create user - in: body - name: instance + - description: task id + in: path + name: task_id required: true - schema: - $ref: '#/definitions/v1.CreateUserReqV1' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 创建用户 - tags: - - user - /v1/users/{user_name}/: - delete: - description: delete user - operationId: deleteUserV1 - parameters: - - description: user name + type: string + - description: sql number in: path - name: user_name + name: number required: true type: string + - description: modify the relevant information of a certain SQL in the audit + task + in: body + name: audit_plan + required: true + schema: + $ref: '#/definitions/v1.UpdateAuditTaskSQLsReqV1' responses: "200": description: OK @@ -10829,85 +7596,52 @@ paths: $ref: '#/definitions/controller.BaseRes' security: - ApiKeyAuth: [] - summary: 删除用户 + summary: 修改扫描任务中某条SQL的相关信息 tags: - - user + - task + /v1/tasks/audits/{task_id}/sqls/{number}/analysis: get: - description: get user info - operationId: getUserV1 + description: get SQL explain and related table metadata for analysis + operationId: getTaskAnalysisData parameters: - - description: user name + - description: task id in: path - name: user_name + name: task_id required: true type: string - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v1.GetUserDetailResV1' - security: - - ApiKeyAuth: [] - summary: 获取用户信息 - tags: - - user - patch: - consumes: - - application/json - description: update user - operationId: updateUserV1 - parameters: - - description: user name + - description: sql number in: path - name: user_name - required: true - type: string - - description: update user - in: body - name: instance + name: number required: true - schema: - $ref: '#/definitions/v1.UpdateUserReqV1' - produces: - - application/json + type: integer responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetTaskAnalysisDataResV1' security: - ApiKeyAuth: [] - summary: 更新用户信息 + summary: 获取task相关的SQL执行计划和表元数据 tags: - - user - /v1/users/{user_name}/password: - patch: - consumes: - - application/json - description: admin modifies the passwords of other users - operationId: UpdateOtherUserPasswordV1 + - task + /v1/user_tips: + get: + description: get user tip list + operationId: getUserTipListV1 parameters: - - description: user name - in: path - name: user_name + - description: project name + in: query + name: filter_project required: true type: string - - description: change user's password - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v1.UpdateOtherUserPasswordReqV1' - produces: - - application/json responses: "200": description: OK schema: - $ref: '#/definitions/controller.BaseRes' + $ref: '#/definitions/v1.GetUserTipsResV1' security: - ApiKeyAuth: [] - summary: admin修改其他用户密码 + summary: 获取用户提示列表 tags: - user /v1/workflows: @@ -10935,9 +7669,9 @@ paths: in: query name: filter_task_execute_start_time_to type: string - - description: filter create user name + - description: filter create user id in: query - name: filter_create_user_name + name: filter_create_user_id type: string - description: filter workflow status enum: @@ -10951,11 +7685,11 @@ paths: in: query name: filter_status type: string - - description: filter current step assignee user name + - description: filter current step assignee user id in: query - name: filter_current_step_assignee_user_name + name: filter_current_step_assignee_user_id type: string - - description: filter instance name + - description: filter instance id in: query name: filter_task_instance_name type: string @@ -11014,25 +7748,6 @@ paths: summary: 获取当前 server 支持的审核类型 tags: - configuration - /v2/login: - post: - description: user login - operationId: loginV2 - parameters: - - description: user login request - in: body - name: user - required: true - schema: - $ref: '#/definitions/v1.UserLoginReqV1' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - summary: 用户登录 - tags: - - user /v2/projects/{project_name}/audit_plans: get: description: get audit plan info list @@ -11216,87 +7931,6 @@ paths: summary: 增量同步SQL到扫描任务 tags: - audit_plan - /v2/projects/{project_name}/instances: - get: - description: get instance info list - operationId: getInstanceListV2 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: filter instance name - in: query - name: filter_instance_name - type: string - - description: filter db type - in: query - name: filter_db_type - type: string - - description: filter db host - in: query - name: filter_db_host - type: string - - description: filter db port - in: query - name: filter_db_port - type: string - - description: filter db user - in: query - name: filter_db_user - type: string - - description: filter rule template name - in: query - name: filter_rule_template_name - type: string - - description: page index - in: query - name: page_index - required: true - type: integer - - description: size of per page - in: query - name: page_size - required: true - type: integer - responses: - "200": - description: OK - schema: - $ref: '#/definitions/v2.GetInstancesResV2' - security: - - ApiKeyAuth: [] - summary: 获取实例信息列表 - tags: - - instance - post: - consumes: - - application/json - description: create a instance - operationId: createInstanceV2 - parameters: - - description: project name - in: path - name: project_name - required: true - type: string - - description: add instance - in: body - name: instance - required: true - schema: - $ref: '#/definitions/v2.CreateInstanceReqV2' - responses: - "200": - description: OK - schema: - $ref: '#/definitions/controller.BaseRes' - security: - - ApiKeyAuth: [] - summary: 添加实例 - tags: - - instance /v2/projects/{project_name}/instances/{instance_name}/: get: description: get instance db diff --git a/sqle/driver/mysql/audit_test.go b/sqle/driver/mysql/audit_test.go index 827ed62907..8070cb7bd1 100644 --- a/sqle/driver/mysql/audit_test.go +++ b/sqle/driver/mysql/audit_test.go @@ -7029,6 +7029,37 @@ func TestMustMatchLeftMostPrefix(t *testing.T) { Sql: `select * from exist_tb_9 where v2 = 1 union select * from exist_tb_8 where v2 = 1`, TriggerRule: false, }, + // select subquery + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_9) t where t.v1 > 1`, + TriggerRule: false, + }, + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_9) t where t.v1 in (1,2,3)`, + TriggerRule: false, + }, + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_9) t left join exist_tb_8 t1 on t.id=t1.id where t1.v1 in (1,2,3)`, + TriggerRule: true, + }, + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_9) t left join exist_tb_8 t1 on t.id=t1.id where t1.v1 > 1`, + TriggerRule: true, + }, + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_8) t left join exist_tb_9 t1 on t.id=t1.id where t1.v3 > 1`, + TriggerRule: false, + }, + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_8) t left join exist_tb_9 t1 on t.id=t1.id where t1.v3 in (1, 2, 3)`, + TriggerRule: false, + }, } rule := rulepkg.RuleHandlerMap[rulepkg.DMLMustMatchLeftMostPrefix].Rule @@ -7282,6 +7313,22 @@ func TestMustUseLeftMostPrefix(t *testing.T) { Sql: `select * from exist_tb_9 where v2 = 1 union select * from exist_tb_8 where v2 = 1`, TriggerRule: true, }, + // select subquery + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_9) t where v3=1`, + TriggerRule: false, + }, + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_8) t left join exist_tb_9 t1 on t.id=t1.id where t1.v3=1`, + TriggerRule: true, + }, + { + Name: "select-subquery", + Sql: `select * from (select * from exist_tb_9) t left join exist_tb_8 t1 on t.id=t1.id where t.v3=1`, + TriggerRule: false, + }, } rule := rulepkg.RuleHandlerMap[rulepkg.DMLMustUseLeftMostPrefix].Rule diff --git a/sqle/driver/mysql/rule/rule.go b/sqle/driver/mysql/rule/rule.go index 87c5dac3b6..071d02ee35 100644 --- a/sqle/driver/mysql/rule/rule.go +++ b/sqle/driver/mysql/rule/rule.go @@ -17,7 +17,6 @@ import ( "github.com/actiontech/sqle/sqle/driver/mysql/util" driverV2 "github.com/actiontech/sqle/sqle/driver/v2" "github.com/actiontech/sqle/sqle/log" - "github.com/actiontech/sqle/sqle/pkg/params" "github.com/actiontech/sqle/sqle/utils" "github.com/pingcap/parser/ast" @@ -297,2134 +296,6 @@ const ( DefaultMultiParamsSecondKeyName = "multi_params_second_key" ) -var RuleHandlers = []RuleHandler{ - // config - { - Rule: driverV2.Rule{ - Name: ConfigDMLRollbackMaxRows, - Desc: "在 DML 语句中预计影响行数超过指定值则不回滚", - Annotation: "大事务回滚,容易影响数据库性能,使得业务发生波动;具体规则阈值可以根据业务需求调整,默认值:1000", - //Value: "1000", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeGlobalConfig, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1000", - Desc: "最大影响行数", - Type: params.ParamTypeInt, - }, - }, - }, - Func: nil, - }, - { - Rule: driverV2.Rule{ - Name: ConfigDDLOSCMinSize, - Desc: "改表时,表空间超过指定大小(MB)审核时输出osc改写建议", - Annotation: "开启该规则后会对大表的DDL语句给出 pt-osc工具的改写建议【需要参考命令进行手工执行,后续会支持自动执行】;直接对大表进行DDL变更时可能会导致长时间锁表问题,影响业务可持续性。具体对大表定义的阈值可以根据业务需求调整,默认值:1024", - //Value: "16", - Level: driverV2.RuleLevelNormal, - Category: RuleTypeGlobalConfig, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1024", - Desc: "表空间大小(MB)", - Type: params.ParamTypeInt, - }, - }, - }, - Func: nil, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckTableSize, - Desc: "不建议对数据量过大的表执行DDL操作", - Annotation: "大表执行DDL,耗时较久且负载较高,长时间占用锁资源,会影响数据库性能;具体规则阈值可以根据业务需求调整,默认值:1024", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1024", - Desc: "表空间大小(MB)", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "执行DDL的表 %v 空间不建议超过 %vMB", - OnlyAuditNotExecutedSQL: true, - Func: checkDDLTableSize, - }, { - Rule: driverV2.Rule{ - Name: DDLCheckIndexTooMany, - Desc: "单字段上的索引数量不建议超过阈值", - Annotation: "单字段上存在过多索引,一般情况下这些索引都是没有存在价值的;相反,还会降低数据增加删除时的性能,特别是对频繁更新的表来说,负面影响更大;具体规则阈值可以根据业务需求调整,默认值:2", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeIndexingConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "2", - Desc: "单字段的索引数最大值", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "字段 %v 上的索引数量不建议超过%v个", - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - Func: checkIndex, - }, - { - Rule: driverV2.Rule{ - Name: ConfigDMLExplainPreCheckEnable, - Desc: "使用EXPLAIN加强预检查能力", - Annotation: "通过 EXPLAIN 的形式将待上线的DML进行SQL是否能正确执行的检查,提前发现语句的错误,提高上线成功率", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeGlobalConfig, - }, - Func: nil, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckRedundantIndex, - Desc: "不建议创建冗余索引", - Annotation: "MySQL需要单独维护重复的索引,冗余索引增加维护成本,并且优化器在优化查询时需要逐个进行代价计算,影响查询性能", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexOptimization, - }, - Message: "%v", - AllowOffline: true, - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - Func: checkIndex, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckTableSize, - Desc: "不建议对数据量过大的表执行DML操作", - Annotation: "DML操作大表,耗时较久且负载较高,容易影响数据库性能;具体规则阈值可以根据业务需求调整,默认值:1024", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1024", - Desc: "表空间大小(MB)", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "执行DML的表 %v 空间不建议超过 %vMB", - Func: checkDMLTableSize, - }, - { - Rule: driverV2.Rule{ - Name: ConfigOptimizeIndexEnabled, - Desc: "索引创建建议", - Annotation: "通过该规则开启索引优化建议,提供两个参数配置来定义索引优化建议的行为。1. 计算列基数阈值:配置当表数据量超过多少行时不再计算列的区分度来排序索引优先级,防止对大表进行操作影响性能;2. 联合索引最大列数:限制联合索引给到的列数最大值,防止给出建议的联合索引不符合其他SQL标准", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeIndexOptimization, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultMultiParamsFirstKeyName, - Value: "1000000", - Desc: "计算列基数阈值", - Type: params.ParamTypeInt, - }, - ¶ms.Param{ - Key: DefaultMultiParamsSecondKeyName, - Value: "3", - Desc: "联合索引最大列数", - Type: params.ParamTypeInt, - }, - }, - }, - }, - - { - Rule: driverV2.Rule{ - Name: ConfigSQLIsExecuted, - Desc: "停用上线审核模式", - Annotation: "启用该规则来兼容事后审核的场景,对于事后采集的DDL 和 DML 语句将不再进行上线校验。例如库表元数据的扫描任务可开启该规则", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeGlobalConfig, - }, - }, - - { - Rule: driverV2.Rule{ - Name: ConfigDDLGhostMinSize, - Desc: "改表时,表空间超过指定大小(MB)时使用gh-ost上线", - Annotation: "开启该规则后会自动对大表的DDL操作使用gh-ost 工具进行在线改表;直接对大表进行DDL变更时可能会导致长时间锁表问题,影响业务可持续性。具体对大表定义的阈值可以根据业务需求调整,默认值:1024", - //Value: "16", - Level: driverV2.RuleLevelNormal, - Category: RuleTypeGlobalConfig, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1024", - Desc: "表空间大小(MB)", - Type: params.ParamTypeInt, - }, - }, - }, - Func: nil, - }, - - // rule - { - Rule: driverV2.Rule{ - Name: DDLCheckPKWithoutIfNotExists, - Desc: "新建表建议加入 IF NOT EXISTS,保证重复执行不报错", - Annotation: "新建表如果表已经存在,不添加IF NOT EXISTS CREATE执行SQL会报错,建议开启此规则,避免SQL实际执行报错", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - Message: "新建表建议加入 IF NOT EXISTS,保证重复执行不报错", - AllowOffline: true, - Func: checkIfNotExist, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckObjectNameLength, - Desc: "表名、列名、索引名的长度不建议超过阈值", - Annotation: "通过配置该规则可以规范指定业务的对象命名长度,具体长度可以自定义设置,默认最大长度:64。是MySQL规定标识符命名最大长度为64字节", - Level: driverV2.RuleLevelError, - Category: RuleTypeNamingConvention, - //Value: "64", - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "64", - Desc: "最大长度(字节)", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "表名、列名、索引名的长度不建议大于%v字节", - AllowOffline: true, - Func: checkNewObjectName, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckObjectNameIsUpperAndLowerLetterMixed, - Desc: "数据库对象命名不建议大小写字母混合", - Annotation: "数据库对象命名规范,不推荐采用大小写混用的形式建议词语之间使用下划线连接,提高代码可读性", - Category: RuleTypeNamingConvention, - Level: driverV2.RuleLevelNotice, - }, - Message: "数据库对象命名不建议大小写字母混合,以下对象命名不规范:%v", - Func: checkIsObjectNameUpperAndLowerLetterMixed, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckPKNotExist, - Desc: "表必须有主键", - Annotation: "主键使数据达到全局唯一,可提高数据检索效率", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexingConvention, - }, - Message: "表必须有主键", - AllowOffline: true, - NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, - Func: checkPrimaryKey, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckPKWithoutAutoIncrement, - Desc: "主键建议使用自增", - Annotation: "自增主键,数字型速度快,而且是增量增长,占用空间小,更快速的做数据插入操作,避免增加维护索引的开销", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexingConvention, - }, - Message: "主键建议使用自增", - AllowOffline: true, - NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, - Func: checkPrimaryKey, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckPKWithoutBigintUnsigned, - Desc: "主键建议使用 BIGINT 无符号类型,即 BIGINT UNSIGNED", - Annotation: "BIGINT UNSIGNED拥有更大的取值范围,建议开启此规则,避免发生溢出", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexingConvention, - }, - Message: "主键建议使用 BIGINT 无符号类型,即 BIGINT UNSIGNED", - AllowOffline: true, - NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, - Func: checkPrimaryKey, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckJoinFieldType, - Desc: "建议JOIN字段类型保持一致", - Annotation: "JOIN字段类型不一致会导致类型不匹配发生隐式准换,建议开启此规则,避免索引失效", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "建议JOIN字段类型保持一致, 否则会导致隐式转换", - AllowOffline: false, - Func: checkJoinFieldType, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckHasJoinCondition, - Desc: "建议连接操作指定连接条件", - Annotation: "指定连接条件可以确保连接操作的正确性和可靠性,如果没有指定连接条件,可能会导致连接失败或连接不正确的情况。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "建议连接操作指定连接条件,JOIN字段后必须有ON条件", - AllowOffline: true, - Func: checkHasJoinCondition, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnCharLength, - Desc: "CHAR长度大于20时,必须使用VARCHAR类型", - Annotation: "VARCHAR是变长字段,存储空间小,可节省存储空间,同时相对较小的字段检索效率显然也要高些", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "CHAR长度大于20时,必须使用VARCHAR类型", - AllowOffline: true, - Func: checkStringType, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckFieldNotNUllMustContainDefaultValue, - Desc: "建议字段约束为NOT NULL时带默认值", - Annotation: "如存在NOT NULL且不带默认值的字段,INSERT时不包含该字段,会导致插入报错", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - }, - Message: "建议字段约束为NOT NULL时带默认值,以下字段不规范:%v", - AllowOffline: true, - Func: checkFieldNotNUllMustContainDefaultValue, - }, - { - Rule: driverV2.Rule{ - Name: DDLDisableFK, - Desc: "禁止使用外键", - Annotation: "外键在高并发场景下性能较差,容易造成死锁,同时不利于后期维护(拆分、迁移)", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexingConvention, - }, - Message: "禁止使用外键", - AllowOffline: true, - Func: checkForeignKey, - }, - { - Rule: driverV2.Rule{ - Name: DDLDisableAlterFieldUseFirstAndAfter, - Desc: "ALTER表字段禁止使用FIRST,AFTER", - Annotation: "FIRST,AFTER 的ALTER操作通过COPY TABLE的方式完成,对业务影响较大", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "ALTER表字段禁止使用FIRST,AFTER", - AllowOffline: true, - Func: disableAlterUseFirstAndAfter, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckCreateTimeColumn, - Desc: "建议建表DDL包含创建时间字段且默认值为CURRENT_TIMESTAMP", - Annotation: "使用CREATE_TIME字段,有利于问题查找跟踪和检索数据,同时避免后期对数据生命周期管理不便 ,默认值为CURRENT_TIMESTAMP可保证时间的准确性", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "CREATE_TIME", - Desc: "创建时间字段名", - Type: params.ParamTypeString, - }, - }, - }, - Message: "建议建表DDL包含%v字段且默认值为CURRENT_TIMESTAMP", - AllowOffline: true, - Func: checkFieldCreateTime, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckIndexCount, - Desc: "索引个数建议不超过阈值", - Annotation: "在表上建立的每个索引都会增加存储开销,索引对于插入、删除、更新操作也会增加处理上的开销,太多与不充分、不正确的索引对性能都毫无益处;具体规则阈值可以根据业务需求调整,默认值:5", - Level: driverV2.RuleLevelNotice, - //Value: "5", - Category: RuleTypeIndexingConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "5", - Desc: "最大索引个数", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "索引个数建议不超过%v个", - AllowOffline: true, - NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - Func: checkIndex, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckUpdateTimeColumn, - Desc: "建表DDL需要包含更新时间字段且默认值为CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", - Annotation: "使用更新时间字段,有利于问题查找跟踪和检索数据,同时避免后期对数据生命周期管理不便 ,默认值为UPDATE_TIME可保证时间的准确性", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "UPDATE_TIME", - Desc: "更新时间字段名", - Type: params.ParamTypeString, - }, - }, - }, - Message: "建表DDL需要包含%v字段且默认值为CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", - AllowOffline: true, - Func: checkFieldUpdateTime, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckCompositeIndexMax, - Desc: "复合索引的列数量不建议超过阈值", - Annotation: "复合索引会根据索引列数创建对应组合的索引,列数越多,创建的索引越多,每个索引都会增加磁盘空间的开销,同时增加索引维护的开销;具体规则阈值可以根据业务需求调整,默认值:3", - Level: driverV2.RuleLevelNotice, - //Value: "3", - Category: RuleTypeIndexingConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "3", - Desc: "最大索引列数量", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "复合索引的列数量不建议超过%v个", - AllowOffline: true, - NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - Func: checkIndex, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckIndexNotNullConstraint, - Desc: "索引字段需要有非空约束", - Annotation: "索引字段上如果没有非空约束,则表记录与索引记录不会完全映射。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeIndexingConvention, - }, - Message: "这些索引字段(%v)需要有非空约束", - AllowOffline: true, - NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - Func: checkIndexNotNullConstraint, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckObjectNameUsingKeyword, - Desc: "数据库对象命名禁止使用保留字", - Annotation: "通过配置该规则可以规范指定业务的数据对象命名规则,避免发生冲突,以及混淆", - Level: driverV2.RuleLevelError, - Category: RuleTypeNamingConvention, - }, - Message: "数据库对象命名禁止使用保留字 %s", - AllowOffline: true, - Func: checkNewObjectName, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckObjectNameUseCN, - Desc: "数据库对象命名只能使用英文、下划线或数字,首字母必须是英文", - Annotation: "通过配置该规则可以规范指定业务的数据对象命名规则", - Level: driverV2.RuleLevelError, - Category: RuleTypeNamingConvention, - }, - Message: "数据库对象命名只能使用英文、下划线或数字,首字母必须是英文", - AllowOffline: true, - Func: checkNewObjectName, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckTableDBEngine, - Desc: "建议使用指定数据库引擎", - Annotation: "通过配置该规则可以规范指定业务的数据库引擎,具体规则可以自定义设置。默认值是INNODB,INNODB 支持事务,支持行级锁,更好的恢复性,高并发下性能更好", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - //Value: "Innodb", - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "Innodb", - Desc: "数据库引擎", - Type: params.ParamTypeString, - }, - }, - }, - Message: "建议使用%v数据库引擎", - AllowOffline: false, - Func: checkEngine, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckTableCharacterSet, - Desc: "建议使用指定数据库字符集", - Annotation: "通过该规则约束全局的数据库字符集,避免创建非预期的字符集,防止业务侧出现“乱码”等问题。建议项目内库表使用统一的字符集和字符集排序,部分连表查询的情况下字段的字符集或排序规则不一致可能会导致索引失效且不易发现", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - //Value: "utf8mb4", - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "utf8mb4", - Desc: "数据库字符集", - Type: params.ParamTypeString, - }, - }, - }, - Message: "建议使用%v数据库字符集", - AllowOffline: false, - Func: checkCharacterSet, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckIndexedColumnWithBlob, - Desc: "禁止将BLOB类型的列加入索引", - Annotation: "BLOB类型属于大字段类型,作为索引会占用很大的存储空间", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexingConvention, - }, - Message: "禁止将BLOB类型的列加入索引", - AllowOffline: true, - NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, - Func: disableAddIndexForColumnsTypeBlob, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckWhereIsInvalid, - Desc: "禁止使用没有WHERE条件或者WHERE条件恒为TRUE的SQL", - Annotation: "SQL缺少WHERE条件在执行时会进行全表扫描产生额外开销,建议在大数据量高并发环境下开启,避免影响数据库查询性能", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "禁止使用没有WHERE条件或者WHERE条件恒为TRUE的SQL", - AllowOffline: true, - Func: checkSelectWhere, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckAlterTableNeedMerge, - Desc: "存在多条对同一个表的修改语句,建议合并成一个ALTER语句", - Annotation: "避免多次 TABLE REBUILD 带来的消耗、以及对线上业务的影响", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeUsageSuggestion, - }, - Message: "已存在对该表的修改语句,建议合并成一个ALTER语句", - AllowOffline: false, - OnlyAuditNotExecutedSQL: true, - Func: checkMergeAlterTable, - }, - { - Rule: driverV2.Rule{ - Name: DMLDisableSelectAllColumn, - Desc: "不建议使用SELECT *", - Annotation: "当表结构变更时,使用*通配符选择所有列将导致查询行为会发生更改,与业务期望不符;同时SELECT * 中的无用字段会带来不必要的磁盘I/O,以及网络开销,且无法覆盖索引进而回表,大幅度降低查询效率", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用SELECT *", - AllowOffline: true, - Func: checkSelectAll, - }, - { - Rule: driverV2.Rule{ - Name: DDLDisableDropStatement, - Desc: "禁止除索引外的DROP操作", - Annotation: "DROP是DDL,数据变更不会写入日志,无法进行回滚;建议开启此规则,避免误删除操作", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - Message: "禁止除索引外的DROP操作", - AllowOffline: true, - Func: disableDropStmt, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckTableWithoutComment, - Desc: "表建议添加注释", - Annotation: "表添加注释能够使表的意义更明确,方便日后的维护", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - Message: "表建议添加注释", - AllowOffline: true, - Func: checkTableWithoutComment, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnWithoutComment, - Desc: "列建议添加注释", - Annotation: "列添加注释能够使列的意义更明确,方便日后的维护", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - Message: "列建议添加注释", - AllowOffline: true, - Func: checkColumnWithoutComment, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckIndexPrefix, - Desc: "建议普通索引使用固定前缀", - Annotation: "通过配置该规则可以规范指定业务的索引命名规则,具体命名规范可以自定义设置,默认提示值:idx_", - Level: driverV2.RuleLevelError, - Category: RuleTypeNamingConvention, - //Value: "idx_", - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "idx_", - Desc: "索引前缀", - Type: params.ParamTypeString, - }, - }, - }, - Message: "建议普通索引要以\"%v\"为前缀", - AllowOffline: true, - Func: checkIndexPrefix, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckUniqueIndexPrefix, - Desc: "建议UNIQUE索引使用固定前缀", - Annotation: "通过配置该规则可以规范指定业务的UNIQUE索引命名规则,具体命名规范可以自定义设置,默认提示值:uniq_", - Level: driverV2.RuleLevelError, - Category: RuleTypeNamingConvention, - //Value: "uniq_", - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "uniq_", - Desc: "索引前缀", - Type: params.ParamTypeString, - }, - }, - }, - Message: "建议UNIQUE索引要以\"%v\"为前缀", - AllowOffline: true, - Func: checkUniqIndexPrefix, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckUniqueIndex, - Desc: "建议UNIQUE索引名使用 IDX_UK_表名_字段名", - Annotation: "通过配置该规则可以规范指定业务的UNIQUE索引命名规则", - Level: driverV2.RuleLevelError, - Category: RuleTypeNamingConvention, - }, - Message: "建议UNIQUE索引名使用 IDX_UK_表名_字段名", - AllowOffline: true, - Func: checkUniqIndex, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnWithoutDefault, - Desc: "除了自增列及大字段列之外,每个列都必须添加默认值", - Annotation: "列添加默认值,可避免列为NULL值时对查询的影响", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "除了自增列及大字段列之外,每个列都必须添加默认值", - AllowOffline: true, - Func: checkColumnWithoutDefault, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnTimestampWithoutDefault, - Desc: "TIMESTAMP 类型的列必须添加默认值", - Annotation: "TIMESTAMP添加默认值,可避免出现全为0的日期格式与业务预期不符", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "TIMESTAMP 类型的列必须添加默认值", - AllowOffline: true, - Func: checkColumnTimestampWithoutDefault, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnBlobWithNotNull, - Desc: "BLOB 和 TEXT 类型的字段不建议设置为 NOT NULL", - Annotation: "BLOB 和 TEXT 类型的字段无法指定默认值,如插入数据不指定字段默认为NULL,如果添加了 NOT NULL 限制,写入数据时又未对该字段指定值会导致写入失败", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "BLOB 和 TEXT 类型的字段不建议设置为 NOT NULL", - AllowOffline: true, - Func: checkColumnBlobNotNull, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnBlobDefaultIsNotNull, - Desc: "BLOB 和 TEXT 类型的字段默认值只能为NULL", - Annotation: "在SQL_MODE严格模式下BLOB 和 TEXT 类型无法设置默认值,如插入数据不指定值,字段会被设置为NULL", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "BLOB 和 TEXT 类型的字段默认值只能为NULL", - AllowOffline: true, - Func: checkColumnBlobDefaultNull, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckAutoIncrementFieldNum, - Desc: "建表时,自增字段只能设置一个", - Annotation: "MySQL InnoDB,MyISAM 引擎不允许存在多个自增字段,设置多个自增字段会导致上线失败。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - }, - AllowOffline: true, - Message: "建表时,自增字段只能设置一个", - Func: checkAutoIncrementFieldNum, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckAllIndexNotNullConstraint, - Desc: "建议为至少一个索引添加非空约束", - Annotation: "所有索引字段均未做非空约束,请确认下表索引规划的合理性。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - }, - AllowOffline: true, - Message: "建议为至少一个索引添加非空约束", - Func: checkAllIndexNotNullConstraint, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckWithLimit, - Desc: "DELETE/UPDATE 语句不能有LIMIT条件", - Annotation: "DELETE/UPDATE 语句使用LIMIT条件将随机选取数据进行删除或者更新,业务无法预期", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "DELETE/UPDATE 语句不能有LIMIT条件", - AllowOffline: true, - Func: checkDMLWithLimit, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckSelectLimit, - Desc: "SELECT 语句需要带LIMIT", - Annotation: "如果查询的扫描行数很大,可能会导致优化器选择错误的索引甚至不走索引;具体规则阈值可以根据业务需求调整,默认值:1000", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1000", - Desc: "最大查询行数", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "SELECT 语句需要带LIMIT,且限制数不得超过%v", - AllowOffline: true, - Func: checkSelectLimit, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckWithOrderBy, - Desc: "DELETE/UPDATE 语句不能有ORDER BY", - Annotation: "DELETE/UPDATE 存在ORDER BY会使用排序,带来无谓的开销", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "DELETE/UPDATE 语句不能有ORDER BY", - AllowOffline: true, - Func: checkDMLWithOrderBy, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckSelectWithOrderBy, - Desc: "SELECT 语句不能有ORDER BY", - Annotation: "ORDER BY 对查询性能影响较大,同时不便于优化维护,建议将排序部分放到业务处理", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "SELECT 语句不能有ORDER BY", - AllowOffline: true, - Func: checkSelectWithOrderBy, - }, - { - // TODO: 修改level以适配默认模板 - Rule: driverV2.Rule{ - Name: DMLCheckInsertColumnsExist, - Desc: "INSERT 语句需要指定COLUMN", - Annotation: "当表结构发生变更,INSERT请求不明确指定列名,会发生插入数据不匹配的情况;建议开启此规则,避免插入结果与业务预期不符", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "INSERT 语句需要指定COLUMN", - AllowOffline: true, - Func: checkDMLWithInsertColumnExist, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckBatchInsertListsMax, - Desc: "单条INSERT语句,建议批量插入不超过阈值", - Annotation: "避免大事务,以及降低发生回滚对业务的影响;具体规则阈值可以根据业务需求调整,默认值:100", - Level: driverV2.RuleLevelNotice, - //Value: "5000", - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "100", - Desc: "最大插入行数", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "单条INSERT语句,建议批量插入不超过%v条", - AllowOffline: true, - Func: checkDMLWithBatchInsertMaxLimits, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckInQueryNumber, - Desc: "WHERE条件内IN语句中的参数个数不能超过阈值", - Annotation: "当IN值过多时,有可能会导致查询进行全表扫描,使得MySQL性能急剧下降;具体规则阈值可以根据业务需求调整,默认值:50", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "50", - Desc: "in语句参数最大个数", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "WHERE条件内IN语句中的参数已有%v个,不建议超过阙值%v", - AllowOffline: true, - Func: checkInQueryLimit, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckPKProhibitAutoIncrement, - Desc: "不建议主键使用自增", - Annotation: "后期维护相对不便,过于依赖数据库自增机制达到全局唯一,不易拆分,容易造成主键冲突", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeIndexingConvention, - }, - Message: "不建议主键使用自增", - AllowOffline: true, - NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, - NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, - Func: checkPrimaryKey, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckWhereExistFunc, - Desc: "避免对条件字段使用函数操作", - Annotation: "对条件字段做函数操作,可能会破坏索引值的有序性,导致优化器选择放弃走索引,使查询性能大幅度降低", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "避免对条件字段使用函数操作", - AllowOffline: false, - Func: checkWhereExistFunc, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckWhereExistNot, - Desc: "不建议对条件字段使用负向查询", - Annotation: "使用负向查询,将导致全表扫描,出现慢SQL", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不建议对条件字段使用负向查询", - AllowOffline: true, - Func: checkSelectWhere, - }, - { - Rule: driverV2.Rule{ - Name: DMLWhereExistNull, - Desc: "不建议对条件字段使用 NULL 值判断", - Annotation: "使用 IS NULL 或 IS NOT NULL 可能导致查询放弃使用索引而进行全表扫描", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不建议对条件字段使用 NULL 值判断", - Func: checkWhereExistNull, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckWhereExistImplicitConversion, - Desc: "不建议在WHERE条件中使用与过滤字段不一致的数据类型", - Annotation: "WHERE条件中使用与过滤字段不一致的数据类型会引发隐式数据类型转换,导致查询有无法命中索引的风险,在高并发、大数据量的情况下,不走索引会使得数据库的查询性能严重下降", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不建议在WHERE条件中使用与过滤字段不一致的数据类型", - Func: checkWhereColumnImplicitConversion, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckLimitMustExist, - Desc: "建议DELETE/UPDATE 语句带有LIMIT条件", - Annotation: "LIMIT条件可以降低写错 SQL 的代价(删错数据),同时避免长事务影响业务", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "建议DELETE/UPDATE 语句带有LIMIT条件", - Func: checkDMLLimitExist, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckWhereExistScalarSubquery, - Desc: "不建议使用标量子查询", - Annotation: "标量子查询存在多次访问同一张表的问题,执行开销大效率低,可使用LEFT JOIN 替代标量子查询", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用标量子查询", - AllowOffline: true, - Func: checkSelectWhere, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckIndexesExistBeforeCreateConstraints, - Desc: "对字段创建约束前,建议先创建索引", - Annotation: "创建约束前,先行创建索引,约束可作用于二级索引,避免全表扫描,提高性能", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeIndexingConvention, - }, - Message: "对字段创建约束前,建议先创建索引", - OnlyAuditNotExecutedSQL: true, - Func: checkIndexesExistBeforeCreatConstraints, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckSelectForUpdate, - Desc: "不建议使用SELECT FOR UPDATE", - Annotation: "SELECT FOR UPDATE 会对查询结果集中每行数据都添加排他锁,其他线程对该记录的更新与删除操作都会阻塞,在高并发下,容易造成数据库大量锁等待,影响数据库查询性能", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用SELECT FOR UPDATE", - Func: checkDMLSelectForUpdate, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckDatabaseCollation, - Desc: "建议使用规定的数据库排序规则", - Annotation: "通过该规则约束全局的数据库排序规则,避免创建非预期的数据库排序规则,防止业务侧出现排序结果非预期等问题。建议项目内库表使用统一的字符集和字符集排序,部分连表查询的情况下字段的字符集或排序规则不一致可能会导致索引失效且不易发现", - Level: driverV2.RuleLevelNotice, - //Value: "utf8mb4_0900_ai_ci", - Category: RuleTypeDDLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "utf8mb4_0900_ai_ci", - Desc: "数据库排序规则", - Type: params.ParamTypeString, - }, - }, - }, - Message: "建议使用规定的数据库排序规则为%s", - Func: checkCollationDatabase, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckDecimalTypeColumn, - Desc: "精确浮点数建议使用DECIMAL", - Annotation: "对于浮点数运算,DECIMAL精确度较高", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - Message: "精确浮点数建议使用DECIMAL", - Func: checkDecimalTypeColumn, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckBigintInsteadOfDecimal, - Desc: "建议用BIGINT类型代替DECIMAL", - Annotation: "因为CPU不支持对DECIMAL的直接运算,只是MySQL自身实现了DECIMAL的高精度计算,但是计算代价高,并且存储同样范围值的时候,空间占用也更多;使用BIGINT代替DECIMAL,可根据小数的位数乘以相应的倍数,即可达到精确的浮点存储计算,避免DECIMAL计算代价高的问题", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - Message: "建议列%s用BIGINT类型代替DECIMAL", - Func: checkBigintInsteadOfDecimal, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckSubQueryNestNum, - Desc: "子查询嵌套层数不建议超过阈值", - Annotation: "子查询嵌套层数超过阈值,有些情况下,子查询并不能使用到索引。同时对于返回结果集比较大的子查询,会产生大量的临时表,消耗过多的CPU和IO资源,产生大量的慢查询", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "3", - Desc: "子查询嵌套层数不建议超过阈值", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "子查询嵌套层数超过阈值%v", - Func: checkSubQueryNestNum, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckNeedlessFunc, - Desc: "避免使用不必要的内置函数", - Annotation: "通过配置该规则可以指定业务中需要禁止使用的内置函数,使用内置函数可能会导致SQL无法走索引或者产生一些非预期的结果。实际需要禁用的函数可通过规则设置", - Level: driverV2.RuleLevelNotice, - //Value: "sha(),sqrt(),md5()", - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "sha(),sqrt(),md5()", - Desc: "指定的函数集合(逗号分割)", - Type: params.ParamTypeString, - }, - }, - }, - Message: "避免使用不必要的内置函数%v", - Func: checkNeedlessFunc, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckDatabaseSuffix, - Desc: "建议数据库名称使用固定后缀结尾", - Annotation: "通过配置该规则可以规范指定业务的数据库命名规则,具体命名规范可以自定义设置,默认提示值:_DB", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeNamingConvention, - //Value: "_DB", - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "_DB", - Desc: "数据库名称后缀", - Type: params.ParamTypeString, - }, - }, - }, - Message: "建议数据库名称以\"%v\"结尾", - Func: checkDatabaseSuffix, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckPKName, - Desc: "建议主键命名为\"PK_表名\"", - Annotation: "通过配置该规则可以规范指定业务的主键命名规则", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeNamingConvention, - }, - Message: "建议主键命名为\"PK_表名\"", - Func: checkPKIndexName, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckTransactionIsolationLevel, - Desc: "事物隔离级别建议设置成RC", - Annotation: "RC避免了脏读的现象,但没有解决幻读的问题;使用RR,能避免幻读,但是由于引入间隙锁导致加锁的范围可能扩大,从而会影响并发,还容易造成死锁,所以在大多数业务场景下,幻读出现的机率较少,RC基本上能满足业务需求", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeUsageSuggestion, - }, - Message: "事物隔离级别建议设置成RC", - Func: checkTransactionIsolationLevel, - AllowOffline: true, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckFuzzySearch, - Desc: "禁止使用全模糊搜索或左模糊搜索", - Annotation: "使用全模糊搜索或左模糊搜索将导致查询无法使用索引,导致全表扫描", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "禁止使用全模糊搜索或左模糊搜索", - AllowOffline: true, - Func: checkSelectWhere, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckTablePartition, - Desc: "不建议使用分区表相关功能", - Annotation: "分区表在物理上表现为多个文件,在逻辑上表现为一个表,跨分区查询效率可能更低,建议采用物理分表的方式管理大数据", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeUsageSuggestion, - }, - Message: "不建议使用分区表相关功能", - AllowOffline: true, - Func: checkTablePartition, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckNumberOfJoinTables, - Desc: "使用JOIN连接表查询建议不超过阈值", - Annotation: "表关联越多,意味着各种驱动关系组合就越多,比较各种结果集的执行成本的代价也就越高,进而SQL查询性能会大幅度下降;具体规则阈值可以根据业务需求调整,默认值:3", - Level: driverV2.RuleLevelNotice, - //Value: "3", - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "3", - Desc: "最大连接表个数", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "使用JOIN连接表查询建议不超过%v张", - AllowOffline: true, - Func: checkNumberOfJoinTables, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckIfAfterUnionDistinct, - Desc: "建议使用UNION ALL,替代UNION", - Annotation: "UNION会按照字段的顺序进行排序同时去重,UNION ALL只是简单的将两个结果合并后就返回,从效率上看,UNION ALL 要比UNION快很多;如果合并的两个结果集中允许包含重复数据且不需要排序时的话,建议开启此规则,使用UNION ALL替代UNION", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "建议使用UNION ALL,替代UNION", - AllowOffline: true, - Func: checkIsAfterUnionDistinct, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckIsExistLimitOffset, - Desc: "使用分页查询时,避免使用偏移量", - Annotation: "例如:LIMIT N OFFSET M 或 LIMIT M,N。当偏移量m过大的时候,查询效率会很低,因为MySQL是先查出m+n个数据,然后抛弃掉前m个数据;对于有大数据量的MySQL表来说,使用LIMIT分页存在很严重的性能问题", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "使用分页查询时,避免使用偏移量", - AllowOffline: true, - Func: checkIsExistLimitOffset, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckIndexOption, - Desc: "建议索引字段对区分度大于阈值", - Annotation: "选择区分度高的字段作为索引,可快速定位数据;区分度太低,无法有效利用索引,甚至可能需要扫描大量数据页,拖慢SQL;具体规则阈值可以根据业务需求调整,默认值:70", - Level: driverV2.RuleLevelNotice, - //Value: "0.7", - Category: RuleTypeIndexOptimization, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "70", - Desc: "可选择性(百分比)", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "索引 %v 未超过区分度阈值 百分之%v, 不建议选为索引", - AllowOffline: false, - Func: checkIndexOption, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnEnumNotice, - Desc: "不建议使用 ENUM 类型", - Annotation: "ENUM类型不是SQL标准,移植性较差,后期如修改或增加枚举值需重建整张表,代价较大,且无法通过字面量值进行排序", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - Message: "不建议使用 ENUM 类型", - AllowOffline: true, - Func: checkColumnEnumNotice, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnSetNotice, - Desc: "不建议使用 SET 类型", - Annotation: "集合的修改需要重新定义列,后期修改的代价大,建议在业务层实现", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - Message: "不建议使用 SET 类型", - AllowOffline: true, - Func: checkColumnSetNotice, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnBlobNotice, - Desc: "不建议使用 BLOB 或 TEXT 类型", - Annotation: "BLOB 或 TEXT 类型消耗大量的网络和IO带宽,同时在该表上的DML操作都会变得很慢", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - Message: "不建议使用 BLOB 或 TEXT 类型", - AllowOffline: true, - Func: checkColumnBlobNotice, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckExplainAccessTypeAll, - //Value: "10000", - Desc: "全表扫描时,扫描行数不建议超过指定行数(默认值:10000)", - Annotation: "全表扫描时,扫描行数不建议超过指定行数是为了避免性能问题;具体规则阈值可以根据业务需求调整,默认值:10000;如果设置为0,全表扫描都会触发规则", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "10000", - Desc: "最大扫描行数", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "该查询使用了全表扫描并且扫描行数为%v", - AllowOffline: false, - Func: checkExplain, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckExplainExtraUsingFilesort, - Desc: "不建议使用文件排序", - Annotation: "大数据量的情况下,文件排序意味着SQL性能较低,会增加OS的开销,影响数据库性能", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用文件排序", - AllowOffline: false, - Func: checkExplain, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckExplainExtraUsingTemporary, - Desc: "不建议使用临时表", - Annotation: "大数据量的情况下,临时表意味着SQL性能较低,会增加OS的开销,影响数据库性能", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用临时表", - AllowOffline: false, - Func: checkExplain, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckCreateView, - Desc: "禁止使用视图", - Annotation: "视图的查询性能较差,同时基表结构变更,需要对视图进行维护,如果视图可读性差且包含复杂的逻辑,都会增加维护的成本", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - Message: "禁止使用视图", - AllowOffline: true, - Func: checkCreateView, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckCreateTrigger, - Desc: "禁止使用触发器", - Annotation: "触发器难以开发和维护,不能高效移植,且在复杂的逻辑以及高并发下,容易出现死锁影响业务", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - Message: "禁止使用触发器", - AllowOffline: true, - Func: checkCreateTrigger, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckCreateFunction, - Desc: "禁止使用自定义函数", - Annotation: "自定义函数,维护较差,且依赖性高会导致SQL无法跨库使用", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - Message: "禁止使用自定义函数", - AllowOffline: true, - Func: checkCreateFunction, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckCreateProcedure, - Desc: "禁止使用存储过程", - Annotation: "存储过程在一定程度上会使程序难以调试和拓展,各种数据库的存储过程语法相差很大,给将来的数据库移植带来很大的困难,且会极大的增加出现BUG的概率", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - Message: "禁止使用存储过程", - AllowOffline: true, - Func: checkCreateProcedure, - }, - { - Rule: driverV2.Rule{ - Name: DDLDisableTypeTimestamp, - Desc: "不建议使用TIMESTAMP字段", - Annotation: "TIMESTAMP 有最大值限制('2038-01-19 03:14:07' UTC),且会时区转换的问题", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - }, - Message: "不建议使用TIMESTAMP字段", - AllowOffline: true, - Func: disableUseTypeTimestampField, - }, - { - Rule: driverV2.Rule{ //select a as id, id , b as user from mysql.user; - Name: DMLCheckAlias, - Desc: "别名不建议与表或列的名字相同", - Annotation: "表或列的别名与其真实名称相同, 这样的别名会使得查询更难去分辨", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "这些别名(%v)与列名或表名相同", - Func: checkAlias, - }, - { - Rule: driverV2.Rule{ //ALTER TABLE test CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; - Name: DDLHintUpdateTableCharsetWillNotUpdateFieldCharset, - Desc: "不建议修改表的默认字符集", - Annotation: "修改表的默认字符集,只会影响后续新增的字段,不会修表已有字段的字符集;如需修改整张表所有字段的字符集建议开启此规则", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - }, - Message: "不建议修改表的默认字符集", - Func: hintUpdateTableCharsetWillNotUpdateFieldCharset, - }, { - Rule: driverV2.Rule{ //ALTER TABLE tbl DROP COLUMN col; - Name: DDLHintDropColumn, - Desc: "禁止进行删除列的操作", - Annotation: "业务逻辑与删除列依赖未完全消除,列被删除后可能导致程序异常(无法正常读写)的情况;开启该规则,SQLE将提醒删除列为高危操作", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "禁止进行删除列的操作", - Func: hintDropColumn, - }, { - Rule: driverV2.Rule{ //ALTER TABLE tbl DROP PRIMARY KEY; - Name: DDLHintDropPrimaryKey, - Desc: "禁止进行删除主键的操作", - Annotation: "删除已有约束会影响已有业务逻辑;开启该规则,SQLE将提醒删除主键为高危操作", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "禁止进行删除主键的操作", - Func: hintDropPrimaryKey, - }, { - Rule: driverV2.Rule{ //ALTER TABLE tbl DROP FOREIGN KEY a; - Name: DDLHintDropForeignKey, - Desc: "禁止进行删除外键的操作", - Annotation: "删除已有约束会影响已有业务逻辑;开启该规则,SQLE将提醒删除外键为高危操作", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "禁止进行删除外键的操作", - Func: hintDropForeignKey, - }, - { - Rule: driverV2.Rule{ //select * from user where id like "a"; - Name: DMLNotRecommendNotWildcardLike, - Desc: "不建议使用没有通配符的 LIKE 查询", - Annotation: "不包含通配符的 LIKE 查询逻辑上与等值查询相同,建议使用等值查询替代", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用没有通配符的 LIKE 查询", - Func: notRecommendNotWildcardLike, - }, { - Rule: driverV2.Rule{ //SELECT * FROM tb WHERE col IN (NULL); - Name: DMLHintInNullOnlyFalse, - Desc: "避免使用 IN (NULL) 或者 NOT IN (NULL)", - Annotation: "查询条件永远非真,这将导致查询无匹配到的结果", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "避免使用IN (NULL)/NOT IN (NULL) ,该用法永远非真将导致条件失效", - Func: hintInNullOnlyFalse, - }, { - Rule: driverV2.Rule{ //select * from user where id in (a); - Name: DMLNotRecommendIn, - Desc: "不建议使用IN", - Annotation: "当IN值过多时,有可能会导致查询进行全表扫描,使得MySQL性能急剧下降", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用IN", - Func: notRecommendIn, - }, - { - Rule: driverV2.Rule{ //select * from user where id = ' 1'; - Name: DMLCheckSpacesAroundTheString, - Desc: "引号中的字符串开头或结尾不建议包含空格", - Annotation: "字符串前后存在空格将可能导致查询判断逻辑出错,如在MySQL 5.5中'a'和'a '在查询中被认为是相同的值", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "引号中的字符串开头或结尾不建议包含空格", - Func: checkSpacesAroundTheString, - }, { - Rule: driverV2.Rule{ //CREATE TABLE tb (a varchar(10) default '“'); - Name: DDLCheckFullWidthQuotationMarks, - Desc: "DDL语句中不建议使用中文全角引号", - Annotation: "建议开启此规则,可避免MySQL会将中文全角引号识别为命名的一部分,执行结果与业务预期不符", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - Message: "DDL语句中不建议使用中文全角引号,这可能是书写错误", - Func: checkFullWidthQuotationMarks, - }, { - Rule: driverV2.Rule{ //select name from tbl where id < 1000 order by rand(1) - Name: DMLNotRecommendOrderByRand, - Desc: "不建议使用 ORDER BY RAND()", - Annotation: "ORDER BY RAND()使用了临时表,同时还要对其进行排序,在数据量很大的情况下会增加服务器负载以及增加查询时间", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用 ORDER BY RAND()", - Func: notRecommendOrderByRand, - }, { - Rule: driverV2.Rule{ //select col1,col2 from tbl group by 1 - Name: DMLNotRecommendGroupByConstant, - Desc: "不建议对常量进行 GROUP BY", - Annotation: "GROUP BY 1 表示按第一列进行GROUP BY;在GROUP BY子句中使用数字,而不是表达式或列名称,当查询列顺序改变时,会导致查询逻辑出现问题", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议对常量进行 GROUP BY", - Func: notRecommendGroupByConstant, - }, { - Rule: driverV2.Rule{ //select c1,c2,c3 from t1 where c1='foo' order by c2 desc, c3 asc - Name: DMLCheckSortDirection, - Desc: "不建议在 ORDER BY 语句中对多个不同条件使用不同方向的排序", - Annotation: "在 MySQL 8.0 之前当 ORDER BY 多个列指定的排序方向不同时将无法使用已经建立的索引。在MySQL8.0 之后可以建立对应的排序顺序的联合索引来优化", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议在 ORDER BY 语句中对多个不同条件使用不同方向的排序", - Func: checkSortDirection, - }, { - Rule: driverV2.Rule{ //select col1,col2 from tbl group by 1 - Name: DMLHintGroupByRequiresConditions, - Desc: "建议为GROUP BY语句添加ORDER BY条件", - Annotation: "在5.7中,MySQL默认会对’GROUP BY col1, …’按如下顺序’ORDER BY col1,…’隐式排序,导致产生无谓的排序,带来额外的开销;在8.0中,则不会出现这种情况。如果不需要排序建议显示添加’ORDER BY NULL’", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "建议为GROUP BY语句添加ORDER BY条件", - Func: hintGroupByRequiresConditions, - }, { - Rule: driverV2.Rule{ //select description from film where title ='ACADEMY DINOSAUR' order by length-language_id; - Name: DMLNotRecommendGroupByExpression, - Desc: "不建议ORDER BY 的条件为表达式", - Annotation: "当ORDER BY条件为表达式或函数时会使用到临时表,如果在未指定WHERE或WHERE条件返回的结果集较大时性能会很差", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议ORDER BY 的条件为表达式", - Func: notRecommendGroupByExpression, - }, { - Rule: driverV2.Rule{ //select description from film where title ='ACADEMY DINOSAUR' order by length-language_id; - Name: DMLCheckSQLLength, - Desc: "建议将过长的SQL分解成几个简单的SQL", - Annotation: "过长的SQL可读性较差,难以维护,且容易引发性能问题;具体规则阈值可以根据业务需求调整,默认值:1024", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1024", - Desc: "SQL最大长度", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "建议将过长的SQL分解成几个简单的SQL", - Func: checkSQLLength, - }, { - Rule: driverV2.Rule{ //SELECT s.c_id,count(s.c_id) FROM s where c = test GROUP BY s.c_id HAVING s.c_id <> '1660' AND s.c_id <> '2' order by s.c_id - Name: DMLNotRecommendHaving, - Desc: "不建议使用 HAVING 子句", - Annotation: "对于索引字段,放在HAVING子句中时不会走索引;建议将HAVING子句改写为WHERE中的查询条件,可以在查询处理期间使用索引,提高SQL的执行效率", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用 HAVING 子句", - Func: notRecommendHaving, - }, { - Rule: driverV2.Rule{ //delete from tbl - Name: DMLHintUseTruncateInsteadOfDelete, - Desc: "删除全表时建议使用 TRUNCATE 替代 DELETE", - Annotation: "TRUNCATE TABLE 比 DELETE 速度快,且使用的系统和事务日志资源少,同时TRUNCATE后表所占用的空间会被释放,而DELETE后需要手工执行OPTIMIZE才能释放表空间", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "删除全表时建议使用 TRUNCATE 替代 DELETE", - Func: hintUseTruncateInsteadOfDelete, - }, { - Rule: driverV2.Rule{ //update mysql.func set name ="hello"; - Name: DMLNotRecommendUpdatePK, - Desc: "不建议UPDATE主键", - Annotation: "主键索引数据列的顺序就是表记录的物理存储顺序,频繁更新主键将导致整个表记录的顺序的调整,会耗费相当大的资源", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "不建议UPDATE主键", - Func: notRecommendUpdatePK, - }, { - Rule: driverV2.Rule{ //create table t(c1 int,c2 int,c3 int,c4 int,c5 int,c6 int); - Name: DDLCheckColumnQuantity, - Desc: "表的列数不建议超过阈值", - Annotation: "避免在OLTP系统上做宽表设计,后期对性能影响很大;具体规则阈值可根据业务需求调整,默认值:40", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "40", - Desc: "最大列数", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "表的列数不建议超过阈值", - Func: checkColumnQuantity, - AllowOffline: true, - }, { - Rule: driverV2.Rule{ //CREATE TABLE `tb2` ( `id` int(11) DEFAULT NULL, `col` char(10) CHARACTER SET utf8 DEFAULT NULL) - Name: DDLRecommendTableColumnCharsetSame, - Desc: "建议列与表使用同一个字符集", - Annotation: "统一字符集可以避免由于字符集转换产生的乱码,不同的字符集进行比较前需要进行转换会造成索引失效", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - }, - Message: "建议列与表使用同一个字符集", - Func: recommendTableColumnCharsetSame, - }, { - Rule: driverV2.Rule{ //CREATE TABLE tab (a INT(1)); - Name: DDLCheckColumnTypeInteger, - Desc: "整型定义建议采用 INT(10) 或 BIGINT(20)", - Annotation: "INT(M) 或 BIGINT(M),M 表示最大显示宽度,可存储最大值的宽度分别为10、20,采用 INT(10) 或 BIGINT(20)可避免发生显示截断的可能", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - Message: "整型定义建议采用 INT(10) 或 BIGINT(20)", - Func: checkColumnTypeInteger, - }, { - Rule: driverV2.Rule{ //CREATE TABLE tab (a varchar(3500)); - Name: DDLCheckVarcharSize, - Desc: "定义VARCHAR 长度时不建议大于阈值", - Annotation: "MySQL建立索引时没有限制索引的大小,索引长度会默认采用的该字段的长度,VARCHAR 定义长度越长建立的索引存储大小越大;具体规则阈值可以根据业务需求调整,默认值:1024", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1024", - Desc: "VARCHAR最大长度", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "定义VARCHAR 长度时不建议大于阈值, 阈值为%d", - Func: checkVarcharSize, - }, { - Rule: driverV2.Rule{ //select id from t where substring(name,1,3)='abc' - Name: DMLNotRecommendFuncInWhere, - Desc: "应避免在 WHERE 条件中使用函数或其他运算符", - Annotation: "函数或运算符会导致查询无法利用表中的索引,该查询将会全表扫描,性能较差", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "应避免在 WHERE 条件中使用函数或其他运算符", - Func: notRecommendFuncInWhere, - }, { - Rule: driverV2.Rule{ //SELECT SYSDATE(); - Name: DMLNotRecommendSysdate, - Desc: "不建议使用 SYSDATE() 函数", - Annotation: "当SYSDATE()函数在基于STATEMENT模式的主从环境下可能造成数据的不一致,因为语句在主库中执行到日志传递到备库,存在时间差,到备库执行的时候就会变成不同的时间值,建议采取ROW模式的复制环境", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用 SYSDATE() 函数", - Func: notRecommendSysdate, - }, { - Rule: driverV2.Rule{ //SELECT SUM(COL) FROM tbl; - Name: DMLHintSumFuncTips, - Desc: "避免使用 SUM(COL)", - Annotation: "当某一列的值全是NULL时,COUNT(COL)的返回结果为0,但SUM(COL)的返回结果为NULL,因此使用SUM()时需注意NPE问题(指数据返回NULL);如业务需避免NPE问题,建议开启此规则", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "避免使用 SUM(COL) ,该用法存在返回NULL值导致程序空指针的风险", - Func: hintSumFuncTips, - }, { - Rule: driverV2.Rule{ - Name: DMLHintCountFuncWithCol, - Desc: "避免使用 COUNT(COL)", - Annotation: "建议使用COUNT(*),因为使用 COUNT(COL) 需要对表进行全表扫描,这可能会导致性能下降。", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "避免使用 COUNT(COL)", - Func: hintCountFuncWithCol, - AllowOffline: true, - }, { - Rule: driverV2.Rule{ - Name: DDLCheckColumnQuantityInPK, - Desc: "主键包含的列数不建议超过阈值", - Annotation: "主建中的列过多,会导致二级索引占用更多的空间,同时增加索引维护的开销;具体规则阈值可根据业务需求调整,默认值:2", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "2", - Desc: "最大列数", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "主键包含的列数不建议超过阈值", - Func: checkColumnQuantityInPK, - }, { - Rule: driverV2.Rule{ //select col1,col2 from tbl where name=xx limit 10 - Name: DMLHintLimitMustBeCombinedWithOrderBy, - Desc: "LIMIT 查询建议使用ORDER BY", - Annotation: "没有ORDER BY的LIMIT会导致非确定性的结果可能与业务需求不符,这取决于执行计划", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "LIMIT 查询建议使用ORDER BY", - Func: hintLimitMustBeCombinedWithOrderBy, - }, - { - Rule: driverV2.Rule{ //TRUNCATE TABLE tbl_name - Name: DMLHintTruncateTips, - Desc: "不建议使用TRUNCATE操作", - Annotation: "TRUNCATE是DLL,数据不能回滚,在没有备份情况下,谨慎使用TRUNCATE", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用TRUNCATE操作", - Func: hintTruncateTips, - }, { - Rule: driverV2.Rule{ //delete from t where col = 'condition' - Name: DMLHintDeleteTips, - Desc: "建议在执行DELETE/DROP/TRUNCATE等操作前进行备份", - Annotation: "DROP/TRUNCATE是DDL,操作立即生效,不会写入日志,所以无法回滚,在执行高危操作之前对数据进行备份是很有必要的", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "建议在执行DELETE/DROP/TRUNCATE等操作前进行备份", - Func: hintDeleteTips, - }, { - Rule: driverV2.Rule{ //SELECT BENCHMARK(10, RAND()) - Name: DMLCheckSQLInjectionFunc, - Desc: "不建议使用常见 SQL 注入函数", - Annotation: "攻击者通过SQL注入,可未经授权可访问数据库中的数据,存在盗取用户信息,造成用户数据泄露等安全漏洞问题", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议使用常见 SQL 注入函数", - Func: checkSQLInjectionFunc, - }, { - Rule: driverV2.Rule{ //select col1,col2 from tbl where type!=0 - Name: DMLCheckNotEqualSymbol, - Desc: "建议使用'<>'代替'!='", - Annotation: "'!=' 是非标准的运算符,'<>' 才是SQL中标准的不等于运算符", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "建议使用'<>'代替'!='", - Func: checkNotEqualSymbol, - }, { - Rule: driverV2.Rule{ //select col1,col2,col3 from table1 where col2 in(select col from table2) - Name: DMLNotRecommendSubquery, - Desc: "不推荐使用子查询", - Annotation: "有些情况下,子查询并不能使用到索引,同时对于返回结果集比较大的子查询,会产生大量的临时表,消耗过多的CPU和IO资源,产生大量的慢查询", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDMLConvention, - }, - Message: "不推荐使用子查询", - Func: notRecommendSubquery, - }, { - Rule: driverV2.Rule{ //SELECT * FROM staff WHERE name IN (SELECT NAME FROM customer ORDER BY name LIMIT 1) - Name: DMLCheckSubqueryLimit, - Desc: "不建议在子查询中使用LIMIT", - Annotation: "部分MySQL版本不支持在子查询中进行'LIMIT & IN/ALL/ANY/SOME'", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - Message: "不建议在子查询中使用LIMIT", - Func: checkSubqueryLimit, - }, { - Rule: driverV2.Rule{ //CREATE TABLE tbl (a int) AUTO_INCREMENT = 10; - Name: DDLCheckAutoIncrement, - Desc: "表的初始AUTO_INCREMENT值建议为0", - Annotation: "创建表时AUTO_INCREMENT设置为0则自增从1开始,可以避免数据空洞。例如在导出表结构DDL时,表结构内AUTO_INCREMENT通常为当前的自增值,如果建表时没有把AUTO_INCREMENT设置为0,那么通过该DDL进行建表操作会导致自增值从一个无意义数字开始。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - }, - Message: "表的初始AUTO_INCREMENT值建议为0", - Func: checkAutoIncrement, - }, { - Rule: driverV2.Rule{ // rename table t1 to t2; - Name: DDLNotAllowRenaming, - Desc: "禁止使用RENAME或CHANGE对表名字段名进行修改", - Annotation: "RENAME/CHANGE 表名/列名会对线上业务不停机发布造成影响,如需这种操作应当DBA手工干预", - Level: driverV2.RuleLevelError, - Category: RuleTypeDDLConvention, - }, - AllowOffline: true, - Message: "禁止使用RENAME或CHANGE对表名字段名进行修改", - Func: ddlNotAllowRenaming, - }, { - Rule: driverV2.Rule{ - Name: DMLCheckExplainFullIndexScan, - Desc: "不建议对表进行全索引扫描", - Annotation: "在数据量大的情况下索引全扫描严重影响SQL性能。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - AllowOffline: false, - Message: "不建议对表进行全索引扫描", - Func: checkExplain, - }, { - Rule: driverV2.Rule{ - Name: DMLCheckLimitOffsetNum, - Desc: "不建议LIMIT的偏移OFFSET大于阈值", - Annotation: "因为OFFSET指定了结果集的起始位置,如果起始位置过大,那么 MySQL 需要处理更多的数据才能返回结果集,这可能会导致查询性能下降。", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "100", - Desc: "offset 大小", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "不建议LIMIT的偏移OFFSET大于阈值,OFFSET=%v(阈值为%v)", - AllowOffline: true, - Func: checkLimitOffsetNum, - }, { - Rule: driverV2.Rule{ - Name: DMLCheckUpdateOrDeleteHasWhere, - Desc: "建议UPDATE/DELETE操作使用WHERE条件", - Annotation: "因为这些语句的目的是修改数据库中的数据,需要使用 WHERE 条件来过滤需要更新或删除的记录,以确保数据的正确性。另外,使用 WHERE 条件还可以提高查询性能。", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - Message: "建议UPDATE/DELETE操作使用WHERE条件", - AllowOffline: true, - Func: checkUpdateOrDeleteHasWhere, - }, { - Rule: driverV2.Rule{ - Name: DMLCheckSortColumnLength, - Desc: "禁止对长字段排序", - Annotation: "对例如VARCHAR(2000)这样的长字段进行ORDER BY、DISTINCT、GROUP BY、UNION之类的操作,会引发排序,有性能隐患", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "2000", - Desc: "可排序字段的最大长度", - Type: params.ParamTypeInt, - }, - }, - }, - AllowOffline: false, - Message: "长度超过阈值的字段不建议用于ORDER BY、DISTINCT、GROUP BY、UNION,这些字段有:%v", - Func: checkSortColumnLength, - }, { - Rule: driverV2.Rule{ - Name: AllCheckPrepareStatementPlaceholders, - Desc: "绑定的变量个数不建议超过阈值", - Annotation: "因为过度使用绑定变量会增加查询的复杂度,从而降低查询性能。过度使用绑定变量还会增加维护成本。默认阈值:100", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "100", - Desc: "最大绑定变量数量", - Type: params.ParamTypeInt, - }, - }, - }, - AllowOffline: true, - Message: "使用绑定变量数量为 %v,不建议超过设定阈值 %v", - Func: checkPrepareStatementPlaceholders, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckExplainExtraUsingIndexForSkipScan, - Desc: "不建议对表进行索引跳跃扫描", - Annotation: "索引扫描是跳跃扫描,未遵循最左匹配原则,可能降低索引的使用效率,影响查询性能", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - AllowOffline: false, - Message: "不建议对表进行索引跳跃扫描", - Func: checkExplain, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckAffectedRows, - Desc: "UPDATE/DELETE操作影响行数不建议超过阈值", - Annotation: "如果 DML 操作影响行数过多,会导致查询性能下降,因为需要扫描更多的数据。", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "10000", - Desc: "最大影响行数", - Type: params.ParamTypeInt, - }, - }, - }, - AllowOffline: false, - Message: "UPDATE/DELETE操作影响行数不建议超过阈值,影响行数为 %v,超过设定阈值 %v", - Func: checkAffectedRows, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckSameTableJoinedMultipleTimes, - Desc: "不建议对同一张表连接多次", - Annotation: "如果对单表查询多次,会导致查询性能下降。", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - AllowOffline: false, - Message: "表%v被连接多次", - Func: checkSameTableJoinedMultipleTimes, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckExplainUsingIndex, - Desc: "SQL查询条件需要走索引", - Annotation: "使用索引可以显著提高SQL查询的性能。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - AllowOffline: false, - Message: "建议使用索引以优化 SQL 查询性能", - Func: checkExplain, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckInsertSelect, - Desc: "不建议使用INSERT ... SELECT", - Annotation: "使用 INSERT ... SELECT 在默认事务隔离级别下,可能会导致对查询的表施加表级锁。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - AllowOffline: true, - Message: "不建议使用INSERT ... SELECT", - Func: checkInsertSelect, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckAggregate, - Desc: "不建议使用聚合函数", - Annotation: "不建议使用SQL聚合函数,是为了确保查询的简单性、高性能和数据一致性。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDMLConvention, - }, - AllowOffline: true, - Message: "不建议使用聚合函数计算", - Func: checkAggregateFunc, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckColumnNotNULL, - Desc: "表字段建议有NOT NULL约束", - Annotation: "表字段建议有 NOT NULL 约束,可确保数据的完整性,防止插入空值,提升查询准确性。", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - AllowOffline: false, - Message: "建议字段%v设置NOT NULL约束", - Func: checkColumnNotNull, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckIndexSelectivity, - Desc: "建议连库查询时,确保SQL执行计划中使用的索引区分度大于阈值", - Annotation: "确保SQL执行计划中使用的高索引区分度,有助于提升查询性能并优化查询效率。", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "70", - Desc: "可选择性(百分比)", - Type: params.ParamTypeInt, - }, - }, - }, - AllowOffline: false, - Message: "索引:%v,未超过区分度阈值:%v,建议使用超过阈值的索引。", - Func: checkIndexSelectivity, - }, - { - // 该规则只适用于库表元数据扫描并且需要与停用上线审核模式规则一起使用 - Rule: driverV2.Rule{ - Name: DDLCheckTableRows, - Desc: "表行数超过阈值,建议对表进行拆分", - Annotation: "当表行数超过阈值时,对表进行拆分有助于提高数据库性能和查询速度。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeUsageSuggestion, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "1000", - Desc: "表行数(万)", - Type: params.ParamTypeInt, - }, - }, - }, - Message: "表行数超过阈值,建议对表进行拆分", - Func: checkTableRows, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckCompositeIndexDistinction, - Desc: "建议在组合索引中将区分度高的字段靠前放", - Annotation: "将区分度高的字段靠前放置在组合索引中有助于提高索引的查询性能,因为它能更快地减小数据范围,提高检索效率。", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - AllowOffline: false, - Message: "建议在组合索引中将区分度高的字段靠前放,%v", - Func: checkCompositeIndexSelectivity, - }, - { - Rule: driverV2.Rule{ - Name: DDLAvoidText, - Desc: "使用TEXT 类型的字段建议和原表进行分拆,与原表主键单独组成另外一个表进行存放", - Annotation: "将TEXT类型的字段与原表主键分拆成另一个表可以提高数据库性能和查询速度,减少不必要的 I/O 操作。", - Level: driverV2.RuleLevelNotice, - Category: RuleTypeDDLConvention, - }, - AllowOffline: true, - Message: "字段:%v为TEXT类型,建议和原表进行分拆,与原表主键单独组成另外一个表进行存放", - Func: checkText, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckSelectRows, - Desc: "查询数据量超过阈值,筛选条件必须带上主键或者索引", - Annotation: "筛选条件必须带上主键或索引可提高查询性能和减少全表扫描的成本。", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "10", - Desc: "查询数据量(万)", - Type: params.ParamTypeInt, - }, - }, - }, - AllowOffline: false, - Message: "查询数据量超过阈值,筛选条件必须带上主键或者索引", - Func: checkSelectRows, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckScanRows, - Desc: "扫描行数超过阈值,筛选条件必须带上主键或者索引", - Annotation: "筛选条件必须带上主键或索引可降低数据库查询的时间复杂度,提高查询效率。", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "10", - Desc: "扫描行数量(万)", - Type: params.ParamTypeInt, - }, - }, - }, - AllowOffline: false, - Message: "扫描行数超过阈值,筛选条件必须带上主键或者索引", - Func: checkScanRows, - }, - { - Rule: driverV2.Rule{ - Name: DMLMustUseLeftMostPrefix, - Desc: "使用联合索引时,必须使用联合索引的首字段", - Annotation: "使用联合索引时,不包含首字段会导致联合索引失效", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexInvalidation, - }, - AllowOffline: false, - Message: "使用联合索引时,必须使用联合索引的首字段", - Func: mustMatchLeftMostPrefix, - }, - { - Rule: driverV2.Rule{ - Name: DMLMustMatchLeftMostPrefix, - Desc: "禁止对联合索引左侧字段进行IN 、OR等非等值查询", - Annotation: "对联合索引左侧字段进行IN 、OR等非等值查询会导致联合索引失效", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexInvalidation, - }, - AllowOffline: false, - Message: "对联合索引左侧字段进行IN 、OR等非等值查询会导致联合索引失效", - Func: mustMatchLeftMostPrefix, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckJoinFieldUseIndex, - Desc: "JOIN字段必须包含索引", - Annotation: "JOIN字段包含索引可提高连接操作的性能和查询速度。", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexInvalidation, - }, - AllowOffline: false, - Message: "JOIN字段必须包含索引", - Func: checkJoinFieldUseIndex, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckJoinFieldCharacterSetAndCollation, - Desc: "连接表字段的字符集和排序规则必须一致", - Annotation: "连接表字段的字符集和排序规则一致可避免数据不一致和查询错误,确保连接操作正确执行。", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexInvalidation, - }, - AllowOffline: false, - Message: "连接表字段的字符集和排序规则必须一致", - Func: checkJoinFieldCharacterSetAndCollation, - }, - { - Rule: driverV2.Rule{ - Name: DMLCheckMathComputationOrFuncOnIndex, - Desc: "禁止对索引列进行数学运算和使用函数", - Annotation: "对索引列进行数学运算和使用函数会导致索引失效,从而导致全表扫描,影响查询性能。", - Level: driverV2.RuleLevelError, - Category: RuleTypeIndexInvalidation, - }, - AllowOffline: false, - Message: "禁止对索引列进行数学运算和使用函数", - Func: checkMathComputationOrFuncOnIndex, - }, - { - Rule: driverV2.Rule{ - Name: DMLSQLExplainLowestLevel, - Desc: "SQL执行计划中type字段建议满足规定的级别", - Annotation: "验证 SQL 执行计划中的 type 字段,确保满足要求级别,以保证查询性能。", - Level: driverV2.RuleLevelWarn, - Category: RuleTypeDDLConvention, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "range,ref,const,eq_ref,system,NULL", - Desc: "查询计划type等级,以英文逗号隔开", - Type: params.ParamTypeString, - }, - }, - }, - AllowOffline: false, - Message: "建议修改SQL,确保执行计划中type字段可以满足规定中的任一等级:%v", - Func: checkSQLExplainLowestLevel, - }, - { - Rule: driverV2.Rule{ - Name: DDLAvoidFullText, - Desc: "禁止使用全文索引", - Annotation: "全文索引的使用会增加存储开销,并对写操作性能产生一定影响。", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - AllowOffline: true, - Message: "禁止使用全文索引", - Func: avoidFullText, - }, - { - Rule: driverV2.Rule{ - Name: DDLAvoidGeometry, - Desc: "禁止使用空间字段和空间索引", - Annotation: "使用空间字段和空间索引会增加存储需求,对数据库性能造成一定影响", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - AllowOffline: true, - Message: "禁止使用空间字段和空间索引", - Func: avoidGeometry, - }, - { - Rule: driverV2.Rule{ - Name: DMLAvoidWhereEqualNull, - Desc: "WHERE子句中禁止将NULL值与其他字段或值进行比较运算", - Annotation: "NULL在SQL中属于特殊值,无法与普通值进行比较。例如:column = NULL恒为false,即使column存在null值也不会查询出来,所以column = NULL应该写为column is NULL", - Level: driverV2.RuleLevelError, - Category: RuleTypeDMLConvention, - }, - AllowOffline: true, - Message: "WHERE子句中禁止将NULL值与其他字段或值进行比较运算", - Func: avoidWhereEqualNull, - }, - { - Rule: driverV2.Rule{ - Name: DDLAvoidEvent, - Desc: "禁止使用event", - Annotation: "使用event会增加数据库的维护难度和依赖性,并且也会造成安全问题。", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - }, - AllowOffline: true, - Message: "禁止使用event", - Func: avoidEvent, - }, - { - Rule: driverV2.Rule{ - Name: DDLCheckCharLength, - Desc: "禁止char, varchar类型字段字符长度总和超过阈值", - Annotation: "使用过长或者过多的varchar,char字段可能会增加业务逻辑的复杂性;如果字段平均长度过大时,会占用更多的存储空间。", - Level: driverV2.RuleLevelError, - Category: RuleTypeUsageSuggestion, - Params: params.Params{ - ¶ms.Param{ - Key: DefaultSingleParamKeyName, - Value: "2000", - Desc: "字符长度", - Type: params.ParamTypeInt, - }, - }, - }, - AllowOffline: false, - Message: "禁止char, varchar类型字段字符长度总和超过阈值 %v", - Func: checkCharLength, - }, -} - func checkMathComputationOrFuncOnIndex(input *RuleHandlerInput) error { switch stmt := input.Node.(type) { case *ast.SelectStmt: @@ -7439,11 +5310,22 @@ func mustMatchLeftMostPrefix(input *RuleHandlerInput) error { return nil } + isAllSubquery := true + for _, table := range tables { + if _, ok := table.Source.(*ast.TableName); ok { + isAllSubquery = false + break + } + } + if isAllSubquery { + return nil + } + for alias, cols := range tablesFromCondition { table, err := util.ConvertAliasToTable(alias, tables) if err != nil { log.NewEntry().Errorf("convert table alias failed, sqle: %v, error: %v", input.Node.Text(), err) - return fmt.Errorf("convert table alias failed: %v", err) + return nil } createTable, exist, err := input.Ctx.GetCreateTableStmt(table) if err != nil { diff --git a/sqle/driver/mysql/rule/rule_list.go b/sqle/driver/mysql/rule/rule_list.go new file mode 100644 index 0000000000..310fce3276 --- /dev/null +++ b/sqle/driver/mysql/rule/rule_list.go @@ -0,0 +1,2137 @@ +//go:build !trial +// +build !trial + +package rule + +import ( + driverV2 "github.com/actiontech/sqle/sqle/driver/v2" + "github.com/actiontech/sqle/sqle/pkg/params" + "github.com/pingcap/parser/ast" +) + +var RuleHandlers = []RuleHandler{ + { + Rule: driverV2.Rule{ + Name: ConfigDMLRollbackMaxRows, + Desc: "在 DML 语句中预计影响行数超过指定值则不回滚", + Annotation: "大事务回滚,容易影响数据库性能,使得业务发生波动;具体规则阈值可以根据业务需求调整,默认值:1000", + //Value: "1000", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeGlobalConfig, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1000", + Desc: "最大影响行数", + Type: params.ParamTypeInt, + }, + }, + }, + Func: nil, + }, + { + Rule: driverV2.Rule{ + Name: ConfigDDLOSCMinSize, + Desc: "改表时,表空间超过指定大小(MB)审核时输出osc改写建议", + Annotation: "开启该规则后会对大表的DDL语句给出 pt-osc工具的改写建议【需要参考命令进行手工执行,后续会支持自动执行】;直接对大表进行DDL变更时可能会导致长时间锁表问题,影响业务可持续性。具体对大表定义的阈值可以根据业务需求调整,默认值:1024", + //Value: "16", + Level: driverV2.RuleLevelNormal, + Category: RuleTypeGlobalConfig, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1024", + Desc: "表空间大小(MB)", + Type: params.ParamTypeInt, + }, + }, + }, + Func: nil, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckTableSize, + Desc: "不建议对数据量过大的表执行DDL操作", + Annotation: "大表执行DDL,耗时较久且负载较高,长时间占用锁资源,会影响数据库性能;具体规则阈值可以根据业务需求调整,默认值:1024", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1024", + Desc: "表空间大小(MB)", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "执行DDL的表 %v 空间不建议超过 %vMB", + OnlyAuditNotExecutedSQL: true, + Func: checkDDLTableSize, + }, { + Rule: driverV2.Rule{ + Name: DDLCheckIndexTooMany, + Desc: "单字段上的索引数量不建议超过阈值", + Annotation: "单字段上存在过多索引,一般情况下这些索引都是没有存在价值的;相反,还会降低数据增加删除时的性能,特别是对频繁更新的表来说,负面影响更大;具体规则阈值可以根据业务需求调整,默认值:2", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeIndexingConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "2", + Desc: "单字段的索引数最大值", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "字段 %v 上的索引数量不建议超过%v个", + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + Func: checkIndex, + }, + { + Rule: driverV2.Rule{ + Name: ConfigDMLExplainPreCheckEnable, + Desc: "使用EXPLAIN加强预检查能力", + Annotation: "通过 EXPLAIN 的形式将待上线的DML进行SQL是否能正确执行的检查,提前发现语句的错误,提高上线成功率", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeGlobalConfig, + }, + Func: nil, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckRedundantIndex, + Desc: "不建议创建冗余索引", + Annotation: "MySQL需要单独维护重复的索引,冗余索引增加维护成本,并且优化器在优化查询时需要逐个进行代价计算,影响查询性能", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexOptimization, + }, + Message: "%v", + AllowOffline: true, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + Func: checkIndex, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckTableSize, + Desc: "不建议对数据量过大的表执行DML操作", + Annotation: "DML操作大表,耗时较久且负载较高,容易影响数据库性能;具体规则阈值可以根据业务需求调整,默认值:1024", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1024", + Desc: "表空间大小(MB)", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "执行DML的表 %v 空间不建议超过 %vMB", + Func: checkDMLTableSize, + }, + { + Rule: driverV2.Rule{ + Name: ConfigOptimizeIndexEnabled, + Desc: "索引创建建议", + Annotation: "通过该规则开启索引优化建议,提供两个参数配置来定义索引优化建议的行为。1. 计算列基数阈值:配置当表数据量超过多少行时不再计算列的区分度来排序索引优先级,防止对大表进行操作影响性能;2. 联合索引最大列数:限制联合索引给到的列数最大值,防止给出建议的联合索引不符合其他SQL标准", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeIndexOptimization, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultMultiParamsFirstKeyName, + Value: "1000000", + Desc: "计算列基数阈值", + Type: params.ParamTypeInt, + }, + ¶ms.Param{ + Key: DefaultMultiParamsSecondKeyName, + Value: "3", + Desc: "联合索引最大列数", + Type: params.ParamTypeInt, + }, + }, + }, + }, + + { + Rule: driverV2.Rule{ + Name: ConfigSQLIsExecuted, + Desc: "停用上线审核模式", + Annotation: "启用该规则来兼容事后审核的场景,对于事后采集的DDL 和 DML 语句将不再进行上线校验。例如库表元数据的扫描任务可开启该规则", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeGlobalConfig, + }, + }, + + { + Rule: driverV2.Rule{ + Name: ConfigDDLGhostMinSize, + Desc: "改表时,表空间超过指定大小(MB)时使用gh-ost上线", + Annotation: "开启该规则后会自动对大表的DDL操作使用gh-ost 工具进行在线改表;直接对大表进行DDL变更时可能会导致长时间锁表问题,影响业务可持续性。具体对大表定义的阈值可以根据业务需求调整,默认值:1024", + //Value: "16", + Level: driverV2.RuleLevelNormal, + Category: RuleTypeGlobalConfig, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1024", + Desc: "表空间大小(MB)", + Type: params.ParamTypeInt, + }, + }, + }, + Func: nil, + }, + + // rule + { + Rule: driverV2.Rule{ + Name: DDLCheckPKWithoutIfNotExists, + Desc: "新建表建议加入 IF NOT EXISTS,保证重复执行不报错", + Annotation: "新建表如果表已经存在,不添加IF NOT EXISTS CREATE执行SQL会报错,建议开启此规则,避免SQL实际执行报错", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + Message: "新建表建议加入 IF NOT EXISTS,保证重复执行不报错", + AllowOffline: true, + Func: checkIfNotExist, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckObjectNameLength, + Desc: "表名、列名、索引名的长度不建议超过阈值", + Annotation: "通过配置该规则可以规范指定业务的对象命名长度,具体长度可以自定义设置,默认最大长度:64。是MySQL规定标识符命名最大长度为64字节", + Level: driverV2.RuleLevelError, + Category: RuleTypeNamingConvention, + //Value: "64", + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "64", + Desc: "最大长度(字节)", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "表名、列名、索引名的长度不建议大于%v字节", + AllowOffline: true, + Func: checkNewObjectName, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckObjectNameIsUpperAndLowerLetterMixed, + Desc: "数据库对象命名不建议大小写字母混合", + Annotation: "数据库对象命名规范,不推荐采用大小写混用的形式建议词语之间使用下划线连接,提高代码可读性", + Category: RuleTypeNamingConvention, + Level: driverV2.RuleLevelNotice, + }, + Message: "数据库对象命名不建议大小写字母混合,以下对象命名不规范:%v", + Func: checkIsObjectNameUpperAndLowerLetterMixed, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckPKNotExist, + Desc: "表必须有主键", + Annotation: "主键使数据达到全局唯一,可提高数据检索效率", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexingConvention, + }, + Message: "表必须有主键", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, + Func: checkPrimaryKey, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckPKWithoutAutoIncrement, + Desc: "主键建议使用自增", + Annotation: "自增主键,数字型速度快,而且是增量增长,占用空间小,更快速的做数据插入操作,避免增加维护索引的开销", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexingConvention, + }, + Message: "主键建议使用自增", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, + Func: checkPrimaryKey, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckPKWithoutBigintUnsigned, + Desc: "主键建议使用 BIGINT 无符号类型,即 BIGINT UNSIGNED", + Annotation: "BIGINT UNSIGNED拥有更大的取值范围,建议开启此规则,避免发生溢出", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexingConvention, + }, + Message: "主键建议使用 BIGINT 无符号类型,即 BIGINT UNSIGNED", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, + Func: checkPrimaryKey, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckJoinFieldType, + Desc: "建议JOIN字段类型保持一致", + Annotation: "JOIN字段类型不一致会导致类型不匹配发生隐式准换,建议开启此规则,避免索引失效", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "建议JOIN字段类型保持一致, 否则会导致隐式转换", + AllowOffline: false, + Func: checkJoinFieldType, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckHasJoinCondition, + Desc: "建议连接操作指定连接条件", + Annotation: "指定连接条件可以确保连接操作的正确性和可靠性,如果没有指定连接条件,可能会导致连接失败或连接不正确的情况。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "建议连接操作指定连接条件,JOIN字段后必须有ON条件", + AllowOffline: true, + Func: checkHasJoinCondition, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnCharLength, + Desc: "CHAR长度大于20时,必须使用VARCHAR类型", + Annotation: "VARCHAR是变长字段,存储空间小,可节省存储空间,同时相对较小的字段检索效率显然也要高些", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "CHAR长度大于20时,必须使用VARCHAR类型", + AllowOffline: true, + Func: checkStringType, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckFieldNotNUllMustContainDefaultValue, + Desc: "建议字段约束为NOT NULL时带默认值", + Annotation: "如存在NOT NULL且不带默认值的字段,INSERT时不包含该字段,会导致插入报错", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + }, + Message: "建议字段约束为NOT NULL时带默认值,以下字段不规范:%v", + AllowOffline: true, + Func: checkFieldNotNUllMustContainDefaultValue, + }, + { + Rule: driverV2.Rule{ + Name: DDLDisableFK, + Desc: "禁止使用外键", + Annotation: "外键在高并发场景下性能较差,容易造成死锁,同时不利于后期维护(拆分、迁移)", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexingConvention, + }, + Message: "禁止使用外键", + AllowOffline: true, + Func: checkForeignKey, + }, + { + Rule: driverV2.Rule{ + Name: DDLDisableAlterFieldUseFirstAndAfter, + Desc: "ALTER表字段禁止使用FIRST,AFTER", + Annotation: "FIRST,AFTER 的ALTER操作通过COPY TABLE的方式完成,对业务影响较大", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "ALTER表字段禁止使用FIRST,AFTER", + AllowOffline: true, + Func: disableAlterUseFirstAndAfter, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckCreateTimeColumn, + Desc: "建议建表DDL包含创建时间字段且默认值为CURRENT_TIMESTAMP", + Annotation: "使用CREATE_TIME字段,有利于问题查找跟踪和检索数据,同时避免后期对数据生命周期管理不便 ,默认值为CURRENT_TIMESTAMP可保证时间的准确性", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "CREATE_TIME", + Desc: "创建时间字段名", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建议建表DDL包含%v字段且默认值为CURRENT_TIMESTAMP", + AllowOffline: true, + Func: checkFieldCreateTime, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIndexCount, + Desc: "索引个数建议不超过阈值", + Annotation: "在表上建立的每个索引都会增加存储开销,索引对于插入、删除、更新操作也会增加处理上的开销,太多与不充分、不正确的索引对性能都毫无益处;具体规则阈值可以根据业务需求调整,默认值:5", + Level: driverV2.RuleLevelNotice, + //Value: "5", + Category: RuleTypeIndexingConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "5", + Desc: "最大索引个数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "索引个数建议不超过%v个", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + Func: checkIndex, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckUpdateTimeColumn, + Desc: "建表DDL需要包含更新时间字段且默认值为CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", + Annotation: "使用更新时间字段,有利于问题查找跟踪和检索数据,同时避免后期对数据生命周期管理不便 ,默认值为UPDATE_TIME可保证时间的准确性", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "UPDATE_TIME", + Desc: "更新时间字段名", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建表DDL需要包含%v字段且默认值为CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", + AllowOffline: true, + Func: checkFieldUpdateTime, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckCompositeIndexMax, + Desc: "复合索引的列数量不建议超过阈值", + Annotation: "复合索引会根据索引列数创建对应组合的索引,列数越多,创建的索引越多,每个索引都会增加磁盘空间的开销,同时增加索引维护的开销;具体规则阈值可以根据业务需求调整,默认值:3", + Level: driverV2.RuleLevelNotice, + //Value: "3", + Category: RuleTypeIndexingConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "3", + Desc: "最大索引列数量", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "复合索引的列数量不建议超过%v个", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + Func: checkIndex, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIndexNotNullConstraint, + Desc: "索引字段需要有非空约束", + Annotation: "索引字段上如果没有非空约束,则表记录与索引记录不会完全映射。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeIndexingConvention, + }, + Message: "这些索引字段(%v)需要有非空约束", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + Func: checkIndexNotNullConstraint, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckObjectNameUsingKeyword, + Desc: "数据库对象命名禁止使用保留字", + Annotation: "通过配置该规则可以规范指定业务的数据对象命名规则,避免发生冲突,以及混淆", + Level: driverV2.RuleLevelError, + Category: RuleTypeNamingConvention, + }, + Message: "数据库对象命名禁止使用保留字 %s", + AllowOffline: true, + Func: checkNewObjectName, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckObjectNameUseCN, + Desc: "数据库对象命名只能使用英文、下划线或数字,首字母必须是英文", + Annotation: "通过配置该规则可以规范指定业务的数据对象命名规则", + Level: driverV2.RuleLevelError, + Category: RuleTypeNamingConvention, + }, + Message: "数据库对象命名只能使用英文、下划线或数字,首字母必须是英文", + AllowOffline: true, + Func: checkNewObjectName, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckTableDBEngine, + Desc: "建议使用指定数据库引擎", + Annotation: "通过配置该规则可以规范指定业务的数据库引擎,具体规则可以自定义设置。默认值是INNODB,INNODB 支持事务,支持行级锁,更好的恢复性,高并发下性能更好", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + //Value: "Innodb", + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "Innodb", + Desc: "数据库引擎", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建议使用%v数据库引擎", + AllowOffline: false, + Func: checkEngine, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckTableCharacterSet, + Desc: "建议使用指定数据库字符集", + Annotation: "通过该规则约束全局的数据库字符集,避免创建非预期的字符集,防止业务侧出现“乱码”等问题。建议项目内库表使用统一的字符集和字符集排序,部分连表查询的情况下字段的字符集或排序规则不一致可能会导致索引失效且不易发现", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + //Value: "utf8mb4", + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "utf8mb4", + Desc: "数据库字符集", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建议使用%v数据库字符集", + AllowOffline: false, + Func: checkCharacterSet, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIndexedColumnWithBlob, + Desc: "禁止将BLOB类型的列加入索引", + Annotation: "BLOB类型属于大字段类型,作为索引会占用很大的存储空间", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexingConvention, + }, + Message: "禁止将BLOB类型的列加入索引", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + Func: disableAddIndexForColumnsTypeBlob, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckWhereIsInvalid, + Desc: "禁止使用没有WHERE条件或者WHERE条件恒为TRUE的SQL", + Annotation: "SQL缺少WHERE条件在执行时会进行全表扫描产生额外开销,建议在大数据量高并发环境下开启,避免影响数据库查询性能", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "禁止使用没有WHERE条件或者WHERE条件恒为TRUE的SQL", + AllowOffline: true, + Func: checkSelectWhere, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckAlterTableNeedMerge, + Desc: "存在多条对同一个表的修改语句,建议合并成一个ALTER语句", + Annotation: "避免多次 TABLE REBUILD 带来的消耗、以及对线上业务的影响", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeUsageSuggestion, + }, + Message: "已存在对该表的修改语句,建议合并成一个ALTER语句", + AllowOffline: false, + OnlyAuditNotExecutedSQL: true, + Func: checkMergeAlterTable, + }, + { + Rule: driverV2.Rule{ + Name: DMLDisableSelectAllColumn, + Desc: "不建议使用SELECT *", + Annotation: "当表结构变更时,使用*通配符选择所有列将导致查询行为会发生更改,与业务期望不符;同时SELECT * 中的无用字段会带来不必要的磁盘I/O,以及网络开销,且无法覆盖索引进而回表,大幅度降低查询效率", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用SELECT *", + AllowOffline: true, + Func: checkSelectAll, + }, + { + Rule: driverV2.Rule{ + Name: DDLDisableDropStatement, + Desc: "禁止除索引外的DROP操作", + Annotation: "DROP是DDL,数据变更不会写入日志,无法进行回滚;建议开启此规则,避免误删除操作", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + Message: "禁止除索引外的DROP操作", + AllowOffline: true, + Func: disableDropStmt, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckTableWithoutComment, + Desc: "表建议添加注释", + Annotation: "表添加注释能够使表的意义更明确,方便日后的维护", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + Message: "表建议添加注释", + AllowOffline: true, + Func: checkTableWithoutComment, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnWithoutComment, + Desc: "列建议添加注释", + Annotation: "列添加注释能够使列的意义更明确,方便日后的维护", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + Message: "列建议添加注释", + AllowOffline: true, + Func: checkColumnWithoutComment, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIndexPrefix, + Desc: "建议普通索引使用固定前缀", + Annotation: "通过配置该规则可以规范指定业务的索引命名规则,具体命名规范可以自定义设置,默认提示值:idx_", + Level: driverV2.RuleLevelError, + Category: RuleTypeNamingConvention, + //Value: "idx_", + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "idx_", + Desc: "索引前缀", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建议普通索引要以\"%v\"为前缀", + AllowOffline: true, + Func: checkIndexPrefix, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckUniqueIndexPrefix, + Desc: "建议UNIQUE索引使用固定前缀", + Annotation: "通过配置该规则可以规范指定业务的UNIQUE索引命名规则,具体命名规范可以自定义设置,默认提示值:uniq_", + Level: driverV2.RuleLevelError, + Category: RuleTypeNamingConvention, + //Value: "uniq_", + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "uniq_", + Desc: "索引前缀", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建议UNIQUE索引要以\"%v\"为前缀", + AllowOffline: true, + Func: checkUniqIndexPrefix, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckUniqueIndex, + Desc: "建议UNIQUE索引名使用 IDX_UK_表名_字段名", + Annotation: "通过配置该规则可以规范指定业务的UNIQUE索引命名规则", + Level: driverV2.RuleLevelError, + Category: RuleTypeNamingConvention, + }, + Message: "建议UNIQUE索引名使用 IDX_UK_表名_字段名", + AllowOffline: true, + Func: checkUniqIndex, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnWithoutDefault, + Desc: "除了自增列及大字段列之外,每个列都必须添加默认值", + Annotation: "列添加默认值,可避免列为NULL值时对查询的影响", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "除了自增列及大字段列之外,每个列都必须添加默认值", + AllowOffline: true, + Func: checkColumnWithoutDefault, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnTimestampWithoutDefault, + Desc: "TIMESTAMP 类型的列必须添加默认值", + Annotation: "TIMESTAMP添加默认值,可避免出现全为0的日期格式与业务预期不符", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "TIMESTAMP 类型的列必须添加默认值", + AllowOffline: true, + Func: checkColumnTimestampWithoutDefault, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnBlobWithNotNull, + Desc: "BLOB 和 TEXT 类型的字段不建议设置为 NOT NULL", + Annotation: "BLOB 和 TEXT 类型的字段无法指定默认值,如插入数据不指定字段默认为NULL,如果添加了 NOT NULL 限制,写入数据时又未对该字段指定值会导致写入失败", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "BLOB 和 TEXT 类型的字段不建议设置为 NOT NULL", + AllowOffline: true, + Func: checkColumnBlobNotNull, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnBlobDefaultIsNotNull, + Desc: "BLOB 和 TEXT 类型的字段默认值只能为NULL", + Annotation: "在SQL_MODE严格模式下BLOB 和 TEXT 类型无法设置默认值,如插入数据不指定值,字段会被设置为NULL", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "BLOB 和 TEXT 类型的字段默认值只能为NULL", + AllowOffline: true, + Func: checkColumnBlobDefaultNull, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckAutoIncrementFieldNum, + Desc: "建表时,自增字段只能设置一个", + Annotation: "MySQL InnoDB,MyISAM 引擎不允许存在多个自增字段,设置多个自增字段会导致上线失败。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + }, + AllowOffline: true, + Message: "建表时,自增字段只能设置一个", + Func: checkAutoIncrementFieldNum, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckAllIndexNotNullConstraint, + Desc: "建议为至少一个索引添加非空约束", + Annotation: "所有索引字段均未做非空约束,请确认下表索引规划的合理性。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + }, + AllowOffline: true, + Message: "建议为至少一个索引添加非空约束", + Func: checkAllIndexNotNullConstraint, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckWithLimit, + Desc: "DELETE/UPDATE 语句不能有LIMIT条件", + Annotation: "DELETE/UPDATE 语句使用LIMIT条件将随机选取数据进行删除或者更新,业务无法预期", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "DELETE/UPDATE 语句不能有LIMIT条件", + AllowOffline: true, + Func: checkDMLWithLimit, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckSelectLimit, + Desc: "SELECT 语句需要带LIMIT", + Annotation: "如果查询的扫描行数很大,可能会导致优化器选择错误的索引甚至不走索引;具体规则阈值可以根据业务需求调整,默认值:1000", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1000", + Desc: "最大查询行数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "SELECT 语句需要带LIMIT,且限制数不得超过%v", + AllowOffline: true, + Func: checkSelectLimit, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckWithOrderBy, + Desc: "DELETE/UPDATE 语句不能有ORDER BY", + Annotation: "DELETE/UPDATE 存在ORDER BY会使用排序,带来无谓的开销", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "DELETE/UPDATE 语句不能有ORDER BY", + AllowOffline: true, + Func: checkDMLWithOrderBy, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckSelectWithOrderBy, + Desc: "SELECT 语句不能有ORDER BY", + Annotation: "ORDER BY 对查询性能影响较大,同时不便于优化维护,建议将排序部分放到业务处理", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "SELECT 语句不能有ORDER BY", + AllowOffline: true, + Func: checkSelectWithOrderBy, + }, + { + // TODO: 修改level以适配默认模板 + Rule: driverV2.Rule{ + Name: DMLCheckInsertColumnsExist, + Desc: "INSERT 语句需要指定COLUMN", + Annotation: "当表结构发生变更,INSERT请求不明确指定列名,会发生插入数据不匹配的情况;建议开启此规则,避免插入结果与业务预期不符", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "INSERT 语句需要指定COLUMN", + AllowOffline: true, + Func: checkDMLWithInsertColumnExist, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckBatchInsertListsMax, + Desc: "单条INSERT语句,建议批量插入不超过阈值", + Annotation: "避免大事务,以及降低发生回滚对业务的影响;具体规则阈值可以根据业务需求调整,默认值:100", + Level: driverV2.RuleLevelNotice, + //Value: "5000", + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "100", + Desc: "最大插入行数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "单条INSERT语句,建议批量插入不超过%v条", + AllowOffline: true, + Func: checkDMLWithBatchInsertMaxLimits, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckInQueryNumber, + Desc: "WHERE条件内IN语句中的参数个数不能超过阈值", + Annotation: "当IN值过多时,有可能会导致查询进行全表扫描,使得MySQL性能急剧下降;具体规则阈值可以根据业务需求调整,默认值:50", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "50", + Desc: "in语句参数最大个数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "WHERE条件内IN语句中的参数已有%v个,不建议超过阙值%v", + AllowOffline: true, + Func: checkInQueryLimit, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckPKProhibitAutoIncrement, + Desc: "不建议主键使用自增", + Annotation: "后期维护相对不便,过于依赖数据库自增机制达到全局唯一,不易拆分,容易造成主键冲突", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeIndexingConvention, + }, + Message: "不建议主键使用自增", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, + Func: checkPrimaryKey, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckWhereExistFunc, + Desc: "避免对条件字段使用函数操作", + Annotation: "对条件字段做函数操作,可能会破坏索引值的有序性,导致优化器选择放弃走索引,使查询性能大幅度降低", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "避免对条件字段使用函数操作", + AllowOffline: false, + Func: checkWhereExistFunc, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckWhereExistNot, + Desc: "不建议对条件字段使用负向查询", + Annotation: "使用负向查询,将导致全表扫描,出现慢SQL", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不建议对条件字段使用负向查询", + AllowOffline: true, + Func: checkSelectWhere, + }, + { + Rule: driverV2.Rule{ + Name: DMLWhereExistNull, + Desc: "不建议对条件字段使用 NULL 值判断", + Annotation: "使用 IS NULL 或 IS NOT NULL 可能导致查询放弃使用索引而进行全表扫描", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不建议对条件字段使用 NULL 值判断", + Func: checkWhereExistNull, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckWhereExistImplicitConversion, + Desc: "不建议在WHERE条件中使用与过滤字段不一致的数据类型", + Annotation: "WHERE条件中使用与过滤字段不一致的数据类型会引发隐式数据类型转换,导致查询有无法命中索引的风险,在高并发、大数据量的情况下,不走索引会使得数据库的查询性能严重下降", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不建议在WHERE条件中使用与过滤字段不一致的数据类型", + Func: checkWhereColumnImplicitConversion, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckLimitMustExist, + Desc: "建议DELETE/UPDATE 语句带有LIMIT条件", + Annotation: "LIMIT条件可以降低写错 SQL 的代价(删错数据),同时避免长事务影响业务", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "建议DELETE/UPDATE 语句带有LIMIT条件", + Func: checkDMLLimitExist, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckWhereExistScalarSubquery, + Desc: "不建议使用标量子查询", + Annotation: "标量子查询存在多次访问同一张表的问题,执行开销大效率低,可使用LEFT JOIN 替代标量子查询", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用标量子查询", + AllowOffline: true, + Func: checkSelectWhere, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIndexesExistBeforeCreateConstraints, + Desc: "对字段创建约束前,建议先创建索引", + Annotation: "创建约束前,先行创建索引,约束可作用于二级索引,避免全表扫描,提高性能", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeIndexingConvention, + }, + Message: "对字段创建约束前,建议先创建索引", + OnlyAuditNotExecutedSQL: true, + Func: checkIndexesExistBeforeCreatConstraints, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckSelectForUpdate, + Desc: "不建议使用SELECT FOR UPDATE", + Annotation: "SELECT FOR UPDATE 会对查询结果集中每行数据都添加排他锁,其他线程对该记录的更新与删除操作都会阻塞,在高并发下,容易造成数据库大量锁等待,影响数据库查询性能", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用SELECT FOR UPDATE", + Func: checkDMLSelectForUpdate, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckDatabaseCollation, + Desc: "建议使用规定的数据库排序规则", + Annotation: "通过该规则约束全局的数据库排序规则,避免创建非预期的数据库排序规则,防止业务侧出现排序结果非预期等问题。建议项目内库表使用统一的字符集和字符集排序,部分连表查询的情况下字段的字符集或排序规则不一致可能会导致索引失效且不易发现", + Level: driverV2.RuleLevelNotice, + //Value: "utf8mb4_0900_ai_ci", + Category: RuleTypeDDLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "utf8mb4_0900_ai_ci", + Desc: "数据库排序规则", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建议使用规定的数据库排序规则为%s", + Func: checkCollationDatabase, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckDecimalTypeColumn, + Desc: "精确浮点数建议使用DECIMAL", + Annotation: "对于浮点数运算,DECIMAL精确度较高", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + Message: "精确浮点数建议使用DECIMAL", + Func: checkDecimalTypeColumn, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckBigintInsteadOfDecimal, + Desc: "建议用BIGINT类型代替DECIMAL", + Annotation: "因为CPU不支持对DECIMAL的直接运算,只是MySQL自身实现了DECIMAL的高精度计算,但是计算代价高,并且存储同样范围值的时候,空间占用也更多;使用BIGINT代替DECIMAL,可根据小数的位数乘以相应的倍数,即可达到精确的浮点存储计算,避免DECIMAL计算代价高的问题", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + Message: "建议列%s用BIGINT类型代替DECIMAL", + Func: checkBigintInsteadOfDecimal, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckSubQueryNestNum, + Desc: "子查询嵌套层数不建议超过阈值", + Annotation: "子查询嵌套层数超过阈值,有些情况下,子查询并不能使用到索引。同时对于返回结果集比较大的子查询,会产生大量的临时表,消耗过多的CPU和IO资源,产生大量的慢查询", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "3", + Desc: "子查询嵌套层数不建议超过阈值", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "子查询嵌套层数超过阈值%v", + Func: checkSubQueryNestNum, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckNeedlessFunc, + Desc: "避免使用不必要的内置函数", + Annotation: "通过配置该规则可以指定业务中需要禁止使用的内置函数,使用内置函数可能会导致SQL无法走索引或者产生一些非预期的结果。实际需要禁用的函数可通过规则设置", + Level: driverV2.RuleLevelNotice, + //Value: "sha(),sqrt(),md5()", + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "sha(),sqrt(),md5()", + Desc: "指定的函数集合(逗号分割)", + Type: params.ParamTypeString, + }, + }, + }, + Message: "避免使用不必要的内置函数%v", + Func: checkNeedlessFunc, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckDatabaseSuffix, + Desc: "建议数据库名称使用固定后缀结尾", + Annotation: "通过配置该规则可以规范指定业务的数据库命名规则,具体命名规范可以自定义设置,默认提示值:_DB", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeNamingConvention, + //Value: "_DB", + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "_DB", + Desc: "数据库名称后缀", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建议数据库名称以\"%v\"结尾", + Func: checkDatabaseSuffix, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckPKName, + Desc: "建议主键命名为\"PK_表名\"", + Annotation: "通过配置该规则可以规范指定业务的主键命名规则", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeNamingConvention, + }, + Message: "建议主键命名为\"PK_表名\"", + Func: checkPKIndexName, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckTransactionIsolationLevel, + Desc: "事物隔离级别建议设置成RC", + Annotation: "RC避免了脏读的现象,但没有解决幻读的问题;使用RR,能避免幻读,但是由于引入间隙锁导致加锁的范围可能扩大,从而会影响并发,还容易造成死锁,所以在大多数业务场景下,幻读出现的机率较少,RC基本上能满足业务需求", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeUsageSuggestion, + }, + Message: "事物隔离级别建议设置成RC", + Func: checkTransactionIsolationLevel, + AllowOffline: true, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckFuzzySearch, + Desc: "禁止使用全模糊搜索或左模糊搜索", + Annotation: "使用全模糊搜索或左模糊搜索将导致查询无法使用索引,导致全表扫描", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "禁止使用全模糊搜索或左模糊搜索", + AllowOffline: true, + Func: checkSelectWhere, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckTablePartition, + Desc: "不建议使用分区表相关功能", + Annotation: "分区表在物理上表现为多个文件,在逻辑上表现为一个表,跨分区查询效率可能更低,建议采用物理分表的方式管理大数据", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeUsageSuggestion, + }, + Message: "不建议使用分区表相关功能", + AllowOffline: true, + Func: checkTablePartition, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckNumberOfJoinTables, + Desc: "使用JOIN连接表查询建议不超过阈值", + Annotation: "表关联越多,意味着各种驱动关系组合就越多,比较各种结果集的执行成本的代价也就越高,进而SQL查询性能会大幅度下降;具体规则阈值可以根据业务需求调整,默认值:3", + Level: driverV2.RuleLevelNotice, + //Value: "3", + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "3", + Desc: "最大连接表个数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "使用JOIN连接表查询建议不超过%v张", + AllowOffline: true, + Func: checkNumberOfJoinTables, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckIfAfterUnionDistinct, + Desc: "建议使用UNION ALL,替代UNION", + Annotation: "UNION会按照字段的顺序进行排序同时去重,UNION ALL只是简单的将两个结果合并后就返回,从效率上看,UNION ALL 要比UNION快很多;如果合并的两个结果集中允许包含重复数据且不需要排序时的话,建议开启此规则,使用UNION ALL替代UNION", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "建议使用UNION ALL,替代UNION", + AllowOffline: true, + Func: checkIsAfterUnionDistinct, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIsExistLimitOffset, + Desc: "使用分页查询时,避免使用偏移量", + Annotation: "例如:LIMIT N OFFSET M 或 LIMIT M,N。当偏移量m过大的时候,查询效率会很低,因为MySQL是先查出m+n个数据,然后抛弃掉前m个数据;对于有大数据量的MySQL表来说,使用LIMIT分页存在很严重的性能问题", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "使用分页查询时,避免使用偏移量", + AllowOffline: true, + Func: checkIsExistLimitOffset, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIndexOption, + Desc: "建议索引字段对区分度大于阈值", + Annotation: "选择区分度高的字段作为索引,可快速定位数据;区分度太低,无法有效利用索引,甚至可能需要扫描大量数据页,拖慢SQL;具体规则阈值可以根据业务需求调整,默认值:70", + Level: driverV2.RuleLevelNotice, + //Value: "0.7", + Category: RuleTypeIndexOptimization, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "70", + Desc: "可选择性(百分比)", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "索引 %v 未超过区分度阈值 百分之%v, 不建议选为索引", + AllowOffline: false, + Func: checkIndexOption, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnEnumNotice, + Desc: "不建议使用 ENUM 类型", + Annotation: "ENUM类型不是SQL标准,移植性较差,后期如修改或增加枚举值需重建整张表,代价较大,且无法通过字面量值进行排序", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + Message: "不建议使用 ENUM 类型", + AllowOffline: true, + Func: checkColumnEnumNotice, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnSetNotice, + Desc: "不建议使用 SET 类型", + Annotation: "集合的修改需要重新定义列,后期修改的代价大,建议在业务层实现", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + Message: "不建议使用 SET 类型", + AllowOffline: true, + Func: checkColumnSetNotice, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnBlobNotice, + Desc: "不建议使用 BLOB 或 TEXT 类型", + Annotation: "BLOB 或 TEXT 类型消耗大量的网络和IO带宽,同时在该表上的DML操作都会变得很慢", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + Message: "不建议使用 BLOB 或 TEXT 类型", + AllowOffline: true, + Func: checkColumnBlobNotice, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckExplainAccessTypeAll, + //Value: "10000", + Desc: "全表扫描时,扫描行数不建议超过指定行数(默认值:10000)", + Annotation: "全表扫描时,扫描行数不建议超过指定行数是为了避免性能问题;具体规则阈值可以根据业务需求调整,默认值:10000;如果设置为0,全表扫描都会触发规则", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "10000", + Desc: "最大扫描行数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "该查询使用了全表扫描并且扫描行数为%v", + AllowOffline: false, + Func: checkExplain, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckExplainExtraUsingFilesort, + Desc: "不建议使用文件排序", + Annotation: "大数据量的情况下,文件排序意味着SQL性能较低,会增加OS的开销,影响数据库性能", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用文件排序", + AllowOffline: false, + Func: checkExplain, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckExplainExtraUsingTemporary, + Desc: "不建议使用临时表", + Annotation: "大数据量的情况下,临时表意味着SQL性能较低,会增加OS的开销,影响数据库性能", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用临时表", + AllowOffline: false, + Func: checkExplain, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckCreateView, + Desc: "禁止使用视图", + Annotation: "视图的查询性能较差,同时基表结构变更,需要对视图进行维护,如果视图可读性差且包含复杂的逻辑,都会增加维护的成本", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + Message: "禁止使用视图", + AllowOffline: true, + Func: checkCreateView, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckCreateTrigger, + Desc: "禁止使用触发器", + Annotation: "触发器难以开发和维护,不能高效移植,且在复杂的逻辑以及高并发下,容易出现死锁影响业务", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + Message: "禁止使用触发器", + AllowOffline: true, + Func: checkCreateTrigger, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckCreateFunction, + Desc: "禁止使用自定义函数", + Annotation: "自定义函数,维护较差,且依赖性高会导致SQL无法跨库使用", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + Message: "禁止使用自定义函数", + AllowOffline: true, + Func: checkCreateFunction, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckCreateProcedure, + Desc: "禁止使用存储过程", + Annotation: "存储过程在一定程度上会使程序难以调试和拓展,各种数据库的存储过程语法相差很大,给将来的数据库移植带来很大的困难,且会极大的增加出现BUG的概率", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + Message: "禁止使用存储过程", + AllowOffline: true, + Func: checkCreateProcedure, + }, + { + Rule: driverV2.Rule{ + Name: DDLDisableTypeTimestamp, + Desc: "不建议使用TIMESTAMP字段", + Annotation: "TIMESTAMP 有最大值限制('2038-01-19 03:14:07' UTC),且会时区转换的问题", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + }, + Message: "不建议使用TIMESTAMP字段", + AllowOffline: true, + Func: disableUseTypeTimestampField, + }, + { + Rule: driverV2.Rule{ //select a as id, id , b as user from mysql.user; + Name: DMLCheckAlias, + Desc: "别名不建议与表或列的名字相同", + Annotation: "表或列的别名与其真实名称相同, 这样的别名会使得查询更难去分辨", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "这些别名(%v)与列名或表名相同", + Func: checkAlias, + }, + { + Rule: driverV2.Rule{ //ALTER TABLE test CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; + Name: DDLHintUpdateTableCharsetWillNotUpdateFieldCharset, + Desc: "不建议修改表的默认字符集", + Annotation: "修改表的默认字符集,只会影响后续新增的字段,不会修表已有字段的字符集;如需修改整张表所有字段的字符集建议开启此规则", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + }, + Message: "不建议修改表的默认字符集", + Func: hintUpdateTableCharsetWillNotUpdateFieldCharset, + }, { + Rule: driverV2.Rule{ //ALTER TABLE tbl DROP COLUMN col; + Name: DDLHintDropColumn, + Desc: "禁止进行删除列的操作", + Annotation: "业务逻辑与删除列依赖未完全消除,列被删除后可能导致程序异常(无法正常读写)的情况;开启该规则,SQLE将提醒删除列为高危操作", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "禁止进行删除列的操作", + Func: hintDropColumn, + }, { + Rule: driverV2.Rule{ //ALTER TABLE tbl DROP PRIMARY KEY; + Name: DDLHintDropPrimaryKey, + Desc: "禁止进行删除主键的操作", + Annotation: "删除已有约束会影响已有业务逻辑;开启该规则,SQLE将提醒删除主键为高危操作", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "禁止进行删除主键的操作", + Func: hintDropPrimaryKey, + }, { + Rule: driverV2.Rule{ //ALTER TABLE tbl DROP FOREIGN KEY a; + Name: DDLHintDropForeignKey, + Desc: "禁止进行删除外键的操作", + Annotation: "删除已有约束会影响已有业务逻辑;开启该规则,SQLE将提醒删除外键为高危操作", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "禁止进行删除外键的操作", + Func: hintDropForeignKey, + }, + { + Rule: driverV2.Rule{ //select * from user where id like "a"; + Name: DMLNotRecommendNotWildcardLike, + Desc: "不建议使用没有通配符的 LIKE 查询", + Annotation: "不包含通配符的 LIKE 查询逻辑上与等值查询相同,建议使用等值查询替代", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用没有通配符的 LIKE 查询", + Func: notRecommendNotWildcardLike, + }, { + Rule: driverV2.Rule{ //SELECT * FROM tb WHERE col IN (NULL); + Name: DMLHintInNullOnlyFalse, + Desc: "避免使用 IN (NULL) 或者 NOT IN (NULL)", + Annotation: "查询条件永远非真,这将导致查询无匹配到的结果", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "避免使用IN (NULL)/NOT IN (NULL) ,该用法永远非真将导致条件失效", + Func: hintInNullOnlyFalse, + }, { + Rule: driverV2.Rule{ //select * from user where id in (a); + Name: DMLNotRecommendIn, + Desc: "不建议使用IN", + Annotation: "当IN值过多时,有可能会导致查询进行全表扫描,使得MySQL性能急剧下降", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用IN", + Func: notRecommendIn, + }, + { + Rule: driverV2.Rule{ //select * from user where id = ' 1'; + Name: DMLCheckSpacesAroundTheString, + Desc: "引号中的字符串开头或结尾不建议包含空格", + Annotation: "字符串前后存在空格将可能导致查询判断逻辑出错,如在MySQL 5.5中'a'和'a '在查询中被认为是相同的值", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "引号中的字符串开头或结尾不建议包含空格", + Func: checkSpacesAroundTheString, + }, { + Rule: driverV2.Rule{ //CREATE TABLE tb (a varchar(10) default '“'); + Name: DDLCheckFullWidthQuotationMarks, + Desc: "DDL语句中不建议使用中文全角引号", + Annotation: "建议开启此规则,可避免MySQL会将中文全角引号识别为命名的一部分,执行结果与业务预期不符", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "DDL语句中不建议使用中文全角引号,这可能是书写错误", + Func: checkFullWidthQuotationMarks, + }, { + Rule: driverV2.Rule{ //select name from tbl where id < 1000 order by rand(1) + Name: DMLNotRecommendOrderByRand, + Desc: "不建议使用 ORDER BY RAND()", + Annotation: "ORDER BY RAND()使用了临时表,同时还要对其进行排序,在数据量很大的情况下会增加服务器负载以及增加查询时间", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用 ORDER BY RAND()", + Func: notRecommendOrderByRand, + }, { + Rule: driverV2.Rule{ //select col1,col2 from tbl group by 1 + Name: DMLNotRecommendGroupByConstant, + Desc: "不建议对常量进行 GROUP BY", + Annotation: "GROUP BY 1 表示按第一列进行GROUP BY;在GROUP BY子句中使用数字,而不是表达式或列名称,当查询列顺序改变时,会导致查询逻辑出现问题", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议对常量进行 GROUP BY", + Func: notRecommendGroupByConstant, + }, { + Rule: driverV2.Rule{ //select c1,c2,c3 from t1 where c1='foo' order by c2 desc, c3 asc + Name: DMLCheckSortDirection, + Desc: "不建议在 ORDER BY 语句中对多个不同条件使用不同方向的排序", + Annotation: "在 MySQL 8.0 之前当 ORDER BY 多个列指定的排序方向不同时将无法使用已经建立的索引。在MySQL8.0 之后可以建立对应的排序顺序的联合索引来优化", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议在 ORDER BY 语句中对多个不同条件使用不同方向的排序", + Func: checkSortDirection, + }, { + Rule: driverV2.Rule{ //select col1,col2 from tbl group by 1 + Name: DMLHintGroupByRequiresConditions, + Desc: "建议为GROUP BY语句添加ORDER BY条件", + Annotation: "在5.7中,MySQL默认会对’GROUP BY col1, …’按如下顺序’ORDER BY col1,…’隐式排序,导致产生无谓的排序,带来额外的开销;在8.0中,则不会出现这种情况。如果不需要排序建议显示添加’ORDER BY NULL’", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "建议为GROUP BY语句添加ORDER BY条件", + Func: hintGroupByRequiresConditions, + }, { + Rule: driverV2.Rule{ //select description from film where title ='ACADEMY DINOSAUR' order by length-language_id; + Name: DMLNotRecommendGroupByExpression, + Desc: "不建议ORDER BY 的条件为表达式", + Annotation: "当ORDER BY条件为表达式或函数时会使用到临时表,如果在未指定WHERE或WHERE条件返回的结果集较大时性能会很差", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议ORDER BY 的条件为表达式", + Func: notRecommendGroupByExpression, + }, { + Rule: driverV2.Rule{ //select description from film where title ='ACADEMY DINOSAUR' order by length-language_id; + Name: DMLCheckSQLLength, + Desc: "建议将过长的SQL分解成几个简单的SQL", + Annotation: "过长的SQL可读性较差,难以维护,且容易引发性能问题;具体规则阈值可以根据业务需求调整,默认值:1024", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1024", + Desc: "SQL最大长度", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "建议将过长的SQL分解成几个简单的SQL", + Func: checkSQLLength, + }, { + Rule: driverV2.Rule{ //SELECT s.c_id,count(s.c_id) FROM s where c = test GROUP BY s.c_id HAVING s.c_id <> '1660' AND s.c_id <> '2' order by s.c_id + Name: DMLNotRecommendHaving, + Desc: "不建议使用 HAVING 子句", + Annotation: "对于索引字段,放在HAVING子句中时不会走索引;建议将HAVING子句改写为WHERE中的查询条件,可以在查询处理期间使用索引,提高SQL的执行效率", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用 HAVING 子句", + Func: notRecommendHaving, + }, { + Rule: driverV2.Rule{ //delete from tbl + Name: DMLHintUseTruncateInsteadOfDelete, + Desc: "删除全表时建议使用 TRUNCATE 替代 DELETE", + Annotation: "TRUNCATE TABLE 比 DELETE 速度快,且使用的系统和事务日志资源少,同时TRUNCATE后表所占用的空间会被释放,而DELETE后需要手工执行OPTIMIZE才能释放表空间", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "删除全表时建议使用 TRUNCATE 替代 DELETE", + Func: hintUseTruncateInsteadOfDelete, + }, { + Rule: driverV2.Rule{ //update mysql.func set name ="hello"; + Name: DMLNotRecommendUpdatePK, + Desc: "不建议UPDATE主键", + Annotation: "主键索引数据列的顺序就是表记录的物理存储顺序,频繁更新主键将导致整个表记录的顺序的调整,会耗费相当大的资源", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "不建议UPDATE主键", + Func: notRecommendUpdatePK, + }, { + Rule: driverV2.Rule{ //create table t(c1 int,c2 int,c3 int,c4 int,c5 int,c6 int); + Name: DDLCheckColumnQuantity, + Desc: "表的列数不建议超过阈值", + Annotation: "避免在OLTP系统上做宽表设计,后期对性能影响很大;具体规则阈值可根据业务需求调整,默认值:40", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "40", + Desc: "最大列数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "表的列数不建议超过阈值", + Func: checkColumnQuantity, + AllowOffline: true, + }, { + Rule: driverV2.Rule{ //CREATE TABLE `tb2` ( `id` int(11) DEFAULT NULL, `col` char(10) CHARACTER SET utf8 DEFAULT NULL) + Name: DDLRecommendTableColumnCharsetSame, + Desc: "建议列与表使用同一个字符集", + Annotation: "统一字符集可以避免由于字符集转换产生的乱码,不同的字符集进行比较前需要进行转换会造成索引失效", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + }, + Message: "建议列与表使用同一个字符集", + Func: recommendTableColumnCharsetSame, + }, { + Rule: driverV2.Rule{ //CREATE TABLE tab (a INT(1)); + Name: DDLCheckColumnTypeInteger, + Desc: "整型定义建议采用 INT(10) 或 BIGINT(20)", + Annotation: "INT(M) 或 BIGINT(M),M 表示最大显示宽度,可存储最大值的宽度分别为10、20,采用 INT(10) 或 BIGINT(20)可避免发生显示截断的可能", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + Message: "整型定义建议采用 INT(10) 或 BIGINT(20)", + Func: checkColumnTypeInteger, + }, { + Rule: driverV2.Rule{ //CREATE TABLE tab (a varchar(3500)); + Name: DDLCheckVarcharSize, + Desc: "定义VARCHAR 长度时不建议大于阈值", + Annotation: "MySQL建立索引时没有限制索引的大小,索引长度会默认采用的该字段的长度,VARCHAR 定义长度越长建立的索引存储大小越大;具体规则阈值可以根据业务需求调整,默认值:1024", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1024", + Desc: "VARCHAR最大长度", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "定义VARCHAR 长度时不建议大于阈值, 阈值为%d", + Func: checkVarcharSize, + }, { + Rule: driverV2.Rule{ //select id from t where substring(name,1,3)='abc' + Name: DMLNotRecommendFuncInWhere, + Desc: "应避免在 WHERE 条件中使用函数或其他运算符", + Annotation: "函数或运算符会导致查询无法利用表中的索引,该查询将会全表扫描,性能较差", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "应避免在 WHERE 条件中使用函数或其他运算符", + Func: notRecommendFuncInWhere, + }, { + Rule: driverV2.Rule{ //SELECT SYSDATE(); + Name: DMLNotRecommendSysdate, + Desc: "不建议使用 SYSDATE() 函数", + Annotation: "当SYSDATE()函数在基于STATEMENT模式的主从环境下可能造成数据的不一致,因为语句在主库中执行到日志传递到备库,存在时间差,到备库执行的时候就会变成不同的时间值,建议采取ROW模式的复制环境", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用 SYSDATE() 函数", + Func: notRecommendSysdate, + }, { + Rule: driverV2.Rule{ //SELECT SUM(COL) FROM tbl; + Name: DMLHintSumFuncTips, + Desc: "避免使用 SUM(COL)", + Annotation: "当某一列的值全是NULL时,COUNT(COL)的返回结果为0,但SUM(COL)的返回结果为NULL,因此使用SUM()时需注意NPE问题(指数据返回NULL);如业务需避免NPE问题,建议开启此规则", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "避免使用 SUM(COL) ,该用法存在返回NULL值导致程序空指针的风险", + Func: hintSumFuncTips, + }, { + Rule: driverV2.Rule{ + Name: DMLHintCountFuncWithCol, + Desc: "避免使用 COUNT(COL)", + Annotation: "建议使用COUNT(*),因为使用 COUNT(COL) 需要对表进行全表扫描,这可能会导致性能下降。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "避免使用 COUNT(COL)", + Func: hintCountFuncWithCol, + AllowOffline: true, + }, { + Rule: driverV2.Rule{ + Name: DDLCheckColumnQuantityInPK, + Desc: "主键包含的列数不建议超过阈值", + Annotation: "主建中的列过多,会导致二级索引占用更多的空间,同时增加索引维护的开销;具体规则阈值可根据业务需求调整,默认值:2", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "2", + Desc: "最大列数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "主键包含的列数不建议超过阈值", + Func: checkColumnQuantityInPK, + }, { + Rule: driverV2.Rule{ //select col1,col2 from tbl where name=xx limit 10 + Name: DMLHintLimitMustBeCombinedWithOrderBy, + Desc: "LIMIT 查询建议使用ORDER BY", + Annotation: "没有ORDER BY的LIMIT会导致非确定性的结果可能与业务需求不符,这取决于执行计划", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "LIMIT 查询建议使用ORDER BY", + Func: hintLimitMustBeCombinedWithOrderBy, + }, + { + Rule: driverV2.Rule{ //TRUNCATE TABLE tbl_name + Name: DMLHintTruncateTips, + Desc: "不建议使用TRUNCATE操作", + Annotation: "TRUNCATE是DLL,数据不能回滚,在没有备份情况下,谨慎使用TRUNCATE", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用TRUNCATE操作", + Func: hintTruncateTips, + }, { + Rule: driverV2.Rule{ //delete from t where col = 'condition' + Name: DMLHintDeleteTips, + Desc: "建议在执行DELETE/DROP/TRUNCATE等操作前进行备份", + Annotation: "DROP/TRUNCATE是DDL,操作立即生效,不会写入日志,所以无法回滚,在执行高危操作之前对数据进行备份是很有必要的", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "建议在执行DELETE/DROP/TRUNCATE等操作前进行备份", + Func: hintDeleteTips, + }, { + Rule: driverV2.Rule{ //SELECT BENCHMARK(10, RAND()) + Name: DMLCheckSQLInjectionFunc, + Desc: "不建议使用常见 SQL 注入函数", + Annotation: "攻击者通过SQL注入,可未经授权可访问数据库中的数据,存在盗取用户信息,造成用户数据泄露等安全漏洞问题", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议使用常见 SQL 注入函数", + Func: checkSQLInjectionFunc, + }, { + Rule: driverV2.Rule{ //select col1,col2 from tbl where type!=0 + Name: DMLCheckNotEqualSymbol, + Desc: "建议使用'<>'代替'!='", + Annotation: "'!=' 是非标准的运算符,'<>' 才是SQL中标准的不等于运算符", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "建议使用'<>'代替'!='", + Func: checkNotEqualSymbol, + }, { + Rule: driverV2.Rule{ //select col1,col2,col3 from table1 where col2 in(select col from table2) + Name: DMLNotRecommendSubquery, + Desc: "不推荐使用子查询", + Annotation: "有些情况下,子查询并不能使用到索引,同时对于返回结果集比较大的子查询,会产生大量的临时表,消耗过多的CPU和IO资源,产生大量的慢查询", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDMLConvention, + }, + Message: "不推荐使用子查询", + Func: notRecommendSubquery, + }, { + Rule: driverV2.Rule{ //SELECT * FROM staff WHERE name IN (SELECT NAME FROM customer ORDER BY name LIMIT 1) + Name: DMLCheckSubqueryLimit, + Desc: "不建议在子查询中使用LIMIT", + Annotation: "部分MySQL版本不支持在子查询中进行'LIMIT & IN/ALL/ANY/SOME'", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "不建议在子查询中使用LIMIT", + Func: checkSubqueryLimit, + }, { + Rule: driverV2.Rule{ //CREATE TABLE tbl (a int) AUTO_INCREMENT = 10; + Name: DDLCheckAutoIncrement, + Desc: "表的初始AUTO_INCREMENT值建议为0", + Annotation: "创建表时AUTO_INCREMENT设置为0则自增从1开始,可以避免数据空洞。例如在导出表结构DDL时,表结构内AUTO_INCREMENT通常为当前的自增值,如果建表时没有把AUTO_INCREMENT设置为0,那么通过该DDL进行建表操作会导致自增值从一个无意义数字开始。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + }, + Message: "表的初始AUTO_INCREMENT值建议为0", + Func: checkAutoIncrement, + }, { + Rule: driverV2.Rule{ // rename table t1 to t2; + Name: DDLNotAllowRenaming, + Desc: "禁止使用RENAME或CHANGE对表名字段名进行修改", + Annotation: "RENAME/CHANGE 表名/列名会对线上业务不停机发布造成影响,如需这种操作应当DBA手工干预", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + AllowOffline: true, + Message: "禁止使用RENAME或CHANGE对表名字段名进行修改", + Func: ddlNotAllowRenaming, + }, { + Rule: driverV2.Rule{ + Name: DMLCheckExplainFullIndexScan, + Desc: "不建议对表进行全索引扫描", + Annotation: "在数据量大的情况下索引全扫描严重影响SQL性能。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + AllowOffline: false, + Message: "不建议对表进行全索引扫描", + Func: checkExplain, + }, { + Rule: driverV2.Rule{ + Name: DMLCheckLimitOffsetNum, + Desc: "不建议LIMIT的偏移OFFSET大于阈值", + Annotation: "因为OFFSET指定了结果集的起始位置,如果起始位置过大,那么 MySQL 需要处理更多的数据才能返回结果集,这可能会导致查询性能下降。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "100", + Desc: "offset 大小", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "不建议LIMIT的偏移OFFSET大于阈值,OFFSET=%v(阈值为%v)", + AllowOffline: true, + Func: checkLimitOffsetNum, + }, { + Rule: driverV2.Rule{ + Name: DMLCheckUpdateOrDeleteHasWhere, + Desc: "建议UPDATE/DELETE操作使用WHERE条件", + Annotation: "因为这些语句的目的是修改数据库中的数据,需要使用 WHERE 条件来过滤需要更新或删除的记录,以确保数据的正确性。另外,使用 WHERE 条件还可以提高查询性能。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "建议UPDATE/DELETE操作使用WHERE条件", + AllowOffline: true, + Func: checkUpdateOrDeleteHasWhere, + }, { + Rule: driverV2.Rule{ + Name: DMLCheckSortColumnLength, + Desc: "禁止对长字段排序", + Annotation: "对例如VARCHAR(2000)这样的长字段进行ORDER BY、DISTINCT、GROUP BY、UNION之类的操作,会引发排序,有性能隐患", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "2000", + Desc: "可排序字段的最大长度", + Type: params.ParamTypeInt, + }, + }, + }, + AllowOffline: false, + Message: "长度超过阈值的字段不建议用于ORDER BY、DISTINCT、GROUP BY、UNION,这些字段有:%v", + Func: checkSortColumnLength, + }, { + Rule: driverV2.Rule{ + Name: AllCheckPrepareStatementPlaceholders, + Desc: "绑定的变量个数不建议超过阈值", + Annotation: "因为过度使用绑定变量会增加查询的复杂度,从而降低查询性能。过度使用绑定变量还会增加维护成本。默认阈值:100", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "100", + Desc: "最大绑定变量数量", + Type: params.ParamTypeInt, + }, + }, + }, + AllowOffline: true, + Message: "使用绑定变量数量为 %v,不建议超过设定阈值 %v", + Func: checkPrepareStatementPlaceholders, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckExplainExtraUsingIndexForSkipScan, + Desc: "不建议对表进行索引跳跃扫描", + Annotation: "索引扫描是跳跃扫描,未遵循最左匹配原则,可能降低索引的使用效率,影响查询性能", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + AllowOffline: false, + Message: "不建议对表进行索引跳跃扫描", + Func: checkExplain, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckAffectedRows, + Desc: "UPDATE/DELETE操作影响行数不建议超过阈值", + Annotation: "如果 DML 操作影响行数过多,会导致查询性能下降,因为需要扫描更多的数据。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "10000", + Desc: "最大影响行数", + Type: params.ParamTypeInt, + }, + }, + }, + AllowOffline: false, + Message: "UPDATE/DELETE操作影响行数不建议超过阈值,影响行数为 %v,超过设定阈值 %v", + Func: checkAffectedRows, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckSameTableJoinedMultipleTimes, + Desc: "不建议对同一张表连接多次", + Annotation: "如果对单表查询多次,会导致查询性能下降。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + AllowOffline: false, + Message: "表%v被连接多次", + Func: checkSameTableJoinedMultipleTimes, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckExplainUsingIndex, + Desc: "SQL查询条件需要走索引", + Annotation: "使用索引可以显著提高SQL查询的性能。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + AllowOffline: false, + Message: "建议使用索引以优化 SQL 查询性能", + Func: checkExplain, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckInsertSelect, + Desc: "不建议使用INSERT ... SELECT", + Annotation: "使用 INSERT ... SELECT 在默认事务隔离级别下,可能会导致对查询的表施加表级锁。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + AllowOffline: true, + Message: "不建议使用INSERT ... SELECT", + Func: checkInsertSelect, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckAggregate, + Desc: "不建议使用聚合函数", + Annotation: "不建议使用SQL聚合函数,是为了确保查询的简单性、高性能和数据一致性。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + AllowOffline: true, + Message: "不建议使用聚合函数计算", + Func: checkAggregateFunc, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnNotNULL, + Desc: "表字段建议有NOT NULL约束", + Annotation: "表字段建议有 NOT NULL 约束,可确保数据的完整性,防止插入空值,提升查询准确性。", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + AllowOffline: false, + Message: "建议字段%v设置NOT NULL约束", + Func: checkColumnNotNull, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckIndexSelectivity, + Desc: "建议连库查询时,确保SQL执行计划中使用的索引区分度大于阈值", + Annotation: "确保SQL执行计划中使用的高索引区分度,有助于提升查询性能并优化查询效率。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "70", + Desc: "可选择性(百分比)", + Type: params.ParamTypeInt, + }, + }, + }, + AllowOffline: false, + Message: "索引:%v,未超过区分度阈值:%v,建议使用超过阈值的索引。", + Func: checkIndexSelectivity, + }, + { + // 该规则只适用于库表元数据扫描并且需要与停用上线审核模式规则一起使用 + Rule: driverV2.Rule{ + Name: DDLCheckTableRows, + Desc: "表行数超过阈值,建议对表进行拆分", + Annotation: "当表行数超过阈值时,对表进行拆分有助于提高数据库性能和查询速度。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeUsageSuggestion, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "1000", + Desc: "表行数(万)", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "表行数超过阈值,建议对表进行拆分", + Func: checkTableRows, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckCompositeIndexDistinction, + Desc: "建议在组合索引中将区分度高的字段靠前放", + Annotation: "将区分度高的字段靠前放置在组合索引中有助于提高索引的查询性能,因为它能更快地减小数据范围,提高检索效率。", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + AllowOffline: false, + Message: "建议在组合索引中将区分度高的字段靠前放,%v", + Func: checkCompositeIndexSelectivity, + }, + { + Rule: driverV2.Rule{ + Name: DDLAvoidText, + Desc: "使用TEXT 类型的字段建议和原表进行分拆,与原表主键单独组成另外一个表进行存放", + Annotation: "将TEXT类型的字段与原表主键分拆成另一个表可以提高数据库性能和查询速度,减少不必要的 I/O 操作。", + Level: driverV2.RuleLevelNotice, + Category: RuleTypeDDLConvention, + }, + AllowOffline: true, + Message: "字段:%v为TEXT类型,建议和原表进行分拆,与原表主键单独组成另外一个表进行存放", + Func: checkText, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckSelectRows, + Desc: "查询数据量超过阈值,筛选条件必须带上主键或者索引", + Annotation: "筛选条件必须带上主键或索引可提高查询性能和减少全表扫描的成本。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "10", + Desc: "查询数据量(万)", + Type: params.ParamTypeInt, + }, + }, + }, + AllowOffline: false, + Message: "查询数据量超过阈值,筛选条件必须带上主键或者索引", + Func: checkSelectRows, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckScanRows, + Desc: "扫描行数超过阈值,筛选条件必须带上主键或者索引", + Annotation: "筛选条件必须带上主键或索引可降低数据库查询的时间复杂度,提高查询效率。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "10", + Desc: "扫描行数量(万)", + Type: params.ParamTypeInt, + }, + }, + }, + AllowOffline: false, + Message: "扫描行数超过阈值,筛选条件必须带上主键或者索引", + Func: checkScanRows, + }, + { + Rule: driverV2.Rule{ + Name: DMLMustUseLeftMostPrefix, + Desc: "使用联合索引时,必须使用联合索引的首字段", + Annotation: "使用联合索引时,不包含首字段会导致联合索引失效", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexInvalidation, + }, + AllowOffline: false, + Message: "使用联合索引时,必须使用联合索引的首字段", + Func: mustMatchLeftMostPrefix, + }, + { + Rule: driverV2.Rule{ + Name: DMLMustMatchLeftMostPrefix, + Desc: "禁止对联合索引左侧字段进行IN 、OR等非等值查询", + Annotation: "对联合索引左侧字段进行IN 、OR等非等值查询会导致联合索引失效", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexInvalidation, + }, + AllowOffline: false, + Message: "对联合索引左侧字段进行IN 、OR等非等值查询会导致联合索引失效", + Func: mustMatchLeftMostPrefix, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckJoinFieldUseIndex, + Desc: "JOIN字段必须包含索引", + Annotation: "JOIN字段包含索引可提高连接操作的性能和查询速度。", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexInvalidation, + }, + AllowOffline: false, + Message: "JOIN字段必须包含索引", + Func: checkJoinFieldUseIndex, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckJoinFieldCharacterSetAndCollation, + Desc: "连接表字段的字符集和排序规则必须一致", + Annotation: "连接表字段的字符集和排序规则一致可避免数据不一致和查询错误,确保连接操作正确执行。", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexInvalidation, + }, + AllowOffline: false, + Message: "连接表字段的字符集和排序规则必须一致", + Func: checkJoinFieldCharacterSetAndCollation, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckMathComputationOrFuncOnIndex, + Desc: "禁止对索引列进行数学运算和使用函数", + Annotation: "对索引列进行数学运算和使用函数会导致索引失效,从而导致全表扫描,影响查询性能。", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexInvalidation, + }, + AllowOffline: false, + Message: "禁止对索引列进行数学运算和使用函数", + Func: checkMathComputationOrFuncOnIndex, + }, + { + Rule: driverV2.Rule{ + Name: DMLSQLExplainLowestLevel, + Desc: "SQL执行计划中type字段建议满足规定的级别", + Annotation: "验证 SQL 执行计划中的 type 字段,确保满足要求级别,以保证查询性能。", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "range,ref,const,eq_ref,system,NULL", + Desc: "查询计划type等级,以英文逗号隔开", + Type: params.ParamTypeString, + }, + }, + }, + AllowOffline: false, + Message: "建议修改SQL,确保执行计划中type字段可以满足规定中的任一等级:%v", + Func: checkSQLExplainLowestLevel, + }, + { + Rule: driverV2.Rule{ + Name: DDLAvoidFullText, + Desc: "禁止使用全文索引", + Annotation: "全文索引的使用会增加存储开销,并对写操作性能产生一定影响。", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + AllowOffline: true, + Message: "禁止使用全文索引", + Func: avoidFullText, + }, + { + Rule: driverV2.Rule{ + Name: DDLAvoidGeometry, + Desc: "禁止使用空间字段和空间索引", + Annotation: "使用空间字段和空间索引会增加存储需求,对数据库性能造成一定影响", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + AllowOffline: true, + Message: "禁止使用空间字段和空间索引", + Func: avoidGeometry, + }, + { + Rule: driverV2.Rule{ + Name: DMLAvoidWhereEqualNull, + Desc: "WHERE子句中禁止将NULL值与其他字段或值进行比较运算", + Annotation: "NULL在SQL中属于特殊值,无法与普通值进行比较。例如:column = NULL恒为false,即使column存在null值也不会查询出来,所以column = NULL应该写为column is NULL", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + AllowOffline: true, + Message: "WHERE子句中禁止将NULL值与其他字段或值进行比较运算", + Func: avoidWhereEqualNull, + }, + { + Rule: driverV2.Rule{ + Name: DDLAvoidEvent, + Desc: "禁止使用event", + Annotation: "使用event会增加数据库的维护难度和依赖性,并且也会造成安全问题。", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + AllowOffline: true, + Message: "禁止使用event", + Func: avoidEvent, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckCharLength, + Desc: "禁止char, varchar类型字段字符长度总和超过阈值", + Annotation: "使用过长或者过多的varchar,char字段可能会增加业务逻辑的复杂性;如果字段平均长度过大时,会占用更多的存储空间。", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "2000", + Desc: "字符长度", + Type: params.ParamTypeInt, + }, + }, + }, + AllowOffline: false, + Message: "禁止char, varchar类型字段字符长度总和超过阈值 %v", + Func: checkCharLength, + }, +} diff --git a/sqle/driver/mysql/rule/rule_list_trial.go b/sqle/driver/mysql/rule/rule_list_trial.go new file mode 100644 index 0000000000..56541514f0 --- /dev/null +++ b/sqle/driver/mysql/rule/rule_list_trial.go @@ -0,0 +1,223 @@ +//go:build trial +// +build trial + +package rule + +import ( + driverV2 "github.com/actiontech/sqle/sqle/driver/v2" + "github.com/actiontech/sqle/sqle/pkg/params" + "github.com/pingcap/parser/ast" +) + +func init() { + RuleHandlers = []RuleHandler{ + { + Rule: driverV2.Rule{ + Name: DMLCheckFuzzySearch, + Desc: "禁止使用全模糊搜索或左模糊搜索", + Annotation: "使用全模糊搜索或左模糊搜索将导致查询无法使用索引,导致全表扫描", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "禁止使用全模糊搜索或左模糊搜索", + AllowOffline: true, + Func: checkSelectWhere, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckJoinFieldType, + Desc: "建议JOIN字段类型保持一致", + Annotation: "JOIN字段类型不一致会导致类型不匹配发生隐式准换,建议开启此规则,避免索引失效", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDMLConvention, + }, + Message: "建议JOIN字段类型保持一致, 否则会导致隐式转换", + AllowOffline: false, + Func: checkJoinFieldType, + }, + { + Rule: driverV2.Rule{ + Name: DDLRecommendTableColumnCharsetSame, + Desc: "建议列与表使用同一个字符集", + Annotation: "统一字符集可以避免由于字符集转换产生的乱码,不同的字符集进行比较前需要进行转换会造成索引失效", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeDDLConvention, + }, + Message: "建议列与表使用同一个字符集", + Func: recommendTableColumnCharsetSame, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnTimestampWithoutDefault, + Desc: "TIMESTAMP 类型的列必须添加默认值", + Annotation: "TIMESTAMP添加默认值,可避免出现全为0的日期格式与业务预期不符", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "TIMESTAMP 类型的列必须添加默认值", + AllowOffline: true, + Func: checkColumnTimestampWithoutDefault, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIndexPrefix, + Desc: "建议普通索引使用固定前缀", + Annotation: "通过配置该规则可以规范指定业务的索引命名规则,具体命名规范可以自定义设置,默认提示值:idx_", + Level: driverV2.RuleLevelError, + Category: RuleTypeNamingConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "idx_", + Desc: "索引前缀", + Type: params.ParamTypeString, + }, + }, + }, + Message: "建议普通索引要以\"%v\"为前缀", + AllowOffline: true, + Func: checkIndexPrefix, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckPKNotExist, + Desc: "表必须有主键", + Annotation: "主键使数据达到全局唯一,可提高数据检索效率", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexingConvention, + }, + Message: "表必须有主键", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, + Func: checkPrimaryKey, + }, + { + Rule: driverV2.Rule{ + Name: ConfigDMLExplainPreCheckEnable, + Desc: "使用EXPLAIN加强预检查能力", + Annotation: "通过 EXPLAIN 的形式将待上线的DML进行SQL是否能正确执行的检查,提前发现语句的错误,提高上线成功率", + Level: driverV2.RuleLevelWarn, + Category: RuleTypeGlobalConfig, + }, + Func: nil, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckIndexCount, + Desc: "索引个数建议不超过阈值", + Annotation: "在表上建立的每个索引都会增加存储开销,索引对于插入、删除、更新操作也会增加处理上的开销,太多与不充分、不正确的索引对性能都毫无益处;具体规则阈值可以根据业务需求调整,默认值:5", + Level: driverV2.RuleLevelNotice, + //Value: "5", + Category: RuleTypeIndexingConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "5", + Desc: "最大索引个数", + Type: params.ParamTypeInt, + }, + }, + }, + Message: "索引个数建议不超过%v个", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}, &ast.CreateIndexStmt{}}, + Func: checkIndex, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckPKWithoutAutoIncrement, + Desc: "主键建议使用自增", + Annotation: "自增主键,数字型速度快,而且是增量增长,占用空间小,更快速的做数据插入操作,避免增加维护索引的开销", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexingConvention, + }, + Message: "主键建议使用自增", + AllowOffline: true, + NotAllowOfflineStmts: []ast.Node{&ast.AlterTableStmt{}}, + NotSupportExecutedSQLAuditStmts: []ast.Node{&ast.AlterTableStmt{}}, + Func: checkPrimaryKey, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckObjectNameUsingKeyword, + Desc: "数据库对象命名禁止使用保留字", + Annotation: "通过配置该规则可以规范指定业务的数据对象命名规则,避免发生冲突,以及混淆", + Level: driverV2.RuleLevelError, + Category: RuleTypeNamingConvention, + }, + Message: "数据库对象命名禁止使用保留字 %s", + AllowOffline: true, + Func: checkNewObjectName, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckMathComputationOrFuncOnIndex, + Desc: "禁止对索引列进行数学运算和使用函数", + Annotation: "对索引列进行数学运算和使用函数会导致索引失效,从而导致全表扫描,影响查询性能。", + Level: driverV2.RuleLevelError, + Category: RuleTypeIndexInvalidation, + }, + AllowOffline: false, + Message: "禁止对索引列进行数学运算和使用函数", + Func: checkMathComputationOrFuncOnIndex, + }, + { + Rule: driverV2.Rule{ + Name: DDLDisableDropStatement, + Desc: "禁止除索引外的DROP操作", + Annotation: "DROP是DDL,数据变更不会写入日志,无法进行回滚;建议开启此规则,避免误删除操作", + Level: driverV2.RuleLevelError, + Category: RuleTypeUsageSuggestion, + }, + Message: "禁止除索引外的DROP操作", + AllowOffline: true, + Func: disableDropStmt, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckScanRows, + Desc: "扫描行数超过阈值,筛选条件必须带上主键或者索引", + Annotation: "筛选条件必须带上主键或索引可降低数据库查询的时间复杂度,提高查询效率。", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + Params: params.Params{ + ¶ms.Param{ + Key: DefaultSingleParamKeyName, + Value: "10", + Desc: "扫描行数量(万)", + Type: params.ParamTypeInt, + }, + }, + }, + AllowOffline: false, + Message: "扫描行数超过阈值,筛选条件必须带上主键或者索引", + Func: checkScanRows, + }, + { + Rule: driverV2.Rule{ + Name: DMLCheckWhereIsInvalid, + Desc: "禁止使用没有WHERE条件或者WHERE条件恒为TRUE的SQL", + Annotation: "SQL缺少WHERE条件在执行时会进行全表扫描产生额外开销,建议在大数据量高并发环境下开启,避免影响数据库查询性能", + Level: driverV2.RuleLevelError, + Category: RuleTypeDMLConvention, + }, + Message: "禁止使用没有WHERE条件或者WHERE条件恒为TRUE的SQL", + AllowOffline: true, + Func: checkSelectWhere, + }, + { + Rule: driverV2.Rule{ + Name: DDLCheckColumnWithoutDefault, + Desc: "除了自增列及大字段列之外,每个列都必须添加默认值", + Annotation: "列添加默认值,可避免列为NULL值时对查询的影响", + Level: driverV2.RuleLevelError, + Category: RuleTypeDDLConvention, + }, + Message: "除了自增列及大字段列之外,每个列都必须添加默认值", + AllowOffline: true, + Func: checkColumnWithoutDefault, + }, + } +} diff --git a/sqle/errors/errors.go b/sqle/errors/errors.go index 64f6063c1e..d3e91ff525 100644 --- a/sqle/errors/errors.go +++ b/sqle/errors/errors.go @@ -138,3 +138,7 @@ func NewNotSupportGetTaskAnalysisDataErr() error { func NewTaskNoExistOrNoAccessErr() error { return New(DataNotExist, fmt.Errorf("task is not exist or you can't access it")) } + +func NewInstanceNoExistErr() error { + return New(DataNotExist, fmt.Errorf("instance is not exist")) +} diff --git a/sqle/model/audit_plan.go b/sqle/model/audit_plan.go index 31095bb2fd..6facc48526 100644 --- a/sqle/model/audit_plan.go +++ b/sqle/model/audit_plan.go @@ -15,13 +15,13 @@ import ( type AuditPlan struct { Model - ProjectId uint `gorm:"index; not null"` - Name string `json:"name" gorm:"not null;index"` - CronExpression string `json:"cron_expression" gorm:"not null"` - DBType string `json:"db_type" gorm:"not null"` - Token string `json:"token" gorm:"not null"` - InstanceName string `json:"instance_name"` - CreateUserID uint + ProjectId ProjectUID `gorm:"index; not null"` + Name string `json:"name" gorm:"not null;index"` + CronExpression string `json:"cron_expression" gorm:"not null"` + DBType string `json:"db_type" gorm:"not null"` + Token string `json:"token" gorm:"not null"` + InstanceName string `json:"instance_name"` + CreateUserID string `json:"create_user_id"` InstanceDatabase string `json:"instance_database"` Type string `json:"type"` RuleTemplateName string `json:"rule_template_name"` @@ -34,7 +34,9 @@ type AuditPlan struct { WebHookURL string `json:"web_hook_url"` WebHookTemplate string `json:"web_hook_template"` - CreateUser *User `gorm:"foreignkey:CreateUserId"` + ProjectStatus string `gorm:"default:'active'"` // dms-todo: 暂时将项目状态放在这里 + + // CreateUser *User // TODO 移除 `gorm:"foreignkey:CreateUserId"` Instance *Instance `gorm:"foreignkey:InstanceName;association_foreignkey:Name"` AuditPlanSQLs []*AuditPlanSQLV2 `gorm:"foreignkey:AuditPlanID"` } @@ -110,9 +112,8 @@ func (s *Storage) GetAuditPlans() ([]*AuditPlan, error) { func (s *Storage) GetActiveAuditPlans() ([]*AuditPlan, error) { var aps []*AuditPlan - err := s.db.Model(AuditPlan{}).Preload("Instance"). - Joins("LEFT JOIN projects ON projects.id = audit_plans.project_id"). - Where(fmt.Sprintf("projects.status = '%v'", ProjectStatusActive)). + err := s.db.Model(AuditPlan{}). + Where("project_status = ?", ProjectStatusActive). Find(&aps).Error return aps, errors.New(errors.ConnectStorageError, err) } @@ -137,20 +138,18 @@ func (s *Storage) GetAuditPlanById(id uint) (*AuditPlan, bool, error) { func (s *Storage) GetActiveAuditPlanById(id uint) (*AuditPlan, bool, error) { ap := &AuditPlan{} - err := s.db.Model(AuditPlan{}).Preload("Instance"). - Joins("LEFT JOIN projects ON projects.id = audit_plans.project_id"). - Where(fmt.Sprintf("projects.status = '%v'", ProjectStatusActive)). - Where("audit_plans.id = ?", id).Find(ap).Error + err := s.db.Model(AuditPlan{}). + Where("project_status = ?", ProjectStatusActive). + Where("id = ?", id).Find(ap).Error if err == gorm.ErrRecordNotFound { return ap, false, nil } return ap, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetAuditPlanFromProjectByName(projectName, AuditPlanName string) (*AuditPlan, bool, error) { +func (s *Storage) GetAuditPlanFromProjectByName(projectId, AuditPlanName string) (*AuditPlan, bool, error) { ap := &AuditPlan{} - err := s.db.Model(AuditPlan{}).Preload("Instance").Joins("LEFT JOIN projects ON projects.id = audit_plans.project_id"). - Where("projects.name = ? AND audit_plans.name = ?", projectName, AuditPlanName).Find(ap).Error + err := s.db.Model(AuditPlan{}).Where("project_id = ? AND name = ?", projectId, AuditPlanName).Find(ap).Error if err == gorm.ErrRecordNotFound { return ap, false, nil } @@ -313,35 +312,35 @@ func (s *Storage) UpdateAuditPlanById(id uint, attrs map[string]interface{}) err return errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetAuditPlanTotalByProjectName(projectName string) (uint64, error) { - var count uint64 - err := s.db. - Table("audit_plans"). - Joins("LEFT JOIN projects ON audit_plans.project_id = projects.id"). - Where("projects.name = ?", projectName). - Where("audit_plans.deleted_at IS NULL"). - Count(&count). - Error - return count, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) GetAuditPlanIDsByProjectName(projectName string) ([]uint, error) { - ids := []struct { - ID uint `json:"id"` - }{} - err := s.db.Table("audit_plans"). - Select("audit_plans.id"). - Joins("LEFT JOIN projects ON projects.id = audit_plans.project_id"). - Where("projects.name = ?", projectName). - Find(&ids).Error - - resp := []uint{} - for _, id := range ids { - resp = append(resp, id.ID) - } - - return resp, errors.ConnectStorageErrWrapper(err) -} +// func (s *Storage) GetAuditPlanTotalByProjectName(projectName string) (uint64, error) { +// var count uint64 +// err := s.db. +// Table("audit_plans"). +// Joins("LEFT JOIN projects ON audit_plans.project_id = projects.id"). +// Where("projects.name = ?", projectName). +// Where("audit_plans.deleted_at IS NULL"). +// Count(&count). +// Error +// return count, errors.ConnectStorageErrWrapper(err) +// } + +// func (s *Storage) GetAuditPlanIDsByProjectName(projectName string) ([]uint, error) { +// ids := []struct { +// ID uint `json:"id"` +// }{} +// err := s.db.Table("audit_plans"). +// Select("audit_plans.id"). +// Joins("LEFT JOIN projects ON projects.id = audit_plans.project_id"). +// Where("projects.name = ?", projectName). +// Find(&ids).Error + +// resp := []uint{} +// for _, id := range ids { +// resp = append(resp, id.ID) +// } + +// return resp, errors.ConnectStorageErrWrapper(err) +// } // GetLatestAuditPlanIds 获取所有变更过的记录,包括删除 func (s *Storage) GetLatestAuditPlanRecords(after time.Time) ([]*AuditPlan, error) { @@ -357,15 +356,14 @@ type RiskAuditPlan struct { RiskSqlCOUNT uint `json:"risk_sql_count"` } -func (s *Storage) GetRiskAuditPlan(projectName string) ([]*RiskAuditPlan, error) { +func (s *Storage) GetRiskAuditPlan(projectUid string) ([]*RiskAuditPlan, error) { var RiskAuditPlans []*RiskAuditPlan err := s.db.Model(AuditPlan{}). Select(`reports.id report_id, audit_plans.name audit_plan_name, reports.created_at report_create_at, count(case when JSON_TYPE(report_sqls.audit_results)<>'NULL' then 1 else null end) risk_sql_count`). Joins("left join audit_plan_reports_v2 reports on audit_plans.id=reports.audit_plan_id"). Joins("left join audit_plan_report_sqls_v2 report_sqls on report_sqls.audit_plan_report_id=reports.id"). - Joins("left join projects on projects.id=audit_plans.project_id"). - Where("reports.score<60 and projects.name=? and audit_plans.deleted_at is NULL", projectName). + Where("reports.score<60 and audit_plans.project_id=? and audit_plans.deleted_at is NULL", projectUid). Group("audit_plans.name, reports.created_at, audit_plans.created_at, reports.id"). Order("reports.created_at desc").Scan(&RiskAuditPlans).Error @@ -377,13 +375,12 @@ func (s *Storage) GetRiskAuditPlan(projectName string) ([]*RiskAuditPlan, error) } // 使用子查询获取最新的report时间,然后再获取最新report的sql数量和触发规则的sql数量 -func (s *Storage) GetAuditPlanSQLCountAndTriggerRuleCountByProject(projectName string) (SqlCountAndTriggerRuleCount, error) { +func (s *Storage) GetAuditPlanSQLCountAndTriggerRuleCountByProject(projectUid string) (SqlCountAndTriggerRuleCount, error) { sqlCountAndTriggerRuleCount := SqlCountAndTriggerRuleCount{} subQuery := s.db.Model(&AuditPlan{}). Select("audit_plans.id as audit_plan_id, MAX(audit_plan_reports_v2.created_at) as latest_created_at"). Joins("left join audit_plan_reports_v2 on audit_plan_reports_v2.audit_plan_id=audit_plans.id"). - Joins("left join projects on audit_plans.project_id=projects.id"). - Where("projects.name=? and audit_plans.deleted_at is null and audit_plan_reports_v2.id is not null", projectName). + Where("audit_plans.project_id=? and audit_plans.deleted_at is null and audit_plan_reports_v2.id is not null", projectUid). Group("audit_plans.id"). SubQuery() @@ -391,9 +388,8 @@ func (s *Storage) GetAuditPlanSQLCountAndTriggerRuleCountByProject(projectName s Select("count(report_sqls.id) sql_count, count(case when JSON_TYPE(report_sqls.audit_results)<>'NULL' then 1 else null end) trigger_rule_count"). Joins("left join audit_plan_reports_v2 reports on reports.audit_plan_id=audit_plans.id"). Joins("left join audit_plan_report_sqls_v2 report_sqls on report_sqls.audit_plan_report_id=reports.id"). - Joins("left join projects on audit_plans.project_id=projects.id"). Joins("join (?) as sq on audit_plans.id=sq.audit_plan_id and reports.created_at=sq.latest_created_at", subQuery). - Where("projects.name=? and audit_plans.deleted_at is null", projectName). + Where("audit_plans.project_id=? and audit_plans.deleted_at is null", projectUid). Scan(&sqlCountAndTriggerRuleCount).Error return sqlCountAndTriggerRuleCount, errors.ConnectStorageErrWrapper(err) @@ -405,12 +401,11 @@ type DBTypeAuditPlanCount struct { AuditPlanCount uint `json:"audit_plan_count"` } -func (s *Storage) GetDBTypeAuditPlanCountByProject(projectName string) ([]*DBTypeAuditPlanCount, error) { +func (s *Storage) GetDBTypeAuditPlanCountByProject(projectUid string) ([]*DBTypeAuditPlanCount, error) { dBTypeAuditPlanCounts := []*DBTypeAuditPlanCount{} err := s.db.Model(AuditPlan{}). Select("audit_plans.db_type, audit_plans.type, count(1) audit_plan_count"). - Joins("left join projects on audit_plans.project_id=projects.id"). - Where("projects.name=?", projectName). + Where("audit_plans.project_id=?", projectUid). Group("audit_plans.db_type, audit_plans.type").Scan(&dBTypeAuditPlanCounts).Error return dBTypeAuditPlanCounts, errors.New(errors.ConnectStorageError, err) } diff --git a/sqle/model/audit_plan_list.go b/sqle/model/audit_plan_list.go index 2ecd513f62..d315c9d2d1 100644 --- a/sqle/model/audit_plan_list.go +++ b/sqle/model/audit_plan_list.go @@ -37,16 +37,13 @@ SELECT COUNT(*) var auditPlanBodyTpl = ` {{ define "body" }} -FROM audit_plans -LEFT JOIN users ON audit_plans.create_user_id = users.id -LEFT JOIN projects ON audit_plans.project_id = projects.id +FROM audit_plans WHERE audit_plans.deleted_at IS NULL -AND users.deleted_at IS NULL {{- if not .current_user_is_admin }} AND ( -users.login_name = :current_user_name +audit_plans.create_user_id = :current_user_id {{- if .accessible_instances_name }} OR instance_name IN ( {{ .accessible_instances_name }} ) {{- end }} @@ -69,8 +66,8 @@ AND audit_plans.type = :filter_audit_plan_type AND audit_plans.instance_name = :filter_audit_plan_instance_name {{- end }} -{{- if .filter_project_name }} -AND projects.name = :filter_project_name +{{- if .filter_project_id }} +AND audit_plans.project_id = :filter_project_id {{- end }} {{ end }} diff --git a/sqle/model/audit_plan_list_test.go b/sqle/model/audit_plan_list_test.go index 782aea4400..68537a53c8 100644 --- a/sqle/model/audit_plan_list_test.go +++ b/sqle/model/audit_plan_list_test.go @@ -12,14 +12,11 @@ import ( func TestStorage_GetAuditPlansByReq(t *testing.T) { // 1. test for common user tableAndRowOfSQL := ` - FROM audit_plans - LEFT JOIN users ON audit_plans.create_user_id = users.id - LEFT JOIN projects ON audit_plans.project_id = projects.id - WHERE audit_plans.deleted_at IS NULL - AND users.deleted_at IS NULL - AND ( - users.login_name = ? - ) + FROM + audit_plans +WHERE + audit_plans.deleted_at IS NULL + AND ( audit_plans.create_user_id = ? ) AND audit_plans.db_type = ? ` mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) @@ -33,7 +30,7 @@ func TestStorage_GetAuditPlansByReq(t *testing.T) { "COUNT(*)", }).AddRow("2")) nameFields := map[string]interface{}{ - "current_user_name": 1, + "current_user_id": 1, "filter_audit_plan_db_type": "mysql", "limit": 100, "offset": 10} @@ -47,11 +44,10 @@ func TestStorage_GetAuditPlansByReq(t *testing.T) { // 2. test for admin user tableAndRowOfSQL1 := ` - FROM audit_plans - LEFT JOIN users ON audit_plans.create_user_id = users.id - LEFT JOIN projects ON audit_plans.project_id = projects.id - WHERE audit_plans.deleted_at IS NULL - AND users.deleted_at IS NULL + FROM + audit_plans +WHERE + audit_plans.deleted_at IS NULL ` mockDB, mock, err = sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) assert.NoError(t, err) @@ -66,7 +62,7 @@ func TestStorage_GetAuditPlansByReq(t *testing.T) { mock.ExpectPrepare(fmt.Sprintf(`SELECT COUNT(*) %v`, tableAndRowOfSQL1)). ExpectQuery().WillReturnRows(sqlmock.NewRows([]string{"COUNT(*)"}).AddRow("2")) nameFields = map[string]interface{}{ - "current_user_name": 1, + "current_user_id": 1, "current_user_is_admin": true, "limit": 100, "offset": 10} @@ -120,29 +116,32 @@ func TestStorage_GetAuditPlanSQLsByReq(t *testing.T) { func TestStorage_GetAuditPlanReportsByReq(t *testing.T) { tableAndRowOfSQL := ` - FROM audit_plan_reports_v2 AS reports - JOIN audit_plans ON audit_plans.id = reports.audit_plan_id - JOIN projects ON projects.id = audit_plans.project_id - WHERE reports.deleted_at IS NULL - AND audit_plans.deleted_at IS NULL - AND audit_plans.name = ? - AND projects.name = ? - ORDER BY reports.created_at DESC , reports.id DESC + FROM + audit_plan_reports_v2 AS reports + JOIN audit_plans ON audit_plans.id = reports.audit_plan_id +WHERE + reports.deleted_at IS NULL + AND audit_plans.deleted_at IS NULL + AND audit_plans.name = ? + AND audit_plans.project_id = ? +ORDER BY + reports.created_at DESC , + reports.id DESC ` mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) assert.NoError(t, err) defer mockDB.Close() InitMockStorage(mockDB) mock.ExpectPrepare(fmt.Sprintf(`SELECT reports.id, reports.score , reports.pass_rate, reports.audit_level, reports.created_at %v LIMIT ? OFFSET ?`, tableAndRowOfSQL)). - ExpectQuery().WithArgs("audit_plan_for_jave_repo", "project_1", 100, 10).WillReturnRows(sqlmock.NewRows([]string{ + ExpectQuery().WithArgs("audit_plan_for_jave_repo", "1", 100, 10).WillReturnRows(sqlmock.NewRows([]string{ "id", "score", "pass_rate", "audit_level", "created_at"}). AddRow("1", 100, 1, "normal", "2021-09-01T13:46:13+08:00")) mock.ExpectPrepare(fmt.Sprintf(`SELECT COUNT(*) %v`, tableAndRowOfSQL)). - ExpectQuery().WithArgs("audit_plan_for_jave_repo", "project_1").WillReturnRows(sqlmock.NewRows([]string{"COUNT(*)"}).AddRow("2")) + ExpectQuery().WithArgs("audit_plan_for_jave_repo", "1").WillReturnRows(sqlmock.NewRows([]string{"COUNT(*)"}).AddRow("2")) nameFields := map[string]interface{}{ "audit_plan_name": "audit_plan_for_jave_repo", - "project_name": "project_1", + "project_id": "1", "limit": 100, "offset": 10} result, count, err := GetStorage().GetAuditPlanReportsByReq(nameFields) diff --git a/sqle/model/audit_plan_report.go b/sqle/model/audit_plan_report.go index 8ab009f286..df0208bed0 100644 --- a/sqle/model/audit_plan_report.go +++ b/sqle/model/audit_plan_report.go @@ -48,12 +48,11 @@ func (s *Storage) GetAuditPlanReportSQLV2ByReportIDAndNumber(reportId, number ui return auditPlanReportSQLV2, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetAuditPlanReportByProjectName(projectName string) ([]*AuditPlanReportV2, error) { +func (s *Storage) GetAuditPlanReportByProjectName(projectUid string) ([]*AuditPlanReportV2, error) { auditPlanReportV2Slice := []*AuditPlanReportV2{} err := s.db.Model(&AuditPlanReportV2{}). Joins("left join audit_plans on audit_plans.id=audit_plan_reports_v2.audit_plan_id"). - Joins("left join projects on projects.id=audit_plans.project_id"). - Where("projects.name=? and audit_plans.deleted_at is NULL", projectName).Find(&auditPlanReportV2Slice).Error + Where("audit_plans.project_id=? and audit_plans.deleted_at is NULL", projectUid).Find(&auditPlanReportV2Slice).Error return auditPlanReportV2Slice, errors.ConnectStorageErrWrapper(err) } @@ -64,23 +63,25 @@ type LatestAuditPlanReportScore struct { } // 使用子查询获取最新的report的生成时间,再去获取report相关信息 -func (s *Storage) GetLatestAuditPlanReportScoreFromInstanceByProject(projectName string) ([]*LatestAuditPlanReportScore, error) { +func (s *Storage) GetLatestAuditPlanReportScoreFromInstanceByProject(projectUid string, instanceNames []string) ([]*LatestAuditPlanReportScore, error) { + if len(instanceNames) == 0 { + return nil, nil + } + var latestAuditPlanReportScore []*LatestAuditPlanReportScore subQuery := s.db.Model(&AuditPlanReportV2{}). Select("audit_plans.db_type, audit_plans.instance_name, MAX(audit_plan_reports_v2.created_at) as latest_created_at"). Joins("left join audit_plans on audit_plan_reports_v2.audit_plan_id=audit_plans.id"). - Joins("left join projects on audit_plans.project_id=projects.id"). - Where("projects.name=?", projectName). + Where("audit_plans.project_id=?", projectUid). + Where("audit_plans.instance_name in (?)", instanceNames). Group("audit_plans.db_type, audit_plans.instance_name"). SubQuery() err := s.db.Model(&AuditPlanReportV2{}). Select("audit_plans.db_type, audit_plans.instance_name, audit_plan_reports_v2.score"). Joins("left join audit_plans on audit_plan_reports_v2.audit_plan_id=audit_plans.id"). - Joins("left join projects on audit_plans.project_id=projects.id"). - Joins("left join instances on audit_plans.instance_name=instances.name"). Joins("join (?) as sq on audit_plans.db_type=sq.db_type and audit_plans.instance_name=sq.instance_name and audit_plan_reports_v2.created_at=sq.latest_created_at", subQuery). - Where("projects.name=? and instances.deleted_at is null and audit_plans.deleted_at is null and instances.id is not null", projectName). + Where("audit_plans.project_id=? and audit_plans.deleted_at is null", projectUid). Scan(&latestAuditPlanReportScore).Error return latestAuditPlanReportScore, errors.ConnectStorageErrWrapper(err) @@ -88,7 +89,7 @@ func (s *Storage) GetLatestAuditPlanReportScoreFromInstanceByProject(projectName func (s *Storage) GetReportWithAuditPlanByReportID(reportId int) (auditPlanReportV2 *AuditPlanReportV2, exist bool, err error) { auditPlanReportV2 = &AuditPlanReportV2{} - err = s.db.Preload("AuditPlan").Preload("AuditPlan.CreateUser", UnScopedFunc).Preload("AuditPlanReportSQLs").Where("id=?", reportId).Find(auditPlanReportV2).Error + err = s.db.Preload("AuditPlan").Preload("AuditPlanReportSQLs").Where("id=?", reportId).Find(auditPlanReportV2).Error if err == gorm.ErrRecordNotFound { return auditPlanReportV2, false, nil } diff --git a/sqle/model/audit_plan_report_list.go b/sqle/model/audit_plan_report_list.go index 94a945c8a1..0fce957526 100644 --- a/sqle/model/audit_plan_report_list.go +++ b/sqle/model/audit_plan_report_list.go @@ -31,12 +31,11 @@ var auditPlanReportBodyTpl = ` FROM audit_plan_reports_v2 AS reports JOIN audit_plans ON audit_plans.id = reports.audit_plan_id -JOIN projects ON projects.id = audit_plans.project_id WHERE reports.deleted_at IS NULL AND audit_plans.deleted_at IS NULL AND audit_plans.name = :audit_plan_name -AND projects.name = :project_name +AND audit_plans.project_id = :project_id ORDER BY reports.created_at DESC , reports.id DESC diff --git a/sqle/model/audit_plan_test.go b/sqle/model/audit_plan_test.go index 48e2c37374..a3b37ce51c 100644 --- a/sqle/model/audit_plan_test.go +++ b/sqle/model/audit_plan_test.go @@ -56,38 +56,38 @@ func TestStorage_GetAuditPlanByName(t *testing.T) { assert.NoError(t, err) } -func TestStorage_GetAuditPlanFromProjectByName(t *testing.T) { - // 1. test record exist - mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) - assert.NoError(t, err) - InitMockStorage(mockDB) - mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). - WithArgs("project_1", "audit_plan_for_java_repo1"). - WillReturnRows(sqlmock.NewRows([]string{"name"}).AddRow("audit_plan_1")) - mock.ExpectClose() - ap, exist, err := GetStorage().GetAuditPlanFromProjectByName("project_1", "audit_plan_for_java_repo1") - assert.NoError(t, err) - assert.True(t, exist) - assert.Equal(t, "audit_plan_1", ap.Name) - mockDB.Close() - err = mock.ExpectationsWereMet() - assert.NoError(t, err) - - // 2. test record not exist - mockDB, mock, err = sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) - assert.NoError(t, err) - InitMockStorage(mockDB) - mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). - WithArgs("project_1", "audit_plan_for_java_repo1"). - WillReturnRows(sqlmock.NewRows([]string{"name"})) - mock.ExpectClose() - _, exist, err = GetStorage().GetAuditPlanFromProjectByName("project_1", "audit_plan_for_java_repo1") - assert.NoError(t, err) - assert.False(t, exist) - mockDB.Close() - err = mock.ExpectationsWereMet() - assert.NoError(t, err) -} +// func TestStorage_GetAuditPlanFromProjectByName(t *testing.T) { +// // 1. test record exist +// mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) +// assert.NoError(t, err) +// InitMockStorage(mockDB) +// mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). +// WithArgs("project_1", "audit_plan_for_java_repo1"). +// WillReturnRows(sqlmock.NewRows([]string{"name"}).AddRow("audit_plan_1")) +// mock.ExpectClose() +// ap, exist, err := GetStorage().GetAuditPlanFromProjectByName("project_1", "audit_plan_for_java_repo1") +// assert.NoError(t, err) +// assert.True(t, exist) +// assert.Equal(t, "audit_plan_1", ap.Name) +// mockDB.Close() +// err = mock.ExpectationsWereMet() +// assert.NoError(t, err) + +// // 2. test record not exist +// mockDB, mock, err = sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) +// assert.NoError(t, err) +// InitMockStorage(mockDB) +// mock.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.name = ? AND audit_plans.name = ?))"). +// WithArgs("project_1", "audit_plan_for_java_repo1"). +// WillReturnRows(sqlmock.NewRows([]string{"name"})) +// mock.ExpectClose() +// _, exist, err = GetStorage().GetAuditPlanFromProjectByName("project_1", "audit_plan_for_java_repo1") +// assert.NoError(t, err) +// assert.False(t, exist) +// mockDB.Close() +// err = mock.ExpectationsWereMet() +// assert.NoError(t, err) +// } func TestStorage_GetAuditPlanSQLs(t *testing.T) { mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) diff --git a/sqle/model/cloud_beaver.go b/sqle/model/cloud_beaver.go index 4f09e53c63..4ad32d7dc4 100644 --- a/sqle/model/cloud_beaver.go +++ b/sqle/model/cloud_beaver.go @@ -1,68 +1,68 @@ package model -import ( - "fmt" +// import ( +// "fmt" - "github.com/actiontech/sqle/sqle/errors" +// "github.com/actiontech/sqle/sqle/errors" - "github.com/jinzhu/gorm" -) +// "github.com/jinzhu/gorm" +// ) -type CloudBeaverUserCache struct { - SQLEUserID uint `json:"sqle_user_id" gorm:"column:sqle_user_id;primary_key"` - CloudBeaverUserID string `json:"cloud_beaver_user_id" gorm:"column:cloud_beaver_user_id"` - SQLEFingerprint string `json:"sqle_fingerprint" gorm:"column:sqle_fingerprint"` -} +// type CloudBeaverUserCache struct { +// SQLEUserID uint `json:"sqle_user_id" gorm:"column:sqle_user_id;primary_key"` +// CloudBeaverUserID string `json:"cloud_beaver_user_id" gorm:"column:cloud_beaver_user_id"` +// SQLEFingerprint string `json:"sqle_fingerprint" gorm:"column:sqle_fingerprint"` +// } -func (s *Storage) GetCloudBeaverUserCacheByCBUserID(id string) (*CloudBeaverUserCache, bool, error) { - c := &CloudBeaverUserCache{} - err := s.db.Where("cloud_beaver_user_id = ?", id).Find(c).Error - if err == gorm.ErrRecordNotFound { - return c, false, nil - } +// func (s *Storage) GetCloudBeaverUserCacheByCBUserID(id string) (*CloudBeaverUserCache, bool, error) { +// c := &CloudBeaverUserCache{} +// err := s.db.Where("cloud_beaver_user_id = ?", id).Find(c).Error +// if err == gorm.ErrRecordNotFound { +// return c, false, nil +// } - return c, true, errors.New(errors.ConnectStorageError, err) -} +// return c, true, errors.New(errors.ConnectStorageError, err) +// } -func (s *Storage) UpdateCloudBeaverUserCache(sqleUserID uint, CloudBeaverUserID string) error { - user, exist, err := s.GetUserByID(sqleUserID) - if err != nil { - return err - } - if !exist { - return errors.New(errors.ConnectStorageError, fmt.Errorf("sqle user not exist")) - } +// func (s *Storage) UpdateCloudBeaverUserCache(sqleUserID uint, CloudBeaverUserID string) error { +// user, exist, err := s.GetUserByID(sqleUserID) +// if err != nil { +// return err +// } +// if !exist { +// return errors.New(errors.ConnectStorageError, fmt.Errorf("sqle user not exist")) +// } - err = s.db.Table("cloud_beaver_user_caches").Save(&CloudBeaverUserCache{ - SQLEUserID: sqleUserID, - CloudBeaverUserID: CloudBeaverUserID, - SQLEFingerprint: user.FingerPrint(), - }).Error - return errors.New(errors.ConnectStorageError, err) -} +// err = s.db.Table("cloud_beaver_user_caches").Save(&CloudBeaverUserCache{ +// SQLEUserID: sqleUserID, +// CloudBeaverUserID: CloudBeaverUserID, +// SQLEFingerprint: user.FingerPrint(), +// }).Error +// return errors.New(errors.ConnectStorageError, err) +// } -type CloudBeaverInstanceCache struct { - CloudBeaverInstanceID string `json:"cloud_beaver_instance_id"` - SQLEInstanceID uint `json:"sqle_instance_id" gorm:"primary_key"` - SQLEInstanceFingerprint string `json:"sqle_instance_fingerprint"` -} +// type CloudBeaverInstanceCache struct { +// CloudBeaverInstanceID string `json:"cloud_beaver_instance_id"` +// SQLEInstanceID uint `json:"sqle_instance_id" gorm:"primary_key"` +// SQLEInstanceFingerprint string `json:"sqle_instance_fingerprint"` +// } -func (s *Storage) GetCloudBeaverInstanceCacheBySQLEInstIDs(ids []uint) ([]*CloudBeaverInstanceCache, error) { - c := []*CloudBeaverInstanceCache{} - err := s.db.Where("sqle_instance_id in (?)", ids).Find(&c).Error - if err == gorm.ErrRecordNotFound { - return c, nil - } +// func (s *Storage) GetCloudBeaverInstanceCacheBySQLEInstIDs(ids []uint) ([]*CloudBeaverInstanceCache, error) { +// c := []*CloudBeaverInstanceCache{} +// err := s.db.Where("sqle_instance_id in (?)", ids).Find(&c).Error +// if err == gorm.ErrRecordNotFound { +// return c, nil +// } - return c, errors.New(errors.ConnectStorageError, err) -} +// return c, errors.New(errors.ConnectStorageError, err) +// } -func (s *Storage) GetCloudBeaverInstanceCacheByCBInstIDs(ids []string) ([]*CloudBeaverInstanceCache, error) { - c := []*CloudBeaverInstanceCache{} - err := s.db.Where("cloud_beaver_instance_id in (?)", ids).Find(&c).Error - if err == gorm.ErrRecordNotFound { - return c, nil - } +// func (s *Storage) GetCloudBeaverInstanceCacheByCBInstIDs(ids []string) ([]*CloudBeaverInstanceCache, error) { +// c := []*CloudBeaverInstanceCache{} +// err := s.db.Where("cloud_beaver_instance_id in (?)", ids).Find(&c).Error +// if err == gorm.ErrRecordNotFound { +// return c, nil +// } - return c, errors.New(errors.ConnectStorageError, err) -} +// return c, errors.New(errors.ConnectStorageError, err) +// } diff --git a/sqle/model/configuration.go b/sqle/model/configuration.go index 2cbf603efd..1551278de9 100644 --- a/sqle/model/configuration.go +++ b/sqle/model/configuration.go @@ -1,310 +1,18 @@ package model import ( - "database/sql" - e "errors" "fmt" "strconv" - "strings" + e "errors" + + dmsCommonAes "github.com/actiontech/dms/pkg/dms-common/pkg/aes" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" - "github.com/actiontech/sqle/sqle/notification/webhook" - "github.com/actiontech/sqle/sqle/utils" - "github.com/jinzhu/gorm" ) const globalConfigurationTablePrefix = "global_configuration" - -// SMTPConfiguration store SMTP server configuration. -type SMTPConfiguration struct { - Model - EnableSMTPNotify sql.NullBool `json:"enable_smtp_notify" gorm:"default:true"` - Host string `json:"smtp_host" gorm:"column:smtp_host; not null"` - Port string `json:"smtp_port" gorm:"column:smtp_port; not null"` - Username string `json:"smtp_username" gorm:"column:smtp_username; not null"` - Password string `json:"-" gorm:"-"` - SecretPassword string `json:"secret_smtp_password" gorm:"column:secret_smtp_password; not null"` - IsSkipVerify bool `json:"is_skip_verify" gorm:"default:false; not null"` -} - -func (i *SMTPConfiguration) TableName() string { - return fmt.Sprintf("%v_smtp", globalConfigurationTablePrefix) -} - -// BeforeSave is a hook implement gorm model before exec create. -func (i *SMTPConfiguration) BeforeSave() error { - return i.encryptPassword() -} - -func (i *SMTPConfiguration) encryptPassword() error { - if i == nil { - return nil - } - data, err := utils.AesEncrypt(i.Password) - if err != nil { - return err - } - i.SecretPassword = data - return nil -} - -// AfterFind is a hook implement gorm model after query, ignore err if query from db. -func (i *SMTPConfiguration) AfterFind() error { - err := i.decryptPassword() - if err != nil { - log.NewEntry().Errorf("decrypt password for SMTP server configuration failed, error: %v", err) - } - return nil -} - -func (i *SMTPConfiguration) decryptPassword() error { - if i == nil { - return nil - } - if i.Password == "" { - data, err := utils.AesDecrypt(i.SecretPassword) - if err != nil { - return err - } - i.Password = data - } - return nil -} - -func (s *Storage) GetSMTPConfiguration() (*SMTPConfiguration, bool, error) { - smtpC := new(SMTPConfiguration) - err := s.db.Last(smtpC).Error - if err == gorm.ErrRecordNotFound { - return smtpC, false, nil - } - return smtpC, true, errors.New(errors.ConnectStorageError, err) -} - -// WeChatConfiguration store WeChat configuration. -type WeChatConfiguration struct { - Model - EnableWeChatNotify bool `json:"enable_wechat_notify" gorm:"not null"` - CorpID string `json:"corp_id" gorm:"not null"` - CorpSecret string `json:"-" gorm:"-"` - EncryptedCorpSecret string `json:"encrypted_corp_secret" gorm:"not null"` - AgentID int `json:"agent_id" gorm:"not null"` - SafeEnabled bool `json:"safe_enabled" gorm:"not null"` - ProxyIP string `json:"proxy_ip"` -} - -func (i *WeChatConfiguration) TableName() string { - return fmt.Sprintf("%v_wechat", globalConfigurationTablePrefix) -} - -// BeforeSave is a hook implement gorm model before exec create. -func (i *WeChatConfiguration) BeforeSave() error { - return i.encryptPassword() -} - -func (i *WeChatConfiguration) encryptPassword() error { - if i == nil { - return nil - } - data, err := utils.AesEncrypt(i.CorpSecret) - if err != nil { - return err - } - i.EncryptedCorpSecret = data - return nil -} - -// AfterFind is a hook implement gorm model after query, ignore err if query from db. -func (i *WeChatConfiguration) AfterFind() error { - err := i.decryptPassword() - if err != nil { - log.NewEntry().Errorf("decrypt password for WeChat server configuration failed, error: %v", err) - } - return nil -} - -func (i *WeChatConfiguration) decryptPassword() error { - if i == nil { - return nil - } - if i.CorpSecret == "" { - data, err := utils.AesDecrypt(i.EncryptedCorpSecret) - if err != nil { - return err - } - i.CorpSecret = data - } - return nil -} - -func (s *Storage) GetWeChatConfiguration() (*WeChatConfiguration, bool, error) { - wechatC := new(WeChatConfiguration) - err := s.db.Last(wechatC).Error - if err == gorm.ErrRecordNotFound { - return wechatC, false, nil - } - return wechatC, true, errors.New(errors.ConnectStorageError, err) -} - -// LDAPConfiguration store ldap server configuration. -type LDAPConfiguration struct { - Model - // whether the ldap is enabled - Enable bool `json:"enable" gorm:"not null"` - // whether the ssl is enabled - EnableSSL bool `json:"enable_ssl" gorm:"not null"` - // ldap server's ip - Host string `json:"host" gorm:"not null"` - // ldap server's port - Port string `json:"port" gorm:"not null"` - // the DN of the ldap administrative user for verification - ConnectDn string `json:"connect_dn" gorm:"not null"` - // the password of the ldap administrative user for verification - ConnectPassword string `json:"-" gorm:"-"` - // the secret password of the ldap administrative user for verification - ConnectSecretPassword string `json:"connect_secret_password" gorm:"not null"` - // base dn used for ldap verification - BaseDn string `json:"base_dn" gorm:"not null"` - // the key corresponding to the user name in ldap - UserNameRdnKey string `json:"ldap_user_name_rdn_key" gorm:"not null"` - // the key corresponding to the user email in ldap - UserEmailRdnKey string `json:"ldap_user_email_rdn_key" gorm:"not null"` -} - -func (i *LDAPConfiguration) TableName() string { - return fmt.Sprintf("%v_ldap", globalConfigurationTablePrefix) -} - -// BeforeSave is a hook implement gorm model before exec create -func (i *LDAPConfiguration) BeforeSave() error { - return i.encryptPassword() -} - -// AfterFind is a hook implement gorm model after query, ignore err if query from db -func (i *LDAPConfiguration) AfterFind() error { - err := i.decryptPassword() - if err != nil { - log.NewEntry().Errorf("decrypt password for ldap administrative user failed, error: %v", err) - } - return nil -} - -func (i *LDAPConfiguration) decryptPassword() error { - if i == nil { - return nil - } - if i.ConnectPassword == "" { - data, err := utils.AesDecrypt(i.ConnectSecretPassword) - if err != nil { - return err - } else { - i.ConnectPassword = data - } - } - return nil -} - -func (i *LDAPConfiguration) encryptPassword() error { - if i == nil { - return nil - } - data, err := utils.AesEncrypt(i.ConnectPassword) - if err != nil { - return err - } - i.ConnectSecretPassword = data - return nil -} - -func (s *Storage) GetLDAPConfiguration() (*LDAPConfiguration, bool, error) { - ldapC := new(LDAPConfiguration) - err := s.db.Last(ldapC).Error - if err == gorm.ErrRecordNotFound { - return ldapC, false, nil - } - return ldapC, true, errors.New(errors.ConnectStorageError, err) -} - -// Oauth2Configuration store ldap server configuration. -type Oauth2Configuration struct { - Model - EnableOauth2 bool `json:"enable_oauth2" gorm:"column:enable_oauth2"` - ClientID string `json:"client_id" gorm:"column:client_id"` - ClientKey string `json:"-" gorm:"-"` - ClientSecret string `json:"client_secret" gorm:"client_secret"` - ClientHost string `json:"client_host" gorm:"column:client_host"` - ServerAuthUrl string `json:"server_auth_url" gorm:"column:server_auth_url"` - ServerTokenUrl string `json:"server_token_url" gorm:"column:server_token_url"` - ServerUserIdUrl string `json:"server_user_id_url" gorm:"column:server_user_id_url"` - Scopes string `json:"scopes" gorm:"column:scopes"` - AccessTokenTag string `json:"access_token_tag" gorm:"column:access_token_tag"` - UserIdTag string `json:"user_id_tag" gorm:"column:user_id_tag"` - LoginTip string `json:"login_tip" gorm:"column:login_tip; default:'使用第三方账户登录'"` -} - -func (i *Oauth2Configuration) GetScopes() []string { - return strings.Split(i.Scopes, ",") -} - -func (i *Oauth2Configuration) SetScopes(s []string) { - i.Scopes = strings.Join(s, ",") -} - -func (i *Oauth2Configuration) TableName() string { - return fmt.Sprintf("%v_oauth2", globalConfigurationTablePrefix) -} - -// BeforeSave is a hook implement gorm model before exec create -func (i *Oauth2Configuration) BeforeSave() error { - return i.encryptPassword() -} - -// AfterFind is a hook implement gorm model after query, ignore err if query from db -func (i *Oauth2Configuration) AfterFind() error { - err := i.decryptPassword() - if err != nil { - log.NewEntry().Errorf("decrypt password for ldap administrative user failed, error: %v", err) - } - return nil -} - -func (i *Oauth2Configuration) decryptPassword() error { - if i == nil { - return nil - } - if i.ClientKey == "" { - data, err := utils.AesDecrypt(i.ClientSecret) - if err != nil { - return err - } else { - i.ClientKey = data - } - } - return nil -} - -func (i *Oauth2Configuration) encryptPassword() error { - if i == nil { - return nil - } - data, err := utils.AesEncrypt(i.ClientKey) - if err != nil { - return err - } - i.ClientSecret = data - return nil -} - -func (s *Storage) GetOauth2Configuration() (*Oauth2Configuration, bool, error) { - oauth2C := new(Oauth2Configuration) - err := s.db.Last(oauth2C).Error - if err == gorm.ErrRecordNotFound { - return oauth2C, false, nil - } - return oauth2C, true, errors.New(errors.ConnectStorageError, err) -} - const ( SystemVariableWorkflowExpiredHours = "system_variable_workflow_expired_hours" SystemVariableSqleUrl = "system_variable_sqle_url" @@ -418,7 +126,7 @@ func (i *IM) encryptAppSecret() error { if i == nil { return nil } - data, err := utils.AesEncrypt(i.AppSecret) + data, err := dmsCommonAes.AesEncrypt(i.AppSecret) if err != nil { return err } @@ -440,7 +148,7 @@ func (i *IM) decryptAppSecret() error { return nil } if i.AppSecret == "" { - data, err := utils.AesDecrypt(i.EncryptAppSecret) + data, err := dmsCommonAes.AesDecrypt(i.EncryptAppSecret) if err != nil { return err } @@ -485,13 +193,13 @@ const ( type DingTalkInstance struct { Model ApproveInstanceCode string `json:"approve_instance" gorm:"column:approve_instance"` - WorkflowId uint `json:"workflow_id" gorm:"column:workflow_id"` + WorkflowId string `json:"workflow_id" gorm:"column:workflow_id"` // 审批实例 taskID TaskID int64 `json:"task_id" gorm:"column:task_id"` Status string `json:"status" gorm:"default:\"initialized\""` } -func (s *Storage) GetDingTalkInstanceByWorkflowID(workflowId uint) (*DingTalkInstance, bool, error) { +func (s *Storage) GetDingTalkInstanceByWorkflowID(workflowId string) (*DingTalkInstance, bool, error) { dti := new(DingTalkInstance) err := s.db.Where("workflow_id = ?", workflowId).Last(&dti).Error if err == gorm.ErrRecordNotFound { @@ -500,7 +208,7 @@ func (s *Storage) GetDingTalkInstanceByWorkflowID(workflowId uint) (*DingTalkIns return dti, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetDingTalkInstanceListByWorkflowIDs(workflowIds []uint) ([]DingTalkInstance, error) { +func (s *Storage) GetDingTalkInstanceListByWorkflowIDs(workflowIds []string) ([]DingTalkInstance, error) { var dingTalkInstances []DingTalkInstance err := s.db.Model(&DingTalkInstance{}).Where("workflow_id IN (?)", workflowIds).Find(&dingTalkInstances).Error if err != nil { @@ -510,7 +218,7 @@ func (s *Storage) GetDingTalkInstanceListByWorkflowIDs(workflowIds []uint) ([]Di } // batch updates ding_talk_instances'status into input status by workflow_ids, the status should be like ApproveStatusXXX in model package. -func (s *Storage) BatchUpdateStatusOfDingTalkInstance(workflowIds []uint, status string) error { +func (s *Storage) BatchUpdateStatusOfDingTalkInstance(workflowIds []string, status string) error { err := s.db.Model(&DingTalkInstance{}).Where("workflow_id IN (?)", workflowIds).Updates(map[string]interface{}{"status": status}).Error if err != nil { return err @@ -536,13 +244,13 @@ const ( type FeishuInstance struct { Model ApproveInstanceCode string `json:"approve_instance" gorm:"column:approve_instance"` - WorkflowId uint `json:"workflow_id" gorm:"column:workflow_id"` + WorkflowId string `json:"workflow_id" gorm:"column:workflow_id"` // 审批实例 taskID TaskID string `json:"task_id" gorm:"column:task_id"` Status string `json:"status" gorm:"default:\"INITIALIZED\""` } -func (s *Storage) GetFeishuInstanceListByWorkflowIDs(workflowIds []uint) ([]FeishuInstance, error) { +func (s *Storage) GetFeishuInstanceListByWorkflowIDs(workflowIds []string) ([]FeishuInstance, error) { var feishuInstList []FeishuInstance err := s.db.Model(&FeishuInstance{}).Where("workflow_id IN (?)", workflowIds).Find(&feishuInstList).Error if err != nil { @@ -551,7 +259,7 @@ func (s *Storage) GetFeishuInstanceListByWorkflowIDs(workflowIds []uint) ([]Feis return feishuInstList, nil } -func (s *Storage) BatchUpdateStatusOfFeishuInstance(workflowIds []uint, status string) error { +func (s *Storage) BatchUpdateStatusOfFeishuInstance(workflowIds []string, status string) error { err := s.db.Model(&FeishuInstance{}).Where("workflow_id IN (?)", workflowIds).Updates(map[string]interface{}{"status": status}).Error if err != nil { return err @@ -559,7 +267,7 @@ func (s *Storage) BatchUpdateStatusOfFeishuInstance(workflowIds []uint, status s return nil } -func (s *Storage) GetFeishuInstanceByWorkflowID(workflowId uint) (*FeishuInstance, bool, error) { +func (s *Storage) GetFeishuInstanceByWorkflowID(workflowId string) (*FeishuInstance, bool, error) { fi := new(FeishuInstance) err := s.db.Where("workflow_id = ?", workflowId).Last(&fi).Error if e.Is(err, gorm.ErrRecordNotFound) { @@ -576,91 +284,3 @@ func (s *Storage) GetFeishuInstByStatus(status string) ([]FeishuInstance, error) } return feishuInst, nil } - -type PersonaliseConfig struct { - Model - Title string `json:"title" gorm:"column:title"` -} - -func (i *PersonaliseConfig) TableName() string { - return fmt.Sprintf("%v_personalise", globalConfigurationTablePrefix) -} - -type LogoConfig struct { - Model - Logo []byte `json:"logo" gorm:"type:mediumblob"` -} - -func (i *LogoConfig) TableName() string { - return fmt.Sprintf("%v_logo", globalConfigurationTablePrefix) -} - -type WebHookConfig struct { - Model - Enable bool `json:"enable" gorm:"default:true;not null"` - MaxRetryTimes int `json:"max_retry_times" gorm:"not null"` - RetryIntervalSeconds int `json:"retry_interval_seconds" gorm:"not null"` - Token string `json:"-" gorm:"-"` - EncryptedToken string `json:"encrypted_token" gorm:"not null"` - URL string `json:"url" gorm:"not null"` -} - -func (i *WebHookConfig) TableName() string { - return fmt.Sprintf("%v_webhook", globalConfigurationTablePrefix) -} - -func (i *WebHookConfig) BeforeSave() error { - return i.encryptPassword() -} - -func (i *WebHookConfig) AfterSave() error { - webhook.UpdateWorkflowConfig(i.Enable, i.MaxRetryTimes, - i.RetryIntervalSeconds, i.URL, i.Token) - return nil -} - -func (i *WebHookConfig) AfterFind() error { - err := i.decryptPassword() - if err != nil { - log.NewEntry().Errorf("decrypt app secret for web configuration failed, error: %v", err) - } - return nil -} - -func (i *WebHookConfig) encryptPassword() error { - if i == nil { - return nil - } - if i.Token == "" { - i.EncryptedToken = "" - return nil - } - data, err := utils.AesEncrypt(i.Token) - if err != nil { - return err - } - i.EncryptedToken = data - return nil -} - -func (i *WebHookConfig) decryptPassword() error { - if i == nil || len(i.EncryptedToken) == 0 { - return nil - } - data, err := utils.AesDecrypt(i.EncryptedToken) - if err != nil { - return err - } - i.Token = data - return nil -} - -func (s *Storage) GetWorkflowWebHookConfig() (*WebHookConfig, bool, error) { - cfg := &WebHookConfig{} - err := s.db.Last(&cfg).Error - - if err == gorm.ErrRecordNotFound { - return cfg, false, nil - } - return cfg, true, errors.ConnectStorageErrWrapper(err) -} diff --git a/sqle/model/instance.go b/sqle/model/instance.go index 91c79cc09f..06edf54d90 100644 --- a/sqle/model/instance.go +++ b/sqle/model/instance.go @@ -2,14 +2,11 @@ package model import ( "fmt" - "strings" + dmsCommonAes "github.com/actiontech/dms/pkg/dms-common/pkg/aes" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/pkg/params" - "github.com/actiontech/sqle/sqle/utils" - - "github.com/jinzhu/gorm" ) const InstanceSourceSQLE string = "SQLE" @@ -18,8 +15,10 @@ const InstanceSourceSQLE string = "SQLE" // NOTE: related model: // - ProjectMemberRole, ProjectMemberGroupRole type Instance struct { - Model - ProjectId uint `gorm:"index; not null"` + ID uint64 `json:"id"` + RuleTemplateId uint64 `json:"rule_template_id"` + RuleTemplateName string `json:"rule_template_name"` + ProjectId string `gorm:"index; not null"` // has created composite index: [id, name] by gorm#AddIndex Name string `json:"name" gorm:"not null;index" example:""` DbType string `json:"db_type" gorm:"column:db_type; not null" example:"mysql"` @@ -41,6 +40,10 @@ type Instance struct { WorkflowTemplate *WorkflowTemplate `gorm:"foreignkey:WorkflowTemplateId"` } +func (i *Instance) GetIDStr() string { + return fmt.Sprintf("%d", i.ID) +} + // BeforeSave is a hook implement gorm model before exec create func (i *Instance) BeforeSave() error { return i.encryptPassword() @@ -60,7 +63,7 @@ func (i *Instance) decryptPassword() error { return nil } if i.Password == "" { - data, err := utils.AesDecrypt(i.SecretPassword) + data, err := dmsCommonAes.AesDecrypt(i.SecretPassword) if err != nil { return err } else { @@ -75,7 +78,7 @@ func (i *Instance) encryptPassword() error { return nil } if i.SecretPassword == "" { - data, err := utils.AesEncrypt(i.Password) + data, err := dmsCommonAes.AesEncrypt(i.Password) if err != nil { return err } @@ -91,218 +94,93 @@ func (i *Instance) Fingerprint() string { "host":"%v", "port":"%v", "user":"%v", - "secret_password":"%v", + "password":"%v", "additional_params":"%v" } -`, i.ID, i.Host, i.Port, i.User, i.SecretPassword, i.AdditionalParams) -} - -func (s *Storage) GetInstanceById(id string) (*Instance, bool, error) { - instance := &Instance{} - err := s.db.Preload("RuleTemplates").Where("id = ?", id).First(instance).Error - if err == gorm.ErrRecordNotFound { - return instance, false, nil - } - return instance, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetInstancesFromActiveProjectByIds(ids []uint) ([]*Instance, error) { - instances := []*Instance{} - err := s.db.Joins("LEFT JOIN projects ON projects.id = instances.project_id"). - Where("instances.id IN (?)", ids). - Where("projects.status = ?", ProjectStatusActive). - Find(&instances).Error - return instances, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetInstancesByIds(ids []uint) (instances []*Instance, err error) { - distinctIds := utils.RemoveDuplicateUint(ids) - return instances, s.db.Model(&Instance{}).Where("id in (?)", distinctIds).Scan(&instances).Error -} - -func (s *Storage) GetAllInstance() ([]*Instance, error) { - i := []*Instance{} - err := s.db.Preload("RuleTemplates").Find(&i).Error - return i, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetInstanceByNameAndProjectName(instName, projectName string) (*Instance, bool, error) { - instance := &Instance{} - err := s.db.Joins("JOIN projects on projects.id = instances.project_id").Where("projects.name = ?", projectName).Where("instances.name = ?", instName).First(instance).Error - if err == gorm.ErrRecordNotFound { - return instance, false, nil - } - return instance, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetInstanceByNameAndProjectID(instName string, projectID uint) (*Instance, bool, error) { - instance := &Instance{} - err := s.db.Where("instances.project_id = ?", projectID).Where("instances.name = ?", instName).First(instance).Error - if err == gorm.ErrRecordNotFound { - return instance, false, nil - } - return instance, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetInstancesBySyncTaskId(projectID, syncTaskID uint) ([]*Instance, error) { - instances := []*Instance{} - if err := s.db.Where("project_id = ? and sync_instance_task_id = ?", projectID, syncTaskID).Find(&instances).Error; err != nil { - return nil, errors.ConnectStorageErrWrapper(err) - } - return instances, nil -} - -func (s *Storage) DeleteInstance(instance *Instance) error { - err := s.DeleteRoleByInstanceID(instance.ID) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - err = s.Delete(instance) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - return nil -} - -func (s *Storage) GetInstanceDetailByNameAndProjectName(instName string, projectName string) (*Instance, bool, error) { - instance := &Instance{} - err := s.db.Preload("WorkflowTemplate").Preload("RuleTemplates"). - Joins("JOIN projects on projects.id = instances.project_id"). - Where("instances.name = ?", instName).Where("projects.name = ?", projectName).First(instance).Error - if err == gorm.ErrRecordNotFound { - return instance, false, nil - } - return instance, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetInstancesByType(dbType string) ([]*Instance, error) { - instances := []*Instance{} - err := s.db.Where("db_type = ?", dbType).Find(&instances).Error - return instances, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetInstancesByNamesAndProjectName(instNames []string, projectName string) ([]*Instance, error) { - instances := []*Instance{} - err := s.db.Joins("JOIN projects on projects.id = instances.project_id"). - Where("projects.name = ?", projectName). - Where("instances.name in (?)", instNames). - Find(&instances).Error - return instances, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) UpdateInstanceById(InstanceId uint, attrs ...interface{}) error { - err := s.db.Table("instances").Where("id = ?", InstanceId).Update(attrs...).Error - return errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) UpdateInstanceRuleTemplates(instance *Instance, ts ...*RuleTemplate) error { - err := s.db.Model(instance).Association("RuleTemplates").Replace(ts).Error - return errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) UpdateInstanceRoles(instance *Instance, rs ...*Role) error { - err := s.db.Model(instance).Association("Roles").Replace(rs).Error - return errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetAndCheckInstanceExist(instanceNames []string, projectName string) (instances []*Instance, err error) { - instances, err = s.GetInstancesByNamesAndProjectName(instanceNames, projectName) - if err != nil { - return instances, err - } - existInstanceNames := map[string]struct{}{} - for _, instance := range instances { - existInstanceNames[instance.Name] = struct{}{} - } - notExistInstanceNames := []string{} - for _, instanceName := range instanceNames { - if _, ok := existInstanceNames[instanceName]; !ok { - notExistInstanceNames = append(notExistInstanceNames, instanceName) - } - } - if len(notExistInstanceNames) > 0 { - return instances, errors.New(errors.DataNotExist, - fmt.Errorf("instance %s not exist", strings.Join(notExistInstanceNames, ", "))) - } - return instances, nil -} - -func (s *Storage) GetInstanceNamesByWorkflowTemplateId(id uint) ([]string, error) { - var instances []*Instance - err := s.db.Select("name").Where("workflow_template_id = ?", id).Find(&instances).Error - if err != nil { - return []string{}, errors.New(errors.ConnectStorageError, err) - } - names := make([]string, 0, len(instances)) - for _, instance := range instances { - names = append(names, instance.Name) - } - return names, nil -} - -func getDeduplicatedInstanceIds(instances []*Instance) []uint { - instanceIds := make([]uint, len(instances)) - for i, inst := range instances { - instanceIds[i] = inst.ID - } - instanceIds = utils.RemoveDuplicateUint(instanceIds) - return instanceIds -} - -func (s *Storage) GetInstanceTipsByTypeAndTempID(dbType string, tempID uint32, projectName string) (instances []*Instance, err error) { - query := s.db.Model(&Instance{}).Select("instances.name, instances.db_type, instances.db_host, instances.db_port, instances.workflow_template_id").Group("instances.id") - - if dbType != "" { - query = query.Where("db_type = ?", dbType) - } - - if tempID != 0 { - query = query.Where("workflow_template_id = ?", tempID) - } - - if projectName != "" { - query = query.Joins("LEFT JOIN projects ON projects.id = instances.project_id").Where("projects.name = ?", projectName) - } - - return instances, query.Scan(&instances).Error -} - -func (s *Storage) GetAllInstanceCountByType(dbTypes ...string) (int64, error) { - var count int64 - return count, s.db.Model(&Instance{}).Where("db_type in (?)", dbTypes).Count(&count).Error -} +`, i.ID, i.Host, i.Port, i.User, i.Password, i.AdditionalParams) +} + +// func (s *Storage) GetInstancesFromActiveProjectByIds(ids []uint) ([]*Instance, error) { +// instances := []*Instance{} +// err := s.db.Joins("LEFT JOIN projects ON projects.id = instances.project_id"). +// Where("instances.id IN (?)", ids). +// Where("projects.status = ?", ProjectStatusActive). +// Find(&instances).Error +// return instances, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetAllInstance() ([]*Instance, error) { +// i := []*Instance{} +// err := s.db.Preload("RuleTemplates").Find(&i).Error +// return i, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetInstanceByNameAndProjectName(instName, projectName string) (*Instance, bool, error) { +// instance := &Instance{} +// err := s.db.Joins("JOIN projects on projects.id = instances.project_id").Where("projects.name = ?", projectName).Where("instances.name = ?", instName).First(instance).Error +// if err == gorm.ErrRecordNotFound { +// return instance, false, nil +// } +// return instance, true, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetInstances(instIds []string) ([]*Instance, bool, error) { +// instances := []*Instance{} +// err := s.db.Where("instances.id in (?)", instIds).Find(&instances).Error +// if err == gorm.ErrRecordNotFound { +// return instances, false, nil +// } +// return instances, true, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) DeleteInstance(instance *Instance) error { +// err := s.DeleteRoleByInstanceID(instance.ID) +// if err != nil { +// return errors.ConnectStorageErrWrapper(err) +// } +// err = s.Delete(instance) +// if err != nil { +// return errors.ConnectStorageErrWrapper(err) +// } +// return nil +// } + +// func (s *Storage) UpdateInstanceById(InstanceId uint, attrs ...interface{}) error { +// err := s.db.Table("instances").Where("id = ?", InstanceId).Update(attrs...).Error +// return errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) UpdateInstanceRoles(instance *Instance, rs ...*Role) error { +// err := s.db.Model(instance).Association("Roles").Replace(rs).Error +// return errors.New(errors.ConnectStorageError, err) +// } type TypeCount struct { DBType string `json:"db_type"` Count int64 `json:"count"` } -func (s *Storage) GetAllInstanceCount() ([]*TypeCount, error) { - var counts []*TypeCount - return counts, s.db.Table("instances").Select("db_type, count(*) as count").Where("deleted_at is NULL").Group("db_type").Find(&counts).Error -} - -func (s *Storage) GetInstanceTipsByUser(user *User, dbType string, projectName string) ( - instances []*Instance, err error) { +// func (s *Storage) GetInstanceTipsByUser(user *User, dbType string, projectName string) ( +// instances []*Instance, err error) { - isMember, err := s.IsProjectMember(user.Name, projectName) - if err != nil { - return nil, err - } - if IsDefaultAdminUser(user.Name) || isMember { - return s.GetInstanceTipsByTypeAndTempID(dbType, 0, projectName) - } +// isMember, err := s.IsProjectMember(user.Name, projectName) +// if err != nil { +// return nil, err +// } +// if IsDefaultAdminUser(user.Name) || isMember { +// return s.GetInstanceTipsByTypeAndTempID(dbType, 0, projectName) +// } - return []*Instance{}, nil -} +// return []*Instance{}, nil +// } -func getInstanceIDsFromInstances(instances []*Instance) (ids []uint) { +/*func GetInstanceIDsFromInstances(instances []*Instance) (ids []uint) { ids = make([]uint, len(instances)) for i := range instances { ids[i] = instances[i].ID } return ids -} +}*/ //SELECT instances.id //FROM instances @@ -362,135 +240,118 @@ func getInstanceIDsFromInstances(instances []*Instance) (ids []uint) { //AND role_operations.op_code IN (20200) //GROUP BY instances.id -func (s *Storage) CheckInstancesExist(projectName string, instNames []string) (bool, error) { - instNames = utils.RemoveDuplicate(instNames) - - var count int - err := s.db.Model(&Instance{}). - Joins("JOIN projects ON projects.id = instances.project_id"). - Where("projects.name = ?", projectName). - Where("instances.name in (?)", instNames). - Count(&count).Error - return len(instNames) == count, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) getInstanceBindCacheByNames(instNames []string, projectName string) (map[string] /*inst name*/ uint /*inst id*/, error) { - instNames = utils.RemoveDuplicate(instNames) - - insts, err := s.GetInstancesByNamesAndProjectName(instNames, projectName) - if err != nil { - return nil, err - } - - if len(insts) != len(instNames) { - return nil, errors.NewDataNotExistErr("some instances don't exist") - } - - instCache := map[string] /*inst name*/ uint /*inst id*/ {} - - for _, inst := range insts { - instCache[inst.Name] = inst.ID - } - - return instCache, nil -} - -type SyncTaskInstance struct { - Instances []*Instance - RuleTemplate *RuleTemplate - NeedDeletedInstances []*Instance -} - -func (s *Storage) BatchUpdateSyncTask(instTemplate *SyncTaskInstance) error { - err := s.Tx(func(tx *gorm.DB) error { - for _, instance := range instTemplate.Instances { - if err := tx.Save(instance).Error; err != nil { - return err - } - - if err := s.UpdateInstanceRuleTemplates(instance, instTemplate.RuleTemplate); err != nil { - return err - } - } - - for _, instance := range instTemplate.NeedDeletedInstances { - if err := s.DeleteInstance(instance); err != nil { - return err - } - } - - return nil - }) - - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - - return nil -} - -func (s *Storage) GetInstancesNamesByRuleTemplateAndProject( - ruleTemplateName string, projectID uint) (instanceNames []string, err error) { - - var instances []*Instance - - err = s.db.Model(&Instance{}). - Select("instances.name"). - Joins("LEFT JOIN instance_rule_template AS irt ON irt.instance_id=instances.id"). - Joins("LEFT JOIN rule_templates ON rule_templates.id=irt.rule_template_id"). - Where("instances.project_id=?", projectID). - Where("rule_templates.name=?", ruleTemplateName).Find(&instances).Error +// type SyncTaskInstance struct { +// Instances []*Instance +// RuleTemplate *RuleTemplate +// NeedDeletedInstances []*Instance +// } + +// func (s *Storage) BatchUpdateSyncTask(instTemplate *SyncTaskInstance) error { +// err := s.Tx(func(tx *gorm.DB) error { +// for _, instance := range instTemplate.Instances { +// if err := tx.Save(instance).Error; err != nil { +// return err +// } + +// if err := s.UpdateInstanceRuleTemplates(instance, instTemplate.RuleTemplate); err != nil { +// return err +// } +// } + +// for _, instance := range instTemplate.NeedDeletedInstances { +// if err := s.DeleteInstance(instance); err != nil { +// return err +// } +// } + +// return nil +// }) + +// if err != nil { +// return errors.ConnectStorageErrWrapper(err) +// } + +// return nil +// } + +// GetSqlExecutionFailCount 获取sql上线失败统计 +func (s *Storage) GetSqlExecutionFailCount() ([]SqlExecutionCount, error) { + var sqlExecutionFailCount []SqlExecutionCount + + err := s.db.Model(&Workflow{}).Select("t.instance_id, count(*) as count"). + Joins("left join workflow_records wr on workflows.workflow_record_id = wr.id"). + Joins("left join workflow_instance_records wir on wr.id = wir.workflow_record_id"). + Joins("left join tasks t on wir.task_id = t.id"). + Where("t.status = ?", TaskStatusExecuteFailed). + Where("t.exec_start_at is not null"). + Where("t.exec_end_at is not null"). + Group("t.instance_id"). + Scan(&sqlExecutionFailCount).Error if err != nil { return nil, errors.ConnectStorageErrWrapper(err) } - instanceNames = make([]string, len(instances)) - for i := range instances { - instanceNames[i] = instances[i].Name - } - - return instanceNames, nil + return sqlExecutionFailCount, nil } -func (s *Storage) GetInstancesNamesByRuleTemplate( - ruleTemplateName string) (instanceNames []string, err error) { +// GetSqlExecutionTotalCount 获取sql上线总数统计 +// 上线总数(根据数据源划分)是指:正在上线,上线成功,上线失败 task的总数 +func (s *Storage) GetSqlExecutionTotalCount() ([]SqlExecutionCount, error) { + var sqlExecutionTotalCount []SqlExecutionCount - var instances []*Instance - - err = s.db.Model(&Instance{}). - Select("instances.name"). - Joins("LEFT JOIN instance_rule_template AS irt ON irt.instance_id=instances.id"). - Joins("LEFT JOIN rule_templates ON rule_templates.id=irt.rule_template_id"). - Where("rule_templates.name=?", ruleTemplateName).Find(&instances).Error + err := s.db.Model(&Workflow{}).Select("t.instance_id, count(*) as count"). + Joins("left join workflow_records wr on workflows.workflow_record_id = wr.id"). + Joins("left join workflow_instance_records wir on wr.id = wir.workflow_record_id"). + Joins("left join tasks t on wir.task_id = t.id"). + Where("t.status not in (?)", []string{TaskStatusInit, TaskStatusAudited}). + Where("t.exec_start_at is not null"). + Group("t.instance_id"). + Scan(&sqlExecutionTotalCount).Error if err != nil { return nil, errors.ConnectStorageErrWrapper(err) } - instanceNames = make([]string, len(instances)) - for i := range instances { - instanceNames[i] = instances[i].Name - } - - return instanceNames, nil + return sqlExecutionTotalCount, nil } type InstanceWorkFlowStatusCount struct { DbType string `json:"db_type"` InstanceName string `json:"instance_name"` StatusCount uint `json:"status_count"` + InstanceId uint64 `json:"instance_id"` } -func (s *Storage) GetInstanceWorkFlowStatusCountByProject(projectName string, queryStatus []string) ([]*InstanceWorkFlowStatusCount, error) { +func (s *Storage) GetInstanceWorkFlowStatusCountByProject(instances []*Instance, queryStatus []string) ([]*InstanceWorkFlowStatusCount, error) { var instanceWorkFlowStatusCount []*InstanceWorkFlowStatusCount - err := s.db.Model(&Instance{}). - Select("instances.db_type, instances.name instance_name, count(case when workflow_records.status in (?) then 1 else null end) status_count", queryStatus). - Joins("left join workflow_instance_records on instances.id=workflow_instance_records.instance_id"). - Joins("left join workflow_records on workflow_instance_records.workflow_record_id=workflow_records.id"). - Joins("inner join workflows on workflow_records.id=workflows.workflow_record_id"). - Joins("left join projects on instances.project_id=projects.id"). - Where("projects.name=?", projectName). - Group("instances.db_type, instances.name"). + instanceIds := make([]uint64, 0) + var instanceMap = make(map[uint64]InstanceWorkFlowStatusCount) + for _, instance := range instances { + instanceMap[instance.ID] = InstanceWorkFlowStatusCount{ + DbType: instance.DbType, + InstanceName: instance.Name, + } + instanceIds = append(instanceIds, instance.ID) + } + + err := s.db.Model(&WorkflowInstanceRecord{}). + Select("workflow_instance_records.instance_id, count(case when workflow_records.status in (?) then 1 else null end) status_count", queryStatus). + Joins("join workflow_records on workflow_instance_records.workflow_record_id=workflow_records.id"). + Joins("join workflows on workflow_records.id=workflows.workflow_record_id"). + Where("workflow_instance_records.instance_id in (?)", instanceIds). + Group("workflow_instance_records.instance_id"). Scan(&instanceWorkFlowStatusCount).Error - return instanceWorkFlowStatusCount, errors.ConnectStorageErrWrapper(err) + + if err != nil { + return nil, errors.ConnectStorageErrWrapper(err) + } + + for i, item := range instanceWorkFlowStatusCount { + if instance, ok := instanceMap[item.InstanceId]; ok { + instanceWorkFlowStatusCount[i].DbType = instance.DbType + instanceWorkFlowStatusCount[i].InstanceName = instance.InstanceName + } + } + + return instanceWorkFlowStatusCount, nil } diff --git a/sqle/model/instance_list.go b/sqle/model/instance_list.go index baad60c727..fce6746c2f 100644 --- a/sqle/model/instance_list.go +++ b/sqle/model/instance_list.go @@ -1,104 +1,104 @@ package model -import ( - "fmt" - - "github.com/actiontech/sqle/sqle/errors" -) - -type InstanceDetail struct { - Name string `json:"name"` - DbType string `json:"db_type"` - Desc string `json:"desc"` - Host string `json:"db_host"` - Port string `json:"db_port"` - User string `json:"db_user"` - MaintenancePeriod Periods `json:"maintenance_period" gorm:"text"` - RuleTemplateNames RowList `json:"rule_template_names"` - SqlQueryConfig SqlQueryConfig `json:"sql_query_config"` - Source string `json:"source"` -} - -var instancesQueryTpl = `SELECT inst.name, inst.db_type, inst.desc, inst.db_host, -inst.db_port, inst.db_user, inst.maintenance_period, inst.sql_query_config, inst.source, -GROUP_CONCAT(DISTINCT COALESCE(rt.name,'')) AS rule_template_names -FROM instances AS inst -LEFT JOIN instance_rule_template AS inst_rt ON inst.id = inst_rt.instance_id -LEFT JOIN rule_templates AS rt ON inst_rt.rule_template_id = rt.id AND rt.deleted_at IS NULL -WHERE -inst.id in (SELECT DISTINCT(inst.id) - -{{- template "body" . -}} -) -GROUP BY inst.id -{{- if .limit }} -LIMIT :limit OFFSET :offset -{{- end -}} -` - -var instancesCountTpl = `SELECT COUNT(DISTINCT inst.id) - -{{- template "body" . -}} -` - -var instancesQueryBodyTpl = ` -{{ define "body" }} -FROM instances AS inst -LEFT JOIN instance_rule_template AS inst_rt ON inst.id = inst_rt.instance_id -LEFT JOIN rule_templates AS rt ON inst_rt.rule_template_id = rt.id AND rt.deleted_at IS NULL -LEFT JOIN projects AS p ON inst.project_id = p.id - -WHERE inst.deleted_at IS NULL - -AND p.name = :filter_project_name - -{{- if .filter_instance_name }} -AND inst.name = :filter_instance_name -{{- end }} - -{{- if .filter_db_host }} -AND inst.db_host = :filter_db_host -{{- end }} - -{{- if .filter_db_port }} -AND inst.db_port = :filter_db_port -{{- end }} - -{{- if .filter_db_user }} -AND inst.db_user = :filter_db_user -{{- end }} - -{{- if .filter_db_type }} -AND inst.db_type = :filter_db_type -{{- end }} - -{{- if .filter_rule_template_name }} -AND rt.name = :filter_rule_template_name -{{- end }} - -{{- end }} -` - -func (s *Storage) GetInstancesByReq(data map[string]interface{}, user *User) ( - result []*InstanceDetail, count uint64, err error) { - - if data["filter_project_name"] == "" { - return nil, 0, errors.New(errors.DataInvalid, fmt.Errorf("project name can not be empty")) - } - - err = s.getListResult(instancesQueryBodyTpl, instancesQueryTpl, data, &result) - if err != nil { - return result, 0, err - } - - count, err = s.getCountResult(instancesQueryBodyTpl, instancesCountTpl, data) - return result, count, err - -} - -func (s *Storage) GetInstanceTotalByProjectName(projectName string) (uint64, error) { - data := map[string]interface{}{ - "filter_project_name": projectName, - } - return s.getCountResult(instancesQueryBodyTpl, instancesCountTpl, data) -} +// import ( +// "fmt" + +// "github.com/actiontech/sqle/sqle/errors" +// ) + +// type InstanceDetail struct { +// Name string `json:"name"` +// DbType string `json:"db_type"` +// Desc string `json:"desc"` +// Host string `json:"db_host"` +// Port string `json:"db_port"` +// User string `json:"db_user"` +// MaintenancePeriod Periods `json:"maintenance_period" gorm:"text"` +// RuleTemplateNames RowList `json:"rule_template_names"` +// SqlQueryConfig SqlQueryConfig `json:"sql_query_config"` +// Source string `json:"source"` +// } + +// var instancesQueryTpl = `SELECT inst.name, inst.db_type, inst.desc, inst.db_host, +// inst.db_port, inst.db_user, inst.maintenance_period, inst.sql_query_config, inst.source, +// GROUP_CONCAT(DISTINCT COALESCE(rt.name,'')) AS rule_template_names +// FROM instances AS inst +// LEFT JOIN instance_rule_template AS inst_rt ON inst.id = inst_rt.instance_id +// LEFT JOIN rule_templates AS rt ON inst_rt.rule_template_id = rt.id AND rt.deleted_at IS NULL +// WHERE +// inst.id in (SELECT DISTINCT(inst.id) + +// {{- template "body" . -}} +// ) +// GROUP BY inst.id +// {{- if .limit }} +// LIMIT :limit OFFSET :offset +// {{- end -}} +// ` + +// var instancesCountTpl = `SELECT COUNT(DISTINCT inst.id) + +// {{- template "body" . -}} +// ` + +// var instancesQueryBodyTpl = ` +// {{ define "body" }} +// FROM instances AS inst +// LEFT JOIN instance_rule_template AS inst_rt ON inst.id = inst_rt.instance_id +// LEFT JOIN rule_templates AS rt ON inst_rt.rule_template_id = rt.id AND rt.deleted_at IS NULL +// LEFT JOIN projects AS p ON inst.project_id = p.id + +// WHERE inst.deleted_at IS NULL + +// AND p.name = :filter_project_name + +// {{- if .filter_instance_name }} +// AND inst.name = :filter_instance_name +// {{- end }} + +// {{- if .filter_db_host }} +// AND inst.db_host = :filter_db_host +// {{- end }} + +// {{- if .filter_db_port }} +// AND inst.db_port = :filter_db_port +// {{- end }} + +// {{- if .filter_db_user }} +// AND inst.db_user = :filter_db_user +// {{- end }} + +// {{- if .filter_db_type }} +// AND inst.db_type = :filter_db_type +// {{- end }} + +// {{- if .filter_rule_template_name }} +// AND rt.name = :filter_rule_template_name +// {{- end }} + +// {{- end }} +// ` + +// func (s *Storage) GetInstancesByReq(data map[string]interface{}, user *User) ( +// result []*InstanceDetail, count uint64, err error) { + +// if data["filter_project_name"] == "" { +// return nil, 0, errors.New(errors.DataInvalid, fmt.Errorf("project name can not be empty")) +// } + +// err = s.getListResult(instancesQueryBodyTpl, instancesQueryTpl, data, &result) +// if err != nil { +// return result, 0, err +// } + +// count, err = s.getCountResult(instancesQueryBodyTpl, instancesCountTpl, data) +// return result, count, err + +// } + +// func (s *Storage) GetInstanceTotalByProjectName(projectName string) (uint64, error) { +// data := map[string]interface{}{ +// "filter_project_name": projectName, +// } +// return s.getCountResult(instancesQueryBodyTpl, instancesCountTpl, data) +// } diff --git a/sqle/model/management_permission.go b/sqle/model/management_permission.go index 0c5388354d..0761e19238 100644 --- a/sqle/model/management_permission.go +++ b/sqle/model/management_permission.go @@ -1,117 +1,117 @@ package model -import ( - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/utils" - - "github.com/jinzhu/gorm" -) - -// NOTE: related model: -// - model.User -type ManagementPermission struct { - Model - UserId uint `gorm:"index"` - PermissionCode uint `gorm:"comment:'平台管理权限'"` -} - -const ( - // management permission list - - // 创建项目 - ManagementPermissionCreateProject uint = iota + 1 -) - -var managementPermission2Desc = map[uint]string{ - ManagementPermissionCreateProject: "创建项目", -} - -func GetManagementPermissionDesc(code uint) string { - desc, ok := managementPermission2Desc[code] - if !ok { - desc = "未知权限" - } - return desc -} - -func GetManagementPermission() map[uint] /*code*/ string /*desc*/ { - resp := map[uint]string{} - for u, s := range managementPermission2Desc { - resp[u] = s - } - return resp -} - -func (s *Storage) UpdateManagementPermission(userID uint, permissionCode []uint) error { - return s.Tx(func(txDB *gorm.DB) error { - err := updateManagementPermission(txDB, userID, permissionCode) - if err != nil { - txDB.Rollback() - return errors.ConnectStorageErrWrapper(err) - } - return nil - }) -} - -func updateManagementPermission(txDB *gorm.DB, userID uint, permissionCode []uint) error { - if err := txDB.Where("user_id = ?", userID).Delete(&ManagementPermission{}).Error; err != nil { - return err - } - for _, code := range permissionCode { - if err := txDB.Create(&ManagementPermission{ - UserId: userID, - PermissionCode: code, - }).Error; err != nil { - return err - } - } - return nil -} - -func (s *Storage) GetManagementPermissionByUserID(userID uint) ([]uint, error) { - code := []*struct { - PermissionCode uint - }{} - err := s.db.Table("management_permissions").Select("permission_code").Where("user_id = ?", userID).Where("deleted_at IS NULL").Find(&code).Error - resp := []uint{} - for _, c := range code { - resp = append(resp, c.PermissionCode) - } - return resp, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetManagementPermissionByUserIDs(userIDs []uint) (map[uint] /*user id*/ []uint /*codes*/, error) { - p := []*ManagementPermission{} - err := s.db.Table("management_permissions").Select("user_id,permission_code").Where("user_id in (?)", userIDs).Where("deleted_at IS NULL").Scan(&p).Error - - resp := map[uint][]uint{} - for _, permission := range p { - resp[permission.UserId] = append(resp[permission.UserId], permission.PermissionCode) - } - - for id := range resp { - resp[id] = utils.RemoveDuplicateUint(resp[id]) - } - - return resp, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) CheckUserHaveManagementPermission(userID uint, code []uint) (bool, error) { - code = utils.RemoveDuplicateUint(code) - - user, _, err := s.GetUserByID(userID) - if err != nil { - return false, err - } - if user.Name == DefaultAdminUser { - return true, nil - } - - var count int - err = s.db.Model(&ManagementPermission{}). - Where("user_id = ?", userID). - Where("permission_code in (?)", code). - Count(&count).Error - - return count == len(code), errors.ConnectStorageErrWrapper(err) -} \ No newline at end of file +// import ( +// "github.com/actiontech/sqle/sqle/errors" +// "github.com/actiontech/sqle/sqle/utils" + +// "github.com/jinzhu/gorm" +// ) + +// // NOTE: related model: +// // - model.User +// type ManagementPermission struct { +// Model +// UserId uint `gorm:"index"` +// PermissionCode uint `gorm:"comment:'平台管理权限'"` +// } + +// const ( +// // management permission list + +// // 创建项目 +// ManagementPermissionCreateProject uint = iota + 1 +// ) + +// var managementPermission2Desc = map[uint]string{ +// ManagementPermissionCreateProject: "创建项目", +// } + +// func GetManagementPermissionDesc(code uint) string { +// desc, ok := managementPermission2Desc[code] +// if !ok { +// desc = "未知权限" +// } +// return desc +// } + +// func GetManagementPermission() map[uint] /*code*/ string /*desc*/ { +// resp := map[uint]string{} +// for u, s := range managementPermission2Desc { +// resp[u] = s +// } +// return resp +// } + +// func (s *Storage) UpdateManagementPermission(userID uint, permissionCode []uint) error { +// return s.Tx(func(txDB *gorm.DB) error { +// err := updateManagementPermission(txDB, userID, permissionCode) +// if err != nil { +// txDB.Rollback() +// return errors.ConnectStorageErrWrapper(err) +// } +// return nil +// }) +// } + +// func updateManagementPermission(txDB *gorm.DB, userID uint, permissionCode []uint) error { +// if err := txDB.Where("user_id = ?", userID).Delete(&ManagementPermission{}).Error; err != nil { +// return err +// } +// for _, code := range permissionCode { +// if err := txDB.Create(&ManagementPermission{ +// UserId: userID, +// PermissionCode: code, +// }).Error; err != nil { +// return err +// } +// } +// return nil +// } + +// func (s *Storage) GetManagementPermissionByUserID(userID uint) ([]uint, error) { +// code := []*struct { +// PermissionCode uint +// }{} +// err := s.db.Table("management_permissions").Select("permission_code").Where("user_id = ?", userID).Where("deleted_at IS NULL").Find(&code).Error +// resp := []uint{} +// for _, c := range code { +// resp = append(resp, c.PermissionCode) +// } +// return resp, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetManagementPermissionByUserIDs(userIDs []uint) (map[uint] /*user id*/ []uint /*codes*/, error) { +// p := []*ManagementPermission{} +// err := s.db.Table("management_permissions").Select("user_id,permission_code").Where("user_id in (?)", userIDs).Where("deleted_at IS NULL").Scan(&p).Error + +// resp := map[uint][]uint{} +// for _, permission := range p { +// resp[permission.UserId] = append(resp[permission.UserId], permission.PermissionCode) +// } + +// for id := range resp { +// resp[id] = utils.RemoveDuplicateUint(resp[id]) +// } + +// return resp, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) CheckUserHaveManagementPermission(userID uint, code []uint) (bool, error) { +// code = utils.RemoveDuplicateUint(code) + +// user, _, err := s.GetUserByID(userID) +// if err != nil { +// return false, err +// } +// if user.Name == DefaultAdminUser { +// return true, nil +// } + +// var count int +// err = s.db.Model(&ManagementPermission{}). +// Where("user_id = ?", userID). +// Where("permission_code in (?)", code). +// Count(&count).Error + +// return count == len(code), errors.ConnectStorageErrWrapper(err) +// } diff --git a/sqle/model/project.go b/sqle/model/project.go index a5e5578c2a..5858a22eed 100644 --- a/sqle/model/project.go +++ b/sqle/model/project.go @@ -1,567 +1,22 @@ package model -import ( - "database/sql" - "fmt" +// import ( +// "database/sql" +// "fmt" - driverV2 "github.com/actiontech/sqle/sqle/driver/v2" - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/utils" +// driverV2 "github.com/actiontech/sqle/sqle/driver/v2" +// "github.com/actiontech/sqle/sqle/errors" +// "github.com/actiontech/sqle/sqle/utils" - "github.com/jinzhu/gorm" -) +// "github.com/jinzhu/gorm" +// ) + +const ProjectIdForGlobalRuleTemplate = "0" -const ProjectIdForGlobalRuleTemplate = 0 +type ProjectUID string const ( ProjectStatusArchived = "archived" ProjectStatusActive = "active" ) -type Project struct { - Model - Name string - Desc string - - Status string `gorm:"default:'active'"` - - CreateUserId uint `gorm:"not null"` - CreateUser *User `gorm:"foreignkey:CreateUserId"` - - Managers []*User `gorm:"many2many:project_manager;"` - Members []*User `gorm:"many2many:project_user;"` - UserGroups []*UserGroup `gorm:"many2many:project_user_group;"` - - Workflows []*Workflow `gorm:"foreignkey:ProjectId"` - AuditPlans []*AuditPlan `gorm:"foreignkey:ProjectId"` - Instances []*Instance `gorm:"foreignkey:ProjectId"` - SqlWhitelist []*SqlWhitelist `gorm:"foreignkey:ProjectId"` - RuleTemplates []*RuleTemplate `gorm:"foreignkey:ProjectId"` - - WorkflowTemplateId uint `gorm:"not null"` - WorkflowTemplate *WorkflowTemplate `gorm:"foreignkey:WorkflowTemplateId"` -} - -func (p *Project) IsArchived() bool { - return p.Status == ProjectStatusArchived -} - -// IsProjectExist 用于判断当前是否存在项目, 而非某个项目是否存在 -func (s *Storage) IsProjectExist() (bool, error) { - var count uint - err := s.db.Model(&Project{}).Count(&count).Error - return count > 0, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) CreateProject(name string, desc string, createUserID uint) error { - wt := &WorkflowTemplate{ - Name: fmt.Sprintf("%v-WorkflowTemplate", name), - Desc: fmt.Sprintf("%v 默认模板", name), - AllowSubmitWhenLessAuditLevel: string(driverV2.RuleLevelWarn), - Steps: []*WorkflowStepTemplate{ - { - Number: 1, - Typ: WorkflowStepTypeSQLReview, - ApprovedByAuthorized: sql.NullBool{ - Bool: true, - Valid: true, - }, - }, - { - Number: 2, - Typ: WorkflowStepTypeSQLExecute, - ExecuteByAuthorized: sql.NullBool{ - Bool: true, - Valid: true, - }, - }, - }, - } - - return s.TxExec(func(tx *sql.Tx) error { - templateID, err := saveWorkflowTemplate(wt, tx) - if err != nil { - return err - } - - result, err := tx.Exec("INSERT INTO projects (`name`, `desc`, `create_user_id`,`workflow_template_id`) values (?, ?, ?,?)", name, desc, createUserID, templateID) - if err != nil { - return err - } - projectID, err := result.LastInsertId() - if err != nil { - return err - } - _, err = tx.Exec("INSERT INTO project_manager (`project_id`, `user_id`) VALUES (?, ?)", projectID, createUserID) - if err != nil { - return err - } - _, err = tx.Exec("INSERT INTO project_user (`project_id`, `user_id`) VALUES (?, ?)", projectID, createUserID) - if err != nil { - return err - } - - return nil - }) -} - -func (s *Storage) UpdateProjectInfoByID(projectName string, attr map[string]interface{}) error { - err := s.db.Table("projects").Where("name = ?", projectName).Update(attr).Error - return errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetProjectByID(projectID uint) (*Project, bool, error) { - p := &Project{} - err := s.db.Model(&Project{}).Where("id = ?", projectID).Find(p).Error - if err == gorm.ErrRecordNotFound { - return p, false, nil - } - return p, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetProjectByName(projectName string) (*Project, bool, error) { - p := &Project{} - err := s.db.Preload("CreateUser").Preload("Members").Preload("Managers").Preload("Instances"). - Where("name = ?", projectName).First(p).Error - if err == gorm.ErrRecordNotFound { - return p, false, nil - } - return p, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetProjectTips(userName string) ([]*Project, error) { - p := []*Project{} - query := s.db.Table("projects").Select("DISTINCT projects.name,projects.id") - - var err error - if userName != DefaultAdminUser { - err = query.Joins("LEFT JOIN project_user on project_user.project_id = projects.id"). - Joins("LEFT JOIN users on users.id = project_user.user_id"). - Joins("LEFT JOIN project_user_group on project_user_group.project_id = projects.id"). - Joins("LEFT JOIN user_group_users on project_user_group.user_group_id = user_group_users.user_group_id"). - Joins("LEFT JOIN users as u on u.id = user_group_users.user_id"). - Where("(users.login_name = ? AND users.stat = 0) OR (u.login_name = ? AND u.stat = 0)", userName, userName).Find(&p).Error - } else { - err = query.Find(&p).Error - } - - if err == gorm.ErrRecordNotFound { - err = nil - } - return p, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) IsUserInProject(userName, projectName string) (bool, error) { - query := ` -SELECT EXISTS( -SELECT users.login_name -FROM users -LEFT JOIN project_user on project_user.user_id = users.id -LEFT JOIN projects on project_user.project_id = projects.id -LEFT JOIN user_group_users on users.id = user_group_users.user_id -LEFT JOIN project_user_group on user_group_users.user_group_id = project_user_group.user_group_id -LEFT JOIN projects as p on project_user_group.project_id = p.id -WHERE users.stat = 0 -AND users.deleted_at IS NULL -AND users.login_name = ? -AND( - projects.name = ? -OR - p.name = ? -)) AS exist -` - var exist struct { - Exist bool `json:"exist"` - } - err := s.db.Raw(query, userName, projectName, projectName).Find(&exist).Error - return exist.Exist, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) CheckUserIsMember(userName, projectName string) (bool, error) { - query := ` -SELECT EXISTS( -SELECT 1 -FROM project_user -LEFT JOIN projects ON projects.id = project_user.project_id -LEFT JOIN users ON users.id = project_user.user_id -WHERE users.stat = 0 -AND users.deleted_at IS NULL -AND users.login_name = ? -AND projects.name = ? -AND projects.deleted_at IS NULL -) AS exist -` - var exist struct { - Exist bool `json:"exist"` - } - err := s.db.Raw(query, userName, projectName).Find(&exist).Error - return exist.Exist, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) CheckUserGroupIsMember(groupName, projectName string) (bool, error) { - query := ` -SELECT EXISTS( -SELECT 1 -FROM project_user_group -LEFT JOIN projects ON projects.id = project_user_group.project_id -LEFT JOIN user_groups ON user_groups.id = project_user_group.user_group_id -WHERE user_groups.stat = 0 -AND user_groups.deleted_at IS NULL -AND user_groups.name = ? -AND projects.name = ? -AND projects.deleted_at IS NULL -) AS exist -` - var exist struct { - Exist bool `json:"exist"` - } - err := s.db.Raw(query, groupName, projectName).Find(&exist).Error - return exist.Exist, errors.New(errors.ConnectStorageError, err) -} - -type ProjectAndInstance struct { - InstanceName string `json:"instance_name"` - ProjectName string `json:"project_name"` -} - -func (s *Storage) GetProjectNamesByInstanceIds(instanceIds []uint) (map[uint] /*instance id*/ ProjectAndInstance, error) { - instanceIds = utils.RemoveDuplicateUint(instanceIds) - type record struct { - InstanceId uint `json:"instance_id"` - InstanceName string `json:"instance_name"` - ProjectName string `json:"project_name"` - } - records := []record{} - err := s.db.Table("instances"). - Joins("LEFT JOIN projects ON projects.id = instances.project_id"). - Select("instances.id AS instance_id, instances.name AS instance_name, projects.name AS project_name"). - Where("instances.id IN (?)", instanceIds). - Find(&records).Error - - if err != nil { - return nil, errors.New(errors.ConnectStorageError, err) - } - - res := make(map[uint]ProjectAndInstance, len(records)) - for _, r := range records { - res[r.InstanceId] = ProjectAndInstance{ - InstanceName: r.InstanceName, - ProjectName: r.ProjectName, - } - } - - return res, nil -} - -func (s *Storage) AddMember(userName, projectName string, isManager bool, bindRole []BindRole) error { - user, exist, err := s.GetUserByName(userName) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - if !exist { - return errors.ConnectStorageErrWrapper(fmt.Errorf("user not exist")) - } - - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - if !exist { - return errors.ConnectStorageErrWrapper(fmt.Errorf("project not exist")) - } - - return errors.New(errors.ConnectStorageError, s.db.Transaction(func(tx *gorm.DB) error { - - if err = tx.Exec("INSERT INTO project_user (project_id, user_id) VALUES (?,?)", project.ID, user.ID).Error; err != nil { - return errors.ConnectStorageErrWrapper(err) - } - - if isManager { - if err = tx.Exec("INSERT INTO project_manager (project_id, user_id) VALUES (?,?)", project.ID, user.ID).Error; err != nil { - return errors.ConnectStorageErrWrapper(err) - } - } - - err = s.updateUserRoles(tx, user, projectName, bindRole) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - return nil - })) -} - -func (s *Storage) AddProjectManager(userName, projectName string) error { - sql := ` -INSERT INTO project_manager -SELECT projects.id AS project_id , users.id AS user_id -FROM projects -JOIN users -WHERE projects.name = ? -AND users.login_name = ? -AND users.deleted_at is null -LIMIT 1 -` - - return errors.ConnectStorageErrWrapper(s.db.Exec(sql, projectName, userName).Error) -} - -func (s *Storage) RemoveProjectManager(userName, projectName string) error { - sql := ` -DELETE project_manager -FROM project_manager -JOIN projects ON project_manager.project_id = projects.id -JOIN users ON project_manager.user_id = users.id -WHERE projects.name = ? -AND users.login_name = ? -AND users.deleted_at is null -` - - return errors.ConnectStorageErrWrapper(s.db.Exec(sql, projectName, userName).Error) -} - -func (s *Storage) RemoveMember(userName, projectName string) error { - sql := ` -DELETE project_user, project_manager, project_member_roles -FROM project_user -LEFT JOIN project_manager ON project_user.project_id = project_manager.project_id - AND project_user.user_id = project_manager.user_id -LEFT JOIN projects ON project_user.project_id = projects.id -LEFT JOIN users ON project_user.user_id = users.id -LEFT JOIN project_member_roles ON project_member_roles.user_id = users.id -WHERE -users.login_name = ? -AND -projects.name = ? -` - - return errors.ConnectStorageErrWrapper(s.db.Exec(sql, userName, projectName).Error) -} - -func (s *Storage) AddMemberGroup(groupName, projectName string, bindRole []BindRole) error { - group, exist, err := s.GetUserGroupByName(groupName) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - if !exist { - return errors.ConnectStorageErrWrapper(fmt.Errorf("user group not exist")) - } - - project, exist, err := s.GetProjectByName(projectName) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - if !exist { - return errors.ConnectStorageErrWrapper(fmt.Errorf("project not exist")) - } - - return errors.New(errors.ConnectStorageError, s.db.Transaction(func(tx *gorm.DB) error { - - if err = tx.Exec("INSERT INTO project_user_group (project_id, user_group_id) VALUES (?,?)", project.ID, group.ID).Error; err != nil { - return errors.ConnectStorageErrWrapper(err) - } - - err = s.updateUserGroupRoles(tx, group, projectName, bindRole) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - return nil - })) -} - -func (s *Storage) RemoveMemberGroup(groupName, projectName string) error { - sql := ` -DELETE project_user_group, project_member_group_roles -FROM project_user_group -LEFT JOIN projects ON project_user_group.project_id = projects.id -LEFT JOIN user_groups ON project_user_group.user_group_id = user_groups.id -LEFT JOIN project_member_group_roles ON project_member_group_roles.user_group_id = user_groups.id -WHERE -user_groups.name = ? -AND -projects.name = ? -` - - return errors.ConnectStorageErrWrapper(s.db.Exec(sql, groupName, projectName).Error) -} - -type GetMemberGroupFilter struct { - FilterProjectName *string - FilterUserGroupName *string - FilterInstanceName *string - Limit *uint32 - Offset *uint32 -} - -func generateMemberGroupQueryCriteria(query *gorm.DB, filter GetMemberGroupFilter) (*gorm.DB, error) { - if filter.FilterProjectName == nil { - return nil, errors.ConnectStorageErrWrapper(fmt.Errorf("project name cannot be empty")) - } - - query = query.Model(&UserGroup{}). - Preload("Users"). - Joins("LEFT JOIN project_user_group ON project_user_group.user_group_id = user_groups.id"). - Joins("LEFT JOIN projects ON projects.id = project_user_group.project_id"). - Where("user_groups.stat = 0"). - Where("user_groups.deleted_at IS NULL"). - Where("projects.deleted_at IS NULL"). - Where("projects.name = ?", *filter.FilterProjectName). - Group("user_groups.id") - - if filter.Limit != nil { - query = query.Limit(*filter.Limit).Offset(*filter.Offset) - } - if filter.FilterUserGroupName != nil { - query = query.Where("user_groups.name = ?", *filter.FilterUserGroupName) - } - if filter.FilterInstanceName != nil { - query = query. - Joins("LEFT JOIN instances ON instances.project_id = projects.id"). - Where("instances.deleted_at IS NULL"). - Joins("JOIN project_member_group_roles ON project_member_group_roles.user_group_id = user_groups.id AND project_member_group_roles.instance_id = instances.id"). - Where("instances.name = ?", *filter.FilterInstanceName) - } - return query, nil -} - -func (s *Storage) GetMemberGroups(filter GetMemberGroupFilter) ([]*UserGroup, error) { - group := []*UserGroup{} - query, err := generateMemberGroupQueryCriteria(s.db, filter) - if err != nil { - return nil, err - } - err = query.Find(&group).Error - return group, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) GetMemberGroupCount(filter GetMemberGroupFilter) (uint64, error) { - // count要查总数, 清掉limit - filter.Limit = nil - filter.Offset = nil - - var count uint64 - query, err := generateMemberGroupQueryCriteria(s.db, filter) - if err != nil { - return 0, err - } - err = query.Count(&count).Error - return count, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) GetMemberGroupByGroupName(projectName, groupName string) (*UserGroup, error) { - group := &UserGroup{} - err := s.db.Joins("LEFT JOIN project_user_group ON project_user_group.user_group_id = user_groups.id"). - Joins("LEFT JOIN projects ON project_user_group.project_id = projects.id"). - Where("projects.name = ?", projectName). - Where("user_groups.name = ?", groupName). - Find(group).Error - return group, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) RemoveMemberFromAllProjectByUserID(userID uint) error { - sql := ` -DELETE project_user, project_manager, project_member_roles -FROM project_user -LEFT JOIN project_manager ON project_user.project_id = project_manager.project_id - AND project_user.user_id = project_manager.user_id -LEFT JOIN project_member_roles ON project_member_roles.user_id = ? -LEFT JOIN users ON project_user.user_id = users.id -WHERE -users.id = ? -` - - return errors.ConnectStorageErrWrapper(s.db.Exec(sql, userID, userID).Error) -} - -func (s *Storage) RemoveMemberGroupFromAllProjectByUserGroupID(userGroupID uint) error { - sql := ` -DELETE project_user_group, project_member_group_roles -FROM project_user_group -LEFT JOIN projects ON project_user_group.project_id = projects.id -LEFT JOIN user_groups ON project_user_group.user_group_id = user_groups.id -LEFT JOIN project_member_group_roles ON project_member_group_roles.user_group_id = ? -WHERE -user_groups.id = ? -` - - return errors.ConnectStorageErrWrapper(s.db.Exec(sql, userGroupID, userGroupID).Error) -} - -func (s *Storage) IsLastProjectManager(userName, projectName string) (bool, error) { - - project, _, err := s.GetProjectByName(projectName) - if err != nil { - return true, err - } - - return len(project.Managers) == 1 && project.Managers[0].Name == userName, nil -} - -// 检查用户是否是某一个项目的最后一个管理员 -func (s *Storage) IsLastProjectManagerOfAnyProjectByUserID(userID uint) (bool, error) { - - sql := ` -select count(1) as count -from project_manager -where project_id in( - select distinct project_id - from project_manager - where user_id = ? - ) -group by project_id; -` - - var count []*struct { - Count int `json:"count"` - } - err := s.db.Raw(sql, userID).Scan(&count).Error - if err != nil { - return true, errors.ConnectStorageErrWrapper(err) - } - - for _, c := range count { - if c.Count == 1 { - return true, nil - } - } - return false, nil -} - -func (s *Storage) CheckUserHasManagementPermission(userID uint, code []uint) (bool, error) { - code = utils.RemoveDuplicateUint(code) - - user, _, err := s.GetUserByID(userID) - if err != nil { - return false, err - } - if user.Name == DefaultAdminUser { - return true, nil - } - - var count int - err = s.db.Model(&ManagementPermission{}). - Where("user_id = ?", userID). - Where("permission_code in (?)", code). - Count(&count).Error - - return count == len(code), errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) GetManagedProjects(userID uint) ([]*Project, error) { - p := []*Project{} - err := s.db.Joins("LEFT JOIN project_manager ON project_manager.project_id = projects.id"). - Where("project_manager.user_id = ?", userID). - Find(&p).Error - return p, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) IsProjectArchived(projectName string) (bool, error) { - proj := &Project{} - err := s.db.Select("status").Where("name = ?", projectName).First(&proj).Error - if err == gorm.ErrRecordNotFound { - return false, fmt.Errorf("project doesn't exist") - } - if err != nil { - return false, err - } - return proj.Status == ProjectStatusArchived, nil -} diff --git a/sqle/model/project_list.go b/sqle/model/project_list.go index 7096ab1e87..4fc603e0c4 100644 --- a/sqle/model/project_list.go +++ b/sqle/model/project_list.go @@ -1,172 +1,171 @@ package model -import ( - "fmt" - "time" - - "github.com/actiontech/sqle/sqle/errors" -) - -type ProjectDetail struct { - Name string `json:"name"` - Desc string `json:"desc"` - CreateUserName string `json:"create_user_name"` - CreateTime time.Time `json:"create_time"` - Status string `json:"status"` -} - -var projectsQueryTpl = `SELECT -DISTINCT projects.name , projects.` + "`desc`" + `, cu.login_name as create_user_name, projects.created_at as create_time, projects.status as status - -{{- template "body" . -}} - -{{ if .limit }} -LIMIT :limit OFFSET :offset -{{ end }} -` - -var projectsCountTpl = `SELECT COUNT(DISTINCT projects.id) - -{{- template "body" . -}} -` - -var projectsQueryBodyTpl = ` -{{ define "body" }} - -FROM projects -LEFT JOIN project_user ON project_user.project_id = projects.id -LEFT JOIN users ON users.id = project_user.user_id -LEFT JOIN project_user_group ON project_user_group.project_id = projects.id -LEFT JOIN user_group_users ON project_user_group.user_group_id = user_group_users.user_group_id -LEFT JOIN users AS u ON u.id = user_group_users.user_id -LEFT JOIN users AS cu ON cu.id = projects.create_user_id -WHERE -projects.deleted_at IS NULL - -{{ if .filter_user_name }} -AND -(( - users.login_name = :filter_user_name - AND users.deleted_at IS NULL - AND users.stat = 0 -) -OR ( - u.login_name = :filter_user_name - AND u.deleted_at IS NULL - AND u.stat = 0 -)) -{{ end }} - - -{{ end }} -` - -func (s *Storage) GetProjectsByReq(data map[string]interface{}) ( - result []*ProjectDetail, count uint64, err error) { - - if data["filter_user_name"] == DefaultAdminUser { - delete(data, "filter_user_name") - } - - err = s.getListResult(projectsQueryBodyTpl, projectsQueryTpl, data, &result) - if err != nil { - return result, 0, err - } - count, err = s.getCountResult(projectsQueryBodyTpl, projectsCountTpl, data) - return result, count, err -} - -type MemberDetail struct { - UserName string `json:"user_name"` - IsManager bool `json:"is_manager"` -} - -var membersQueryTpl = ` -SELECT DISTINCT users.login_name AS user_name - -{{ template "body" . }} - -{{ if .limit }} -LIMIT :limit OFFSET :offset -{{ end }} - -` - -var membersCountTpl = ` -SELECT COUNT(DISTINCT project_user.user_id) -{{ template "body" . }} -` - -var membersQueryBodyTpl = ` -{{ define "body" }} - -FROM project_user -LEFT JOIN users ON users.id = project_user.user_id -LEFT JOIN projects ON projects.id = project_user.project_id - -{{ if .filter_instance_name }} -LEFT JOIN instances ON instances.project_id = projects.id -{{ end }} - -{{ if .filter_instance_name }} -JOIN project_member_roles ON project_member_roles.user_id = users.id AND project_member_roles.instance_id = instances.id -{{ end }} - -WHERE users.stat = 0 -AND users.deleted_at IS NULL -AND projects.deleted_at IS NULL - -{{ if .filter_instance_name }} -AND instances.deleted_at IS NULL -{{ end }} - -AND projects.name = :filter_project_name - -{{ if .filter_user_name }} -AND users.login_name = :filter_user_name -{{ end }} - -{{ if .filter_instance_name }} -AND instances.name = :filter_instance_name -{{ end }} - -{{ end }} -` - -func (s *Storage) GetMembersByReq(data map[string]interface{}) ( - result []*MemberDetail, count uint64, err error) { - - if data["filter_project_name"] == nil { - return nil, 0, errors.New(errors.DataInvalid, fmt.Errorf("project name must be exist")) - } - - members := []*struct { - UserName string `json:"user_name"` - }{} - err = s.getListResult(membersQueryBodyTpl, membersQueryTpl, data, &members) - if err != nil { - return result, 0, err - } - - project, _, err := s.GetProjectByName(fmt.Sprintf("%v", data["filter_project_name"])) - if err != nil { - return result, 0, err - } - - for _, member := range members { - isManager := false - for _, manager := range project.Managers { - if manager.Name == member.UserName { - isManager = true - break - } - } - result = append(result, &MemberDetail{ - UserName: member.UserName, - IsManager: isManager, - }) - } - - count, err = s.getCountResult(membersQueryBodyTpl, membersCountTpl, data) - return result, count, err -} +// import ( +// "fmt" +// "time" + +// "github.com/actiontech/sqle/sqle/errors" +// ) + +// type ProjectDetail struct { +// Name string `json:"name"` +// Desc string `json:"desc"` +// CreateUserName string `json:"create_user_name"` +// CreateTime time.Time `json:"create_time"` +// Status string `json:"status"` +// } + +// var projectsQueryTpl = `SELECT +// DISTINCT projects.name , projects.` + "`desc`" + `, cu.login_name as create_user_name, projects.created_at as create_time, projects.status as status + +// {{- template "body" . -}} + +// {{ if .limit }} +// LIMIT :limit OFFSET :offset +// {{ end }} +// ` + +// var projectsCountTpl = `SELECT COUNT(DISTINCT projects.id) + +// {{- template "body" . -}} +// ` + +// var projectsQueryBodyTpl = ` +// {{ define "body" }} + +// FROM projects +// LEFT JOIN project_user ON project_user.project_id = projects.id +// LEFT JOIN users ON users.id = project_user.user_id +// LEFT JOIN project_user_group ON project_user_group.project_id = projects.id +// LEFT JOIN user_group_users ON project_user_group.user_group_id = user_group_users.user_group_id +// LEFT JOIN users AS u ON u.id = user_group_users.user_id +// LEFT JOIN users AS cu ON cu.id = projects.create_user_id +// WHERE +// projects.deleted_at IS NULL + +// {{ if .filter_user_name }} +// AND +// (( +// users.login_name = :filter_user_name +// AND users.deleted_at IS NULL +// AND users.stat = 0 +// ) +// OR ( +// u.login_name = :filter_user_name +// AND u.deleted_at IS NULL +// AND u.stat = 0 +// )) +// {{ end }} + +// {{ end }} +// ` + +// func (s *Storage) GetProjectsByReq(data map[string]interface{}) ( +// result []*ProjectDetail, count uint64, err error) { + +// if data["filter_user_name"] == DefaultAdminUser { +// delete(data, "filter_user_name") +// } + +// err = s.getListResult(projectsQueryBodyTpl, projectsQueryTpl, data, &result) +// if err != nil { +// return result, 0, err +// } +// count, err = s.getCountResult(projectsQueryBodyTpl, projectsCountTpl, data) +// return result, count, err +// } + +// type MemberDetail struct { +// UserName string `json:"user_name"` +// IsManager bool `json:"is_manager"` +// } + +// var membersQueryTpl = ` +// SELECT DISTINCT users.login_name AS user_name + +// {{ template "body" . }} + +// {{ if .limit }} +// LIMIT :limit OFFSET :offset +// {{ end }} + +// ` + +// var membersCountTpl = ` +// SELECT COUNT(DISTINCT project_user.user_id) +// {{ template "body" . }} +// ` + +// var membersQueryBodyTpl = ` +// {{ define "body" }} + +// FROM project_user +// LEFT JOIN users ON users.id = project_user.user_id +// LEFT JOIN projects ON projects.id = project_user.project_id + +// {{ if .filter_instance_name }} +// LEFT JOIN instances ON instances.project_id = projects.id +// {{ end }} + +// {{ if .filter_instance_name }} +// JOIN project_member_roles ON project_member_roles.user_id = users.id AND project_member_roles.instance_id = instances.id +// {{ end }} + +// WHERE users.stat = 0 +// AND users.deleted_at IS NULL +// AND projects.deleted_at IS NULL + +// {{ if .filter_instance_name }} +// AND instances.deleted_at IS NULL +// {{ end }} + +// AND projects.name = :filter_project_name + +// {{ if .filter_user_name }} +// AND users.login_name = :filter_user_name +// {{ end }} + +// {{ if .filter_instance_name }} +// AND instances.name = :filter_instance_name +// {{ end }} + +// {{ end }} +// ` + +// func (s *Storage) GetMembersByReq(data map[string]interface{}) ( +// result []*MemberDetail, count uint64, err error) { + +// if data["filter_project_name"] == nil { +// return nil, 0, errors.New(errors.DataInvalid, fmt.Errorf("project name must be exist")) +// } + +// members := []*struct { +// UserName string `json:"user_name"` +// }{} +// err = s.getListResult(membersQueryBodyTpl, membersQueryTpl, data, &members) +// if err != nil { +// return result, 0, err +// } + +// project, _, err := s.GetProjectByName(fmt.Sprintf("%v", data["filter_project_name"])) +// if err != nil { +// return result, 0, err +// } + +// for _, member := range members { +// isManager := false +// for _, manager := range project.Managers { +// if manager.Name == member.UserName { +// isManager = true +// break +// } +// } +// result = append(result, &MemberDetail{ +// UserName: member.UserName, +// IsManager: isManager, +// }) +// } + +// count, err = s.getCountResult(membersQueryBodyTpl, membersCountTpl, data) +// return result, count, err +// } diff --git a/sqle/model/project_permission.go b/sqle/model/project_permission.go index 689cc18c8e..150ec48f59 100644 --- a/sqle/model/project_permission.go +++ b/sqle/model/project_permission.go @@ -1,468 +1,499 @@ package model -import ( - "github.com/actiontech/sqle/sqle/errors" - "github.com/jinzhu/gorm" -) - -/* - -instance permission. - -*/ - -var queryInstanceUserWithOp = ` -SELECT - -{{- template "select_fields" . -}} - -FROM instances -{{- if .project_name }} -LEFT JOIN projects ON instances.project_id = projects.id -{{- end }} -LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id -LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 -LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 -LEFT JOIN role_operations ON role_operations.role_id = roles.id -WHERE -instances.deleted_at IS NULL -AND users.id = :user_id -AND role_operations.op_code IN (:op_codes) - -{{- if .instance_ids }} -AND instances.id IN (:instance_ids) -{{- end }} - -{{- if .project_name }} -AND projects.name = :project_name -{{- end }} - -{{- if .db_type }} -AND instances.db_type = :db_type -{{- end }} -GROUP BY instances.id - -UNION -SELECT - -{{- template "select_fields" . -}} - -FROM instances -{{- if .project_name }} -LEFT JOIN projects ON instances.project_id = projects.id -{{- end }} -LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id -LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 -LEFT JOIN role_operations ON role_operations.role_id = roles.id -LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 -JOIN user_group_users ON user_groups.id = user_group_users.user_group_id -JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 -WHERE -instances.deleted_at IS NULL -AND users.id = :user_id -AND role_operations.op_code IN (:op_codes) - -{{- if .instance_ids }} -AND instances.id IN (:instance_ids) -{{- end }} - -{{- if .project_name }} -AND projects.name = :project_name -{{- end }} - -{{- if .db_type }} -AND instances.db_type = :db_type -{{- end }} -GROUP BY instances.id - -UNION -SELECT - -{{- template "select_fields" . -}} - -FROM instances -LEFT JOIN projects ON instances.project_id = projects.id -LEFT JOIN project_manager ON project_manager.project_id = projects.id -LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 -WHERE -instances.deleted_at IS NULL -AND users.id = :user_id - -{{- if .instance_ids }} -AND instances.id IN (:instance_ids) -{{- end }} - -{{- if .project_name }} -AND projects.name = :project_name -{{- end }} - -{{- if .db_type }} -AND instances.db_type = :db_type -{{- end }} -GROUP BY instances.id - -` - -func (s *Storage) filterUserHasOpInstances(user *User, instanceIds []uint, ops []uint) ([]*Instance, error) { - var instanceRecords []*Instance - data := map[string]interface{}{ - "instance_ids": instanceIds, - "op_codes": ops, - "user_id": user.ID, - } - fields := ` -{{ define "select_fields" }} -instances.id -{{ end }} - ` - err := s.getTemplateQueryResult(data, &instanceRecords, queryInstanceUserWithOp, fields) - if err != nil { - return nil, errors.ConnectStorageErrWrapper(err) - } - return instanceRecords, nil -} - -func (s *Storage) CheckUserHasOpToInstances(user *User, instances []*Instance, ops []uint) (bool, error) { - instanceIds := getDeduplicatedInstanceIds(instances) - instanceRecords, err := s.filterUserHasOpInstances(user, instanceIds, ops) - if err != nil { - return false, err - } - return len(instanceRecords) == len(instanceIds), nil -} - -func (s *Storage) CheckUserHasOpToAnyInstance(user *User, instances []*Instance, ops []uint) (bool, error) { - instanceIds := getDeduplicatedInstanceIds(instances) - instanceRecords, err := s.filterUserHasOpInstances(user, instanceIds, ops) - if err != nil { - return false, err - } - return len(instanceRecords) > 0, nil -} - -func (s *Storage) GetUserCanOpInstances(user *User, ops []uint) ([]*Instance, error) { - var instances []*Instance - data := map[string]interface{}{ - "op_codes": ops, - "user_id": user.ID, - } - fields := ` -{{ define "select_fields" }} -instances.id, instances.name -{{ end }} -` - err := s.getTemplateQueryResult(data, &instances, queryInstanceUserWithOp, fields) - if err != nil { - return instances, errors.ConnectStorageErrWrapper(err) - } - return instances, nil -} - -func (s *Storage) GetUserCanOpInstancesFromProject(user *User, projectName string, ops []uint) ([]*Instance, error) { - var instances []*Instance - data := map[string]interface{}{ - "op_codes": ops, - "user_id": user.ID, - "project_name": projectName, - } - fields := ` -{{ define "select_fields" }} -instances.id, instances.name -{{ end }} -` - err := s.getTemplateQueryResult(data, &instances, queryInstanceUserWithOp, fields) - if err != nil { - return instances, errors.ConnectStorageErrWrapper(err) - } - return instances, nil -} - -func (s *Storage) GetInstanceTipsByUserAndOperation(user *User, dbType, projectName string, opCode ...int) ( - instances []*Instance, err error) { - - isProjectManager, err := s.IsProjectManager(user.Name, projectName) - if err != nil { - return nil, err - } - - if IsDefaultAdminUser(user.Name) || isProjectManager { - return s.GetInstanceTipsByTypeAndTempID(dbType, 0, projectName) - } - return s.getInstanceTipsByUserAndOperation(user, dbType, projectName, opCode...) -} - -func (s *Storage) getInstanceTipsByUserAndOperation(user *User, dbType string, projectName string, opCode ...int) ([]*Instance, error) { - var instances []*Instance - data := map[string]interface{}{ - "op_codes": opCode, - "user_id": user.ID, - "project_name": projectName, - "db_type": dbType, - } - fields := ` -{{ define "select_fields" }} -instances.id, instances.name, instances.db_host as host, instances.db_port as port, instances.db_type -{{ end }} - ` - err := s.getTemplateQueryResult(data, &instances, queryInstanceUserWithOp, fields) - if err != nil { - return instances, errors.ConnectStorageErrWrapper(err) - } - return instances, nil -} - -func (s *Storage) UserCanAccessInstance(user *User, instance *Instance) ( - ok bool, err error) { - - isManager, err := s.IsProjectManagerByID(user.ID, instance.ProjectId) - if err != nil { - return false, err - } - - if IsDefaultAdminUser(user.Name) || isManager { - return true, nil - } - - type countStruct struct { - Count int `json:"count"` - } - - query := ` -SELECT COUNT(1) AS count -FROM instances -LEFT JOIN project_member_roles ON project_member_roles.instance_id = instances.id -LEFT JOIN users ON users.id = project_member_roles.user_id -WHERE instances.deleted_at IS NULL -AND users.stat = 0 -AND users.deleted_at IS NULL -AND instances.id = ? -AND users.id = ? -GROUP BY instances.id -UNION -SELECT instances.id -FROM instances -LEFT JOIN project_member_group_roles ON project_member_group_roles.instance_id = instances.id -JOIN user_group_users ON project_member_group_roles.user_group_id = user_group_users.user_group_id -JOIN users ON users.id = user_group_users.user_id -WHERE instances.deleted_at IS NULL -AND users.stat = 0 -AND users.deleted_at IS NULL -AND instances.id = ? -AND users.id = ? -GROUP BY instances.id -` - var cnt countStruct - err = s.db.Unscoped().Raw(query, instance.ID, user.ID, instance.ID, user.ID).Scan(&cnt).Error - if err != nil { - if gorm.IsRecordNotFoundError(err) { - return false, nil - } - return false, errors.New(errors.ConnectStorageError, err) - } - return cnt.Count > 0, nil -} - -func (s *Storage) GetWithOperationUserFromInstance(instance *Instance, opCode ...int) (users []*User, err error) { - query := ` - SELECT users.id, users.login_name - FROM users - LEFT JOIN project_member_roles ON users.id = project_member_roles.user_id - LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 - LEFT JOIN role_operations ON role_operations.role_id = roles.id - WHERE - users.deleted_at IS NULL - AND users.stat = 0 - AND project_member_roles.instance_id = ? - AND role_operations.op_code IN (?) - - UNION - SELECT users.id, users.login_name - FROM users - LEFT JOIN user_group_users ON users.id = user_group_users.user_id - LEFT JOIN user_groups ON user_group_users.user_group_id = user_groups.id AND user_groups.stat = 0 - LEFT JOIN project_member_group_roles ON user_groups.id = project_member_group_roles.user_group_id - LEFT JOIN roles ON project_member_group_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 - LEFT JOIN role_operations ON role_operations.role_id = roles.id - WHERE - users.deleted_at IS NULL - AND users.stat = 0 - AND project_member_group_roles.instance_id = ? - AND role_operations.op_code IN (?) - ` - err = s.db.Raw(query, instance.ID, opCode, instance.ID, opCode).Scan(&users).Error - if err != nil { - return nil, errors.ConnectStorageErrWrapper(err) - } - return -} - -/* - -workflow permission. - -*/ - -func (s *Storage) UserCanAccessWorkflow(user *User, workflow *Workflow) (bool, error) { +import "github.com/actiontech/sqle/sqle/errors" + +// import ( +// "github.com/actiontech/sqle/sqle/errors" +// "github.com/jinzhu/gorm" +// ) + +// /* + +// instance permission. + +// */ + +// var queryInstanceUserWithOp = ` +// SELECT + +// {{- template "select_fields" . -}} + +// FROM instances +// {{- if .project_name }} +// LEFT JOIN projects ON instances.project_id = projects.id +// {{- end }} +// LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id +// LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// WHERE +// instances.deleted_at IS NULL +// AND users.id = :user_id +// AND role_operations.op_code IN (:op_codes) + +// {{- if .instance_ids }} +// AND instances.id IN (:instance_ids) +// {{- end }} + +// {{- if .project_name }} +// AND projects.name = :project_name +// {{- end }} + +// {{- if .db_type }} +// AND instances.db_type = :db_type +// {{- end }} +// GROUP BY instances.id + +// UNION +// SELECT + +// {{- template "select_fields" . -}} + +// FROM instances +// {{- if .project_name }} +// LEFT JOIN projects ON instances.project_id = projects.id +// {{- end }} +// LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id +// LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 +// JOIN user_group_users ON user_groups.id = user_group_users.user_group_id +// JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = :user_id +// AND role_operations.op_code IN (:op_codes) + +// {{- if .instance_ids }} +// AND instances.id IN (:instance_ids) +// {{- end }} + +// {{- if .project_name }} +// AND projects.name = :project_name +// {{- end }} + +// {{- if .db_type }} +// AND instances.db_type = :db_type +// {{- end }} +// GROUP BY instances.id + +// UNION +// SELECT + +// {{- template "select_fields" . -}} + +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_manager ON project_manager.project_id = projects.id +// LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = :user_id + +// {{- if .instance_ids }} +// AND instances.id IN (:instance_ids) +// {{- end }} + +// {{- if .project_name }} +// AND projects.name = :project_name +// {{- end }} + +// {{- if .db_type }} +// AND instances.db_type = :db_type +// {{- end }} +// GROUP BY instances.id + +// ` + +// func (s *Storage) filterUserHasOpInstances(user *User, instanceIds []uint, ops []uint) ([]*Instance, error) { +// var instanceRecords []*Instance +// data := map[string]interface{}{ +// "instance_ids": instanceIds, +// "op_codes": ops, +// "user_id": user.ID, +// } +// fields := ` +// {{ define "select_fields" }} +// instances.id +// {{ end }} +// ` +// err := s.getTemplateQueryResult(data, &instanceRecords, queryInstanceUserWithOp, fields) +// if err != nil { +// return nil, errors.ConnectStorageErrWrapper(err) +// } +// return instanceRecords, nil +// } + +// func (s *Storage) CheckUserHasOpToInstances(user *User, instances []*Instance, ops []uint) (bool, error) { +// instanceIds := getDeduplicatedInstanceIds(instances) +// instanceRecords, err := s.filterUserHasOpInstances(user, instanceIds, ops) +// if err != nil { +// return false, err +// } +// return len(instanceRecords) == len(instanceIds), nil +// } + +// func (s *Storage) CheckUserHasOpToAnyInstance(user *User, instances []*Instance, ops []uint) (bool, error) { +// instanceIds := getDeduplicatedInstanceIds(instances) +// instanceRecords, err := s.filterUserHasOpInstances(user, instanceIds, ops) +// if err != nil { +// return false, err +// } +// return len(instanceRecords) > 0, nil +// } + +// func (s *Storage) GetUserCanOpInstances(user *User, ops []uint) ([]*Instance, error) { +// var instances []*Instance +// data := map[string]interface{}{ +// "op_codes": ops, +// "user_id": user.ID, +// } +// fields := ` +// {{ define "select_fields" }} +// instances.id, instances.name +// {{ end }} +// ` +// err := s.getTemplateQueryResult(data, &instances, queryInstanceUserWithOp, fields) +// if err != nil { +// return instances, errors.ConnectStorageErrWrapper(err) +// } +// return instances, nil +// } + +// func (s *Storage) GetUserCanOpInstancesFromProject(user *User, projectName string, ops []uint) ([]*Instance, error) { +// var instances []*Instance +// data := map[string]interface{}{ +// "op_codes": ops, +// "user_id": user.ID, +// "project_name": projectName, +// } +// fields := ` +// {{ define "select_fields" }} +// instances.id, instances.name +// {{ end }} +// ` +// err := s.getTemplateQueryResult(data, &instances, queryInstanceUserWithOp, fields) +// if err != nil { +// return instances, errors.ConnectStorageErrWrapper(err) +// } +// return instances, nil +// } + +// func (s *Storage) GetInstanceTipsByUserAndOperation(user *User, dbType, projectName string, opCode ...int) ( +// instances []*Instance, err error) { + +// isProjectManager, err := s.IsProjectManager(user.Name, projectName) +// if err != nil { +// return nil, err +// } + +// if IsDefaultAdminUser(user.Name) || isProjectManager { +// return s.GetInstanceTipsByTypeAndTempID(dbType, 0, projectName) +// } +// return s.getInstanceTipsByUserAndOperation(user, dbType, projectName, opCode...) +// } + +// func (s *Storage) getInstanceTipsByUserAndOperation(user *User, dbType string, projectName string, opCode ...int) ([]*Instance, error) { +// var instances []*Instance +// data := map[string]interface{}{ +// "op_codes": opCode, +// "user_id": user.ID, +// "project_name": projectName, +// "db_type": dbType, +// } +// fields := ` +// {{ define "select_fields" }} +// instances.id, instances.name, instances.db_host as host, instances.db_port as port, instances.db_type +// {{ end }} +// ` +// err := s.getTemplateQueryResult(data, &instances, queryInstanceUserWithOp, fields) +// if err != nil { +// return instances, errors.ConnectStorageErrWrapper(err) +// } +// return instances, nil +// } + +// func (s *Storage) UserCanAccessInstance(user *User, instance *Instance) ( +// ok bool, err error) { + +// isManager, err := s.IsProjectManagerByID(user.ID, instance.ProjectId) +// if err != nil { +// return false, err +// } + +// if IsDefaultAdminUser(user.Name) || isManager { +// return true, nil +// } + +// type countStruct struct { +// Count int `json:"count"` +// } + +// query := ` +// SELECT COUNT(1) AS count +// FROM instances +// LEFT JOIN project_member_roles ON project_member_roles.instance_id = instances.id +// LEFT JOIN users ON users.id = project_member_roles.user_id +// WHERE instances.deleted_at IS NULL +// AND users.stat = 0 +// AND users.deleted_at IS NULL +// AND instances.id = ? +// AND users.id = ? +// GROUP BY instances.id +// UNION +// SELECT instances.id +// FROM instances +// LEFT JOIN project_member_group_roles ON project_member_group_roles.instance_id = instances.id +// JOIN user_group_users ON project_member_group_roles.user_group_id = user_group_users.user_group_id +// JOIN users ON users.id = user_group_users.user_id +// WHERE instances.deleted_at IS NULL +// AND users.stat = 0 +// AND users.deleted_at IS NULL +// AND instances.id = ? +// AND users.id = ? +// GROUP BY instances.id +// ` +// var cnt countStruct +// err = s.db.Unscoped().Raw(query, instance.ID, user.ID, instance.ID, user.ID).Scan(&cnt).Error +// if err != nil { +// if gorm.IsRecordNotFoundError(err) { +// return false, nil +// } +// return false, errors.New(errors.ConnectStorageError, err) +// } +// return cnt.Count > 0, nil +// } + +// func (s *Storage) GetWithOperationUserFromInstance(instance *Instance, opCode ...int) (users []*User, err error) { +// query := ` +// SELECT users.id, users.login_name +// FROM users +// LEFT JOIN project_member_roles ON users.id = project_member_roles.user_id +// LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// WHERE +// users.deleted_at IS NULL +// AND users.stat = 0 +// AND project_member_roles.instance_id = ? +// AND role_operations.op_code IN (?) + +// UNION +// SELECT users.id, users.login_name +// FROM users +// LEFT JOIN user_group_users ON users.id = user_group_users.user_id +// LEFT JOIN user_groups ON user_group_users.user_group_id = user_groups.id AND user_groups.stat = 0 +// LEFT JOIN project_member_group_roles ON user_groups.id = project_member_group_roles.user_group_id +// LEFT JOIN roles ON project_member_group_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// WHERE +// users.deleted_at IS NULL +// AND users.stat = 0 +// AND project_member_group_roles.instance_id = ? +// AND role_operations.op_code IN (?) +// ` +// err = s.db.Raw(query, instance.ID, opCode, instance.ID, opCode).Scan(&users).Error +// if err != nil { +// return nil, errors.ConnectStorageErrWrapper(err) +// } +// return +// } + +// /* + +// workflow permission. + +// */ + +// func (s *Storage) UserCanAccessWorkflow(user *User, workflow *Workflow) (bool, error) { +// query := `SELECT count(w.id) FROM workflows AS w +// JOIN workflow_records AS wr ON w.workflow_record_id = wr.id AND w.id = ? +// LEFT JOIN workflow_steps AS cur_ws ON wr.current_workflow_step_id = cur_ws.id +// LEFT JOIN workflow_step_templates AS cur_wst ON cur_ws.workflow_step_template_id = cur_wst.id +// LEFT JOIN workflow_step_user AS cur_wst_re_user ON cur_ws.id = cur_wst_re_user.workflow_step_id +// LEFT JOIN users AS cur_ass_user ON cur_wst_re_user.user_id = cur_ass_user.id AND cur_ass_user.stat=0 +// LEFT JOIN workflow_steps AS op_ws ON w.id = op_ws.workflow_id AND op_ws.state != "initialized" +// LEFT JOIN workflow_step_templates AS op_wst ON op_ws.workflow_step_template_id = op_wst.id +// LEFT JOIN workflow_step_user AS op_wst_re_user ON op_ws.id = op_wst_re_user.workflow_step_id +// LEFT JOIN users AS op_ass_user ON op_wst_re_user.user_id = op_ass_user.id AND op_ass_user.stat=0 +// where w.deleted_at IS NULL +// AND (w.create_user_id = ? OR cur_ass_user.id = ? OR op_ass_user.id = ?) +// ` +// var count uint +// err := s.db.Raw(query, workflow.ID, user.ID, user.ID, user.ID).Count(&count).Error +// if err != nil { +// return false, errors.New(errors.ConnectStorageError, err) +// } +// return count > 0, nil +// } + +// /* + +// workflow permission. TODO DMS权限接口替换掉UserCanAccessWorkflow + +// 去除了与用户表关联关系(TODO 用户不可用时需要判断) +// LEFT JOIN users AS cur_ass_user ON cur_wst_re_user.user_id = cur_ass_user.id AND cur_ass_user.stat=0 +// LEFT JOIN users AS op_ass_user ON op_wst_re_user.user_id = op_ass_user.id AND op_ass_user.stat=0 +// LEFT JOIN workflow_step_user AS cur_wst_re_user ON cur_ws.id = cur_wst_re_user.workflow_step_id +// LEFT JOIN workflow_step_user AS op_wst_re_user ON op_ws.id = op_wst_re_user.workflow_step_id +// */ + +func (s *Storage) UserCanAccessWorkflow(userId string, workflow *Workflow) (bool, error) { query := `SELECT count(w.id) FROM workflows AS w -JOIN workflow_records AS wr ON w.workflow_record_id = wr.id AND w.id = ? +JOIN workflow_records AS wr ON w.workflow_record_id = wr.id AND w.workflow_id = ? LEFT JOIN workflow_steps AS cur_ws ON wr.current_workflow_step_id = cur_ws.id LEFT JOIN workflow_step_templates AS cur_wst ON cur_ws.workflow_step_template_id = cur_wst.id -LEFT JOIN workflow_step_user AS cur_wst_re_user ON cur_ws.id = cur_wst_re_user.workflow_step_id -LEFT JOIN users AS cur_ass_user ON cur_wst_re_user.user_id = cur_ass_user.id AND cur_ass_user.stat=0 LEFT JOIN workflow_steps AS op_ws ON w.id = op_ws.workflow_id AND op_ws.state != "initialized" LEFT JOIN workflow_step_templates AS op_wst ON op_ws.workflow_step_template_id = op_wst.id -LEFT JOIN workflow_step_user AS op_wst_re_user ON op_ws.id = op_wst_re_user.workflow_step_id -LEFT JOIN users AS op_ass_user ON op_wst_re_user.user_id = op_ass_user.id AND op_ass_user.stat=0 where w.deleted_at IS NULL -AND (w.create_user_id = ? OR cur_ass_user.id = ? OR op_ass_user.id = ?) +AND (w.create_user_id = ? OR cur_ws.assignees REGEXP ? OR op_ws.assignees REGEXP ?) ` var count uint - err := s.db.Raw(query, workflow.ID, user.ID, user.ID, user.ID).Count(&count).Error + err := s.db.Raw(query, workflow.WorkflowId, userId, userId, userId).Count(&count).Error if err != nil { return false, errors.New(errors.ConnectStorageError, err) } return count > 0, nil } -// GetCanAuditWorkflowUsers will return admin user if no qualified user is found, preventing the process from being stuck because no user can operate -func (s *Storage) GetCanAuditWorkflowUsers(instance *Instance) (users []*User, err error) { - users, err = s.GetWithOperationUserFromInstance(instance, OP_WORKFLOW_AUDIT) - if err != nil { - return - } - if len(users) != 0 { - return - } - return s.GetUsersByNames([]string{DefaultAdminUser}) -} - -// GetCanExecuteWorkflowUsers will return admin user if no qualified user is found, preventing the process from being stuck because no user can operate -func (s *Storage) GetCanExecuteWorkflowUsers(instance *Instance) (users []*User, err error) { - users, err = s.GetWithOperationUserFromInstance(instance, OP_WORKFLOW_EXECUTE) - if err != nil { - return - } - if len(users) != 0 { - return - } - return s.GetUsersByNames([]string{DefaultAdminUser}) -} - -/* - -audit plan permission. - -*/ - -func (s *Storage) CheckUserCanCreateAuditPlan(user *User, projectName, instName string) (bool, error) { - if IsDefaultAdminUser(user.Name) { - return true, nil - } - - isManager, err := s.IsProjectManager(user.Name, projectName) - if err != nil { - return false, err - } - - if isManager { - return true, nil - } - - // todo: check it in db, don't get all instances. - instances, err := s.GetUserCanOpInstancesFromProject(user, projectName, []uint{OP_AUDIT_PLAN_SAVE}) - if err != nil { - return false, err - } - for _, instance := range instances { - if instName == instance.Name { - return true, nil - } - } - return false, nil -} - -/* - -project permission. - -*/ - -func (s *Storage) CheckUserCanUpdateProject(projectName string, userID uint) (bool, error) { - user, exist, err := s.GetUserByID(userID) - if err != nil || !exist { - return false, err - } - - if user.Name == DefaultAdminUser { - return true, nil - } - - project, exist, err := s.GetProjectByName(projectName) - if err != nil || !exist { - return false, err - } - - for _, manager := range project.Managers { - if manager.ID == userID { - return true, nil - } - } - return false, nil -} - -func (s *Storage) IsProjectManager(userName string, projectName string) (bool, error) { - var count uint - - err := s.db.Table("project_manager"). - Joins("LEFT JOIN projects ON projects.id = project_manager.project_id"). - Joins("LEFT JOIN users ON project_manager.user_id = users.id"). - Where("users.login_name = ?", userName). - Where("users.stat = 0"). - Where("projects.name = ?", projectName). - Where("users.deleted_at IS NULL"). - Where("projects.deleted_at IS NULL"). - Count(&count).Error - - return count > 0, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) IsProjectManagerByID(userID, projectID uint) (bool, error) { - var count uint - - err := s.db.Table("project_manager"). - Joins("LEFT JOIN projects ON projects.id = project_manager.project_id"). - Joins("LEFT JOIN users ON project_manager.user_id = users.id"). - Where("users.id = ?", userID). - Where("users.stat = 0"). - Where("project_manager.project_id = ?", projectID). - Where("users.deleted_at IS NULL"). - Where("projects.deleted_at IS NULL"). - Count(&count).Error - - return count > 0, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) IsProjectMember(userName, projectName string) (bool, error) { - query := ` -SELECT EXISTS( -SELECT users.login_name -FROM users -LEFT JOIN project_user on project_user.user_id = users.id -LEFT JOIN projects on project_user.project_id = projects.id -LEFT JOIN user_group_users on users.id = user_group_users.user_id -LEFT JOIN project_user_group on user_group_users.user_group_id = project_user_group.user_group_id -LEFT JOIN projects as p on project_user_group.project_id = p.id -WHERE users.stat = 0 -AND users.login_name = ? -AND( - projects.name = ? -OR - p.name = ? -)) AS exist -` - var exist struct { - Exist bool `json:"exist"` - } - err := s.db.Raw(query, userName, projectName, projectName).Find(&exist).Error - return exist.Exist, errors.New(errors.ConnectStorageError, err) -} +// // GetCanAuditWorkflowUsers will return admin user if no qualified user is found, preventing the process from being stuck because no user can operate +// func (s *Storage) GetCanAuditWorkflowUsers(instance *Instance) (users []*User, err error) { +// users, err = s.GetWithOperationUserFromInstance(instance, OP_WORKFLOW_AUDIT) +// if err != nil { +// return +// } +// if len(users) != 0 { +// return +// } +// return s.GetUsersByNames([]string{DefaultAdminUser}) +// } + +// // GetCanExecuteWorkflowUsers will return admin user if no qualified user is found, preventing the process from being stuck because no user can operate +// func (s *Storage) GetCanExecuteWorkflowUsers(instance *Instance) (users []*User, err error) { +// users, err = s.GetWithOperationUserFromInstance(instance, OP_WORKFLOW_EXECUTE) +// if err != nil { +// return +// } +// if len(users) != 0 { +// return +// } +// return s.GetUsersByNames([]string{DefaultAdminUser}) +// } + +// /* + +// audit plan permission. + +// */ + +// func (s *Storage) CheckUserCanCreateAuditPlan(user *User, projectName, instName string) (bool, error) { +// if IsDefaultAdminUser(user.Name) { +// return true, nil +// } + +// isManager, err := s.IsProjectManager(user.Name, projectName) +// if err != nil { +// return false, err +// } + +// if isManager { +// return true, nil +// } + +// // todo: check it in db, don't get all instances. +// instances, err := s.GetUserCanOpInstancesFromProject(user, projectName, []uint{OP_AUDIT_PLAN_SAVE}) +// if err != nil { +// return false, err +// } +// for _, instance := range instances { +// if instName == instance.Name { +// return true, nil +// } +// } +// return false, nil +// } + +// /* + +// project permission. + +// */ + +// func (s *Storage) CheckUserCanUpdateProject(projectName string, userID uint) (bool, error) { +// user, exist, err := s.GetUserByID(userID) +// if err != nil || !exist { +// return false, err +// } + +// if user.Name == DefaultAdminUser { +// return true, nil +// } + +// project, exist, err := s.GetProjectByName(projectName) +// if err != nil || !exist { +// return false, err +// } + +// for _, manager := range project.Managers { +// if manager.ID == userID { +// return true, nil +// } +// } +// return false, nil +// } + +// func (s *Storage) IsProjectManager(userName string, projectName string) (bool, error) { +// var count uint + +// err := s.db.Table("project_manager"). +// Joins("LEFT JOIN projects ON projects.id = project_manager.project_id"). +// Joins("LEFT JOIN users ON project_manager.user_id = users.id"). +// Where("users.login_name = ?", userName). +// Where("users.stat = 0"). +// Where("projects.name = ?", projectName). +// Where("users.deleted_at IS NULL"). +// Where("projects.deleted_at IS NULL"). +// Count(&count).Error + +// return count > 0, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) IsProjectManagerByID(userID, projectID uint) (bool, error) { +// var count uint + +// err := s.db.Table("project_manager"). +// Joins("LEFT JOIN projects ON projects.id = project_manager.project_id"). +// Joins("LEFT JOIN users ON project_manager.user_id = users.id"). +// Where("users.id = ?", userID). +// Where("users.stat = 0"). +// Where("project_manager.project_id = ?", projectID). +// Where("users.deleted_at IS NULL"). +// Where("projects.deleted_at IS NULL"). +// Count(&count).Error + +// return count > 0, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) IsProjectMember(userName, projectName string) (bool, error) { +// query := ` +// SELECT EXISTS( +// SELECT users.login_name +// FROM users +// LEFT JOIN project_user on project_user.user_id = users.id +// LEFT JOIN projects on project_user.project_id = projects.id +// LEFT JOIN user_group_users on users.id = user_group_users.user_id +// LEFT JOIN project_user_group on user_group_users.user_group_id = project_user_group.user_group_id +// LEFT JOIN projects as p on project_user_group.project_id = p.id +// WHERE users.stat = 0 +// AND users.login_name = ? +// AND( +// projects.name = ? +// OR +// p.name = ? +// )) AS exist +// ` +// var exist struct { +// Exist bool `json:"exist"` +// } +// err := s.db.Raw(query, userName, projectName, projectName).Find(&exist).Error +// return exist.Exist, errors.New(errors.ConnectStorageError, err) +// } diff --git a/sqle/model/project_permission_test.go b/sqle/model/project_permission_test.go index 30bd796e89..93d682ffc5 100644 --- a/sqle/model/project_permission_test.go +++ b/sqle/model/project_permission_test.go @@ -1,268 +1,268 @@ package model -import ( - "testing" +// import ( +// "testing" - sqlmock "github.com/DATA-DOG/go-sqlmock" - "github.com/stretchr/testify/assert" -) +// sqlmock "github.com/DATA-DOG/go-sqlmock" +// "github.com/stretchr/testify/assert" +// ) -func TestStorage_CheckUserHasOpToInstances(t *testing.T) { - // 1. test for common user - query := ` -SELECT -instances.id -FROM instances -LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id -LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 -LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 -LEFT JOIN role_operations ON role_operations.role_id = roles.id -WHERE -instances.deleted_at IS NULL -AND users.id = ? -AND role_operations.op_code IN (?) -AND instances.id IN (?, ?) -GROUP BY instances.id +// func TestStorage_CheckUserHasOpToInstances(t *testing.T) { +// // 1. test for common user +// query := ` +// SELECT +// instances.id +// FROM instances +// LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id +// LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND role_operations.op_code IN (?) +// AND instances.id IN (?, ?) +// GROUP BY instances.id -UNION -SELECT -instances.id -FROM instances -LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id -LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 -LEFT JOIN role_operations ON role_operations.role_id = roles.id -LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 -JOIN user_group_users ON user_groups.id = user_group_users.user_group_id -JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 -WHERE -instances.deleted_at IS NULL -AND users.id = ? -AND role_operations.op_code IN (?) -AND instances.id IN (?, ?) -GROUP BY instances.id +// UNION +// SELECT +// instances.id +// FROM instances +// LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id +// LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 +// JOIN user_group_users ON user_groups.id = user_group_users.user_group_id +// JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND role_operations.op_code IN (?) +// AND instances.id IN (?, ?) +// GROUP BY instances.id -UNION -SELECT instances.id -FROM instances -LEFT JOIN projects ON instances.project_id = projects.id -LEFT JOIN project_manager ON project_manager.project_id = projects.id -LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 -WHERE instances.deleted_at IS NULL -AND users.id = ? -AND instances.id IN (?, ?) -GROUP BY instances.id -` - mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) - assert.NoError(t, err) - InitMockStorage(mockDB) - mock.ExpectQuery(query).WithArgs(1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1).AddRow(2)) +// UNION +// SELECT instances.id +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_manager ON project_manager.project_id = projects.id +// LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// WHERE instances.deleted_at IS NULL +// AND users.id = ? +// AND instances.id IN (?, ?) +// GROUP BY instances.id +// ` +// mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) +// assert.NoError(t, err) +// InitMockStorage(mockDB) +// mock.ExpectQuery(query).WithArgs(1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2). +// WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1).AddRow(2)) - inst1 := &Instance{} - inst1.ID = 1 - inst2 := &Instance{} - inst2.ID = 2 +// inst1 := &Instance{} +// inst1.ID = 1 +// inst2 := &Instance{} +// inst2.ID = 2 - user := &User{} - user.ID = 1 - exist, err := GetStorage().CheckUserHasOpToInstances(user, []*Instance{inst1, inst2}, []uint{1}) - assert.NoError(t, err) - assert.Equal(t, true, exist) - mockDB.Close() -} +// user := &User{} +// user.ID = 1 +// exist, err := GetStorage().CheckUserHasOpToInstances(user, []*Instance{inst1, inst2}, []uint{1}) +// assert.NoError(t, err) +// assert.Equal(t, true, exist) +// mockDB.Close() +// } -func Test_GetUserCanOpInstances(t *testing.T) { - query := ` - SELECT - instances.id, instances.name - FROM instances - LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id - LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 - LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 - LEFT JOIN role_operations ON role_operations.role_id = roles.id - WHERE - instances.deleted_at IS NULL - AND users.id = ? - AND role_operations.op_code IN (?, ?, ?) - GROUP BY instances.id +// func Test_GetUserCanOpInstances(t *testing.T) { +// query := ` +// SELECT +// instances.id, instances.name +// FROM instances +// LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id +// LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND role_operations.op_code IN (?, ?, ?) +// GROUP BY instances.id - UNION - SELECT - instances.id, instances.name - FROM instances - LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id - LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 - LEFT JOIN role_operations ON role_operations.role_id = roles.id - LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 - JOIN user_group_users ON user_groups.id = user_group_users.user_group_id - JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 - WHERE - instances.deleted_at IS NULL - AND users.id = ? - AND role_operations.op_code IN (?, ?, ?) - GROUP BY instances.id +// UNION +// SELECT +// instances.id, instances.name +// FROM instances +// LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id +// LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 +// JOIN user_group_users ON user_groups.id = user_group_users.user_group_id +// JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND role_operations.op_code IN (?, ?, ?) +// GROUP BY instances.id - UNION - SELECT - instances.id, instances.name - FROM instances - LEFT JOIN projects ON instances.project_id = projects.id - LEFT JOIN project_manager ON project_manager.project_id = projects.id - LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 - WHERE - instances.deleted_at IS NULL - AND users.id = ? - GROUP BY instances.id - ` - mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) - assert.NoError(t, err) - InitMockStorage(mockDB) - mock.ExpectQuery(query).WithArgs(1, 1, 2, 3, 1, 1, 2, 3, 1). - WillReturnRows(sqlmock.NewRows([]string{"id", "name"}).AddRow(1, "inst_1").AddRow(2, "inst_2")) +// UNION +// SELECT +// instances.id, instances.name +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_manager ON project_manager.project_id = projects.id +// LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// GROUP BY instances.id +// ` +// mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) +// assert.NoError(t, err) +// InitMockStorage(mockDB) +// mock.ExpectQuery(query).WithArgs(1, 1, 2, 3, 1, 1, 2, 3, 1). +// WillReturnRows(sqlmock.NewRows([]string{"id", "name"}).AddRow(1, "inst_1").AddRow(2, "inst_2")) - user := &User{} - user.ID = 1 - instances, err := GetStorage().GetUserCanOpInstances(user, []uint{1, 2, 3}) - assert.NoError(t, err) - assert.Equal(t, 2, len(instances)) - assert.Equal(t, uint(1), instances[0].ID) - assert.Equal(t, "inst_1", instances[0].Name) - assert.Equal(t, uint(2), instances[1].ID) - assert.Equal(t, "inst_2", instances[1].Name) - mockDB.Close() -} +// user := &User{} +// user.ID = 1 +// instances, err := GetStorage().GetUserCanOpInstances(user, []uint{1, 2, 3}) +// assert.NoError(t, err) +// assert.Equal(t, 2, len(instances)) +// assert.Equal(t, uint(1), instances[0].ID) +// assert.Equal(t, "inst_1", instances[0].Name) +// assert.Equal(t, uint(2), instances[1].ID) +// assert.Equal(t, "inst_2", instances[1].Name) +// mockDB.Close() +// } -func Test_GetUserCanOpInstancesFromProject(t *testing.T) { - query := ` - SELECT - instances.id, instances.name - FROM instances - LEFT JOIN projects ON instances.project_id = projects.id - LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id - LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 - LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 - LEFT JOIN role_operations ON role_operations.role_id = roles.id - WHERE - instances.deleted_at IS NULL - AND users.id = ? - AND role_operations.op_code IN (?) - AND projects.name = ? - GROUP BY instances.id +// func Test_GetUserCanOpInstancesFromProject(t *testing.T) { +// query := ` +// SELECT +// instances.id, instances.name +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id +// LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND role_operations.op_code IN (?) +// AND projects.name = ? +// GROUP BY instances.id - UNION - SELECT - instances.id, instances.name - FROM instances - LEFT JOIN projects ON instances.project_id = projects.id - LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id - LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 - LEFT JOIN role_operations ON role_operations.role_id = roles.id - LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 - JOIN user_group_users ON user_groups.id = user_group_users.user_group_id - JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 - WHERE - instances.deleted_at IS NULL - AND users.id = ? - AND role_operations.op_code IN (?) - AND projects.name = ? - GROUP BY instances.id +// UNION +// SELECT +// instances.id, instances.name +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id +// LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 +// JOIN user_group_users ON user_groups.id = user_group_users.user_group_id +// JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND role_operations.op_code IN (?) +// AND projects.name = ? +// GROUP BY instances.id - UNION - SELECT - instances.id, instances.name - FROM instances - LEFT JOIN projects ON instances.project_id = projects.id - LEFT JOIN project_manager ON project_manager.project_id = projects.id - LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 - WHERE - instances.deleted_at IS NULL - AND users.id = ? - AND projects.name = ? - GROUP BY instances.id - ` - mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) - assert.NoError(t, err) - InitMockStorage(mockDB) - mock.ExpectQuery(query).WithArgs(1, 1, "project_1", 1, 1, "project_1", 1, "project_1"). - WillReturnRows(sqlmock.NewRows([]string{"id", "name"}).AddRow(1, "inst_1").AddRow(2, "inst_2")) +// UNION +// SELECT +// instances.id, instances.name +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_manager ON project_manager.project_id = projects.id +// LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND projects.name = ? +// GROUP BY instances.id +// ` +// mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) +// assert.NoError(t, err) +// InitMockStorage(mockDB) +// mock.ExpectQuery(query).WithArgs(1, 1, "project_1", 1, 1, "project_1", 1, "project_1"). +// WillReturnRows(sqlmock.NewRows([]string{"id", "name"}).AddRow(1, "inst_1").AddRow(2, "inst_2")) - user := &User{} - user.ID = 1 - instances, err := GetStorage().GetUserCanOpInstancesFromProject(user, "project_1", []uint{1}) - assert.NoError(t, err) - assert.Equal(t, 2, len(instances)) - assert.Equal(t, uint(1), instances[0].ID) - assert.Equal(t, "inst_1", instances[0].Name) - assert.Equal(t, uint(2), instances[1].ID) - assert.Equal(t, "inst_2", instances[1].Name) - mockDB.Close() -} +// user := &User{} +// user.ID = 1 +// instances, err := GetStorage().GetUserCanOpInstancesFromProject(user, "project_1", []uint{1}) +// assert.NoError(t, err) +// assert.Equal(t, 2, len(instances)) +// assert.Equal(t, uint(1), instances[0].ID) +// assert.Equal(t, "inst_1", instances[0].Name) +// assert.Equal(t, uint(2), instances[1].ID) +// assert.Equal(t, "inst_2", instances[1].Name) +// mockDB.Close() +// } -func Test_GetInstanceTipsByUserAndOperation(t *testing.T) { - query := ` - SELECT - instances.id, instances.name, instances.db_host as host, instances.db_port as port, instances.db_type - FROM instances - LEFT JOIN projects ON instances.project_id = projects.id - LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id - LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 - LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 - LEFT JOIN role_operations ON role_operations.role_id = roles.id - WHERE - instances.deleted_at IS NULL - AND users.id = ? - AND role_operations.op_code IN (?, ?) - AND projects.name = ? - AND instances.db_type = ? - GROUP BY instances.id +// func Test_GetInstanceTipsByUserAndOperation(t *testing.T) { +// query := ` +// SELECT +// instances.id, instances.name, instances.db_host as host, instances.db_port as port, instances.db_type +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_member_roles ON instances.id = project_member_roles.instance_id +// LEFT JOIN users ON project_member_roles.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// LEFT JOIN roles ON project_member_roles.role_id = roles.id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND role_operations.op_code IN (?, ?) +// AND projects.name = ? +// AND instances.db_type = ? +// GROUP BY instances.id - UNION - SELECT - instances.id, instances.name, instances.db_host as host, instances.db_port as port, instances.db_type - FROM instances - LEFT JOIN projects ON instances.project_id = projects.id - LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id - LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 - LEFT JOIN role_operations ON role_operations.role_id = roles.id - LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 - JOIN user_group_users ON user_groups.id = user_group_users.user_group_id - JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 - WHERE - instances.deleted_at IS NULL - AND users.id = ? - AND role_operations.op_code IN (?, ?) - AND projects.name = ? - AND instances.db_type = ? - GROUP BY instances.id +// UNION +// SELECT +// instances.id, instances.name, instances.db_host as host, instances.db_port as port, instances.db_type +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_member_group_roles ON instances.id = project_member_group_roles.instance_id +// LEFT JOIN roles ON roles.id = project_member_group_roles.role_id AND roles.deleted_at IS NULL AND roles.stat = 0 +// LEFT JOIN role_operations ON role_operations.role_id = roles.id +// LEFT JOIN user_groups ON project_member_group_roles.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL AND user_groups.stat = 0 +// JOIN user_group_users ON user_groups.id = user_group_users.user_group_id +// JOIN users ON users.id = user_group_users.user_id AND users.deleted_at IS NULL AND users.stat=0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND role_operations.op_code IN (?, ?) +// AND projects.name = ? +// AND instances.db_type = ? +// GROUP BY instances.id - UNION - SELECT - instances.id, instances.name, instances.db_host as host, instances.db_port as port, instances.db_type - FROM instances - LEFT JOIN projects ON instances.project_id = projects.id - LEFT JOIN project_manager ON project_manager.project_id = projects.id - LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 - WHERE - instances.deleted_at IS NULL - AND users.id = ? - AND projects.name = ? - AND instances.db_type = ? - GROUP BY instances.id - ` - mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) - assert.NoError(t, err) - InitMockStorage(mockDB) - mock.ExpectQuery(query).WithArgs(1, 1, 2, "project_1", "MySQL", 1, 1, 2, "project_1", "MySQL", 1, "project_1", "MySQL"). - WillReturnRows(sqlmock.NewRows([]string{"id", "name", "db_type"}).AddRow(1, "inst_1", "MySQL").AddRow(2, "inst_2", "Oracle")) +// UNION +// SELECT +// instances.id, instances.name, instances.db_host as host, instances.db_port as port, instances.db_type +// FROM instances +// LEFT JOIN projects ON instances.project_id = projects.id +// LEFT JOIN project_manager ON project_manager.project_id = projects.id +// LEFT JOIN users ON project_manager.user_id = users.id AND users.deleted_at IS NULL AND users.stat = 0 +// WHERE +// instances.deleted_at IS NULL +// AND users.id = ? +// AND projects.name = ? +// AND instances.db_type = ? +// GROUP BY instances.id +// ` +// mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) +// assert.NoError(t, err) +// InitMockStorage(mockDB) +// mock.ExpectQuery(query).WithArgs(1, 1, 2, "project_1", "MySQL", 1, 1, 2, "project_1", "MySQL", 1, "project_1", "MySQL"). +// WillReturnRows(sqlmock.NewRows([]string{"id", "name", "db_type"}).AddRow(1, "inst_1", "MySQL").AddRow(2, "inst_2", "Oracle")) - user := &User{} - user.ID = 1 - instances, err := GetStorage().getInstanceTipsByUserAndOperation(user, "MySQL", "project_1", 1, 2) - assert.NoError(t, err) - assert.Equal(t, 2, len(instances)) - assert.Equal(t, uint(1), instances[0].ID) - assert.Equal(t, "MySQL", instances[0].DbType) - assert.Equal(t, uint(2), instances[1].ID) - assert.Equal(t, "Oracle", instances[1].DbType) - mockDB.Close() -} +// user := &User{} +// user.ID = 1 +// instances, err := GetStorage().getInstanceTipsByUserAndOperation(user, "MySQL", "project_1", 1, 2) +// assert.NoError(t, err) +// assert.Equal(t, 2, len(instances)) +// assert.Equal(t, uint(1), instances[0].ID) +// assert.Equal(t, "MySQL", instances[0].DbType) +// assert.Equal(t, uint(2), instances[1].ID) +// assert.Equal(t, "Oracle", instances[1].DbType) +// mockDB.Close() +// } diff --git a/sqle/model/role.go b/sqle/model/role.go index 3bdf6a7879..e9305f31b3 100644 --- a/sqle/model/role.go +++ b/sqle/model/role.go @@ -1,451 +1,451 @@ package model -import ( - "fmt" - "strings" - - "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/utils" - - "github.com/jinzhu/gorm" -) - -// NOTE: related model: -// - RoleOperation, ProjectMemberRole, ProjectMemberGroupRole -type Role struct { - Model - Name string `gorm:"index"` - Desc string - Stat uint `json:"stat" gorm:"not null; default: 0; comment:'0:正常 1:被禁用'"` -} - -// NOTE: related model: -// - Role, User, Instance -type ProjectMemberRole struct { - Model - UserID uint `json:"user_id" gorm:"not null"` - InstanceID uint `json:"instance_id" gorm:"not null"` - RoleID uint `json:"role_id" gorm:"not null"` -} - -// NOTE: related model: -// - Role, UserGroup, Instance -type ProjectMemberGroupRole struct { - Model - UserGroupID uint `json:"user_group_id" gorm:"not null"` - InstanceID uint `json:"instance_id" gorm:"not null"` - RoleID uint `json:"role_id" gorm:"not null"` -} - -type BindRole struct { - InstanceName string `json:"instance_name" valid:"required"` - RoleNames []string `json:"role_names" valid:"required"` -} - -func (s *Storage) UpdateUserRoles(userName, projectName string, bindRoles []BindRole) error { - user, exist, err := s.GetUserByName(userName) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - if !exist { - return errors.ConnectStorageErrWrapper(fmt.Errorf("user not exist")) - } - - return s.db.Transaction(func(tx *gorm.DB) error { - return errors.ConnectStorageErrWrapper(s.updateUserRoles(tx, user, projectName, bindRoles)) - }) -} - -// 每次更新都是全量更新 InstID+UserID 定位到的角色 -func (s *Storage) updateUserRoles(tx *gorm.DB, user *User, projectName string, bindRoles []BindRole) error { - // 获取实例ID和角色ID - instNames := []string{} - roleNames := []string{} - for _, role := range bindRoles { - instNames = append(instNames, role.InstanceName) - roleNames = append(roleNames, role.RoleNames...) - } - - instCache, err := s.getInstanceBindCacheByNames(instNames, projectName) - if err != nil { - return err - } - - roleCache, err := s.getRoleBindIDByNames(roleNames) - if err != nil { - return err - } - - // 删掉所有旧数据 - err = tx.Exec(` -DELETE project_member_roles -FROM project_member_roles -LEFT JOIN project_user ON project_user.user_id = project_member_roles.user_id -LEFT JOIN projects ON projects.id = project_user.project_id -JOIN instances ON projects.id = instances.project_id AND project_member_roles.instance_id = instances.id -WHERE project_member_roles.user_id = ? -AND projects.name = ? -`, user.ID, projectName).Error - if err != nil { - return err - } - - // 写入新数据 - duplicate := map[string]struct{}{} - for _, role := range bindRoles { - for _, name := range role.RoleNames { - roleFg := fmt.Sprintf("%v-%v-%v", name, role.InstanceName, user.ID) - if _, ok := duplicate[roleFg]; ok { - continue - } - duplicate[roleFg] = struct{}{} - if err = tx.Save(&ProjectMemberRole{ - RoleID: roleCache[name], - InstanceID: instCache[role.InstanceName], - UserID: user.ID, - }).Error; err != nil { - return err - } - } - } - - return nil -} - -func (s *Storage) UpdateUserGroupRoles(groupName, projectName string, bindRoles []BindRole) error { - user, exist, err := s.GetUserGroupByName(groupName) - if err != nil { - return errors.ConnectStorageErrWrapper(err) - } - if !exist { - return errors.ConnectStorageErrWrapper(fmt.Errorf("user not exist")) - } - - return s.db.Transaction(func(tx *gorm.DB) error { - return errors.ConnectStorageErrWrapper(s.updateUserGroupRoles(tx, user, projectName, bindRoles)) - }) -} - -// 每次更新都是全量更新 InstID+UserGroupID 定位到的角色 -func (s *Storage) updateUserGroupRoles(tx *gorm.DB, group *UserGroup, projectName string, bindRoles []BindRole) error { - - // 获取实例ID和角色ID - instNames := []string{} - roleNames := []string{} - for _, role := range bindRoles { - instNames = append(instNames, role.InstanceName) - roleNames = append(roleNames, role.RoleNames...) - } - - instCache, err := s.getInstanceBindCacheByNames(instNames, projectName) - if err != nil { - return err - } - - roleCache, err := s.getRoleBindIDByNames(roleNames) - if err != nil { - return err - } - - // 删掉所有旧数据 - err = tx.Exec(` -DELETE project_member_group_roles -FROM project_member_group_roles -LEFT JOIN project_user_group ON project_user_group.user_group_id = project_member_group_roles.user_group_id -LEFT JOIN projects ON projects.id = project_user_group.project_id -JOIN instances ON projects.id = instances.project_id AND project_member_group_roles.instance_id = instances.id -WHERE project_member_group_roles.user_group_id = ? -AND projects.name = ? -`, group.ID, projectName).Error - if err != nil { - return err - } - - // 写入新数据 - duplicate := map[string]struct{}{} - for _, role := range bindRoles { - for _, name := range role.RoleNames { - roleFg := fmt.Sprintf("%v-%v-%v", name, role.InstanceName, group.ID) - if _, ok := duplicate[roleFg]; ok { - continue - } - duplicate[roleFg] = struct{}{} - if err = tx.Save(&ProjectMemberGroupRole{ - RoleID: roleCache[name], - InstanceID: instCache[role.InstanceName], - UserGroupID: group.ID, - }).Error; err != nil { - return err - } - } - } - - return nil -} - -func (s *Storage) getRoleBindIDByNames(roleNames []string) (map[string] /*role name*/ uint /*role id*/, error) { - roleNames = utils.RemoveDuplicate(roleNames) - - roles, err := s.GetRolesByNames(roleNames) - if err != nil { - return nil, err - } - - if len(roles) != len(roleNames) { - return nil, errors.NewDataNotExistErr("some roles don't exist") - } - - roleCache := map[string] /*role name*/ uint /*role id*/ {} - for _, role := range roles { - roleCache[role.Name] = role.ID - } - - return roleCache, nil -} - -func (s *Storage) GetBindRolesByMemberNames(names []string, projectName string) (map[string] /*member name*/ []BindRole, error) { - roles := []*struct { - UserName string `json:"user_name"` - InstanceName string `json:"instance_name"` - RoleName string `json:"role_name"` - }{} - - err := s.db.Table("project_member_roles"). - Select("users.login_name AS user_name , instances.name AS instance_name , roles.name AS role_name"). - Joins("LEFT JOIN users ON users.id = project_member_roles.user_id"). - Joins("LEFT JOIN instances ON instances.id = project_member_roles.instance_id"). - Joins("LEFT JOIN projects ON projects.id = instances.project_id"). - Joins("LEFT JOIN roles ON roles.id = project_member_roles.role_id"). - Where("project_member_roles.deleted_at IS NULL"). - Where("projects.deleted_at IS NULL"). - Where("users.deleted_at IS NULL"). - Where("instances.deleted_at IS NULL"). - Where("roles.deleted_at IS NULL"). - Where("projects.name = ?", projectName). - Where("users.login_name in (?)", names). - Scan(&roles).Error - - if err != nil { - return nil, errors.ConnectStorageErrWrapper(err) - } - - removeDuplicate := map[string]struct{}{} - resp := map[string][]BindRole{} - -A: - for _, role := range roles { - // 去重 - fg := role.RoleName + role.InstanceName + role.UserName - if _, ok := removeDuplicate[fg]; ok { - continue - } - removeDuplicate[fg] = struct{}{} - - // resp中已有此用户+实例的信息时走这里 - for i, bindRole := range resp[role.UserName] { - if bindRole.InstanceName == role.InstanceName { - resp[role.UserName][i].RoleNames = append(resp[role.UserName][i].RoleNames, role.RoleName) - continue A - } - } - // resp还没记录过此用户或此用户+实例的信息时走这里 - resp[role.UserName] = append(resp[role.UserName], BindRole{ - InstanceName: role.InstanceName, - RoleNames: []string{role.RoleName}, - }) - } - - return resp, nil -} - -func (s *Storage) GetBindRolesByMemberGroupNames(names []string, projectName string) (map[string] /*member group name*/ []BindRole, error) { - roles := []*struct { - GroupName string `json:"group_name"` - InstanceName string `json:"instance_name"` - RoleName string `json:"role_name"` - }{} - - err := s.db.Table("project_member_group_roles"). - Select("user_groups.name AS group_name , instances.name AS instance_name , roles.name AS role_name"). - Joins("LEFT JOIN user_groups ON user_groups.id = project_member_group_roles.user_group_id"). - Joins("LEFT JOIN instances ON instances.id = project_member_group_roles.instance_id"). - Joins("LEFT JOIN projects ON projects.id = instances.project_id"). - Joins("LEFT JOIN roles ON roles.id = project_member_group_roles.role_id"). - Where("project_member_group_roles.deleted_at IS NULL"). - Where("projects.deleted_at IS NULL"). - Where("user_groups.deleted_at IS NULL"). - Where("instances.deleted_at IS NULL"). - Where("roles.deleted_at IS NULL"). - Where("projects.name = ?", projectName). - Where("user_groups.name in (?)", names). - Scan(&roles).Error - - if err != nil { - return nil, errors.ConnectStorageErrWrapper(err) - } - - removeDuplicate := map[string]struct{}{} - resp := map[string][]BindRole{} - -A: - for _, role := range roles { - // 去重 - fg := role.RoleName + role.InstanceName + role.GroupName - if _, ok := removeDuplicate[fg]; ok { - continue - } - removeDuplicate[fg] = struct{}{} - - // resp中已有此用户组+实例的信息时走这里 - for i, bindRole := range resp[role.GroupName] { - if bindRole.InstanceName == role.InstanceName { - resp[role.GroupName][i].RoleNames = append(resp[role.GroupName][i].RoleNames, role.RoleName) - continue A - } - } - // resp还没记录过此用户或此用户+实例的信息时走这里 - resp[role.GroupName] = append(resp[role.GroupName], BindRole{ - InstanceName: role.InstanceName, - RoleNames: []string{role.RoleName}, - }) - } - - return resp, nil -} - -func (s *Storage) GetRoleByName(name string) (*Role, bool, error) { - role := &Role{} - err := s.db.Where("name = ?", name).Find(role).Error - if err == gorm.ErrRecordNotFound { - return role, false, nil - } - return role, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetRolesByNames(names []string) ([]*Role, error) { - roles := []*Role{} - err := s.db.Where("name in (?)", names).Find(&roles).Error - return roles, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) UpdateRoleUsers(role *Role, users ...*User) error { - err := s.db.Model(role).Association("Users").Replace(users).Error - return errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) UpdateRoleInstances(role *Role, instances ...*Instance) error { - err := s.db.Model(role).Association("Instances").Replace(instances).Error - return errors.New(errors.ConnectStorageError, err) -} - -var roleTipsQueryTpl = `SELECT roles.name, -GROUP_CONCAT(DISTINCT COALESCE(role_operations.op_code,'')) AS operations_codes -{{ template "body" . }} -GROUP BY roles.id -` - -var roleTipsQueryBodyTpl = ` -{{ define "body" }} -FROM roles -LEFT JOIN role_operations ON role_operations.role_id = roles.id AND role_operations.deleted_at IS NULL -WHERE -roles.deleted_at IS NULL - -{{- end }} -` - -type RoleTips struct { - Name string `json:"name"` - OperationsCodes RowList `json:"operations_codes"` -} - -func (s *Storage) GetAllRoleTip() ([]*RoleTips, error) { - result := []*RoleTips{} - err := s.getListResult(roleTipsQueryBodyTpl, roleTipsQueryTpl, nil, &result) - if err != nil { - return nil, err - } - return result, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetAndCheckRoleExist(roleNames []string) (roles []*Role, err error) { - roles, err = s.GetRolesByNames(roleNames) - if err != nil { - return roles, err - } - existRoleNames := map[string]struct{}{} - for _, role := range roles { - existRoleNames[role.Name] = struct{}{} - } - notExistRoleNames := []string{} - for _, roleName := range roleNames { - if _, ok := existRoleNames[roleName]; !ok { - notExistRoleNames = append(notExistRoleNames, roleName) - } - } - if len(notExistRoleNames) > 0 { - return roles, errors.New(errors.DataNotExist, - fmt.Errorf("user role %s not exist", strings.Join(notExistRoleNames, ", "))) - } - return roles, nil -} - -func (s *Storage) SaveRoleAndAssociations(role *Role, - opCodes []uint) (err error) { - return s.Tx(func(txDB *gorm.DB) (err error) { - - // save role - if err = txDB.Save(role).Error; err != nil { - return errors.ConnectStorageErrWrapper(err) - } - - // sync operations - { - if opCodes != nil { - if err := s.ReplaceRoleOperationsByOpCodes(role.ID, opCodes); err != nil { - return err - } - } - } - - return - }) -} - -func (s *Storage) DeleteRoleAndAssociations(role *Role) error { - return s.Tx(func(txDB *gorm.DB) (err error) { - - // delete role - if err = txDB.Delete(role).Error; err != nil { - txDB.Rollback() - return errors.ConnectStorageErrWrapper(err) - } - - // delete role operations - if err = s.DeleteRoleOperationByRoleID(role.ID); err != nil { - txDB.Rollback() - return err - } - - return nil - }) -} - -func (s *Storage) CheckRolesExist(roleNames []string) (bool, error) { - roleNames = utils.RemoveDuplicate(roleNames) - - var count int - err := s.db.Model(&Role{}).Where("name in (?)", roleNames).Count(&count).Error - return len(roleNames) == count, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) DeleteRoleByInstanceID(instanceID uint) error { - sql := ` -DELETE project_member_roles, project_member_group_roles -FROM project_member_roles -LEFT JOIN project_member_group_roles ON project_member_roles.instance_id = project_member_group_roles.instance_id -WHERE project_member_roles.instance_id = ? -` - - return errors.ConnectStorageErrWrapper(s.db.Exec(sql, instanceID).Error) -} +// import ( +// "fmt" +// "strings" + +// "github.com/actiontech/sqle/sqle/errors" +// "github.com/actiontech/sqle/sqle/utils" + +// "github.com/jinzhu/gorm" +// ) + +// // NOTE: related model: +// // - RoleOperation, ProjectMemberRole, ProjectMemberGroupRole +// type Role struct { +// Model +// Name string `gorm:"index"` +// Desc string +// Stat uint `json:"stat" gorm:"not null; default: 0; comment:'0:正常 1:被禁用'"` +// } + +// // NOTE: related model: +// // - Role, User, Instance +// type ProjectMemberRole struct { +// Model +// UserID uint `json:"user_id" gorm:"not null"` +// InstanceID uint `json:"instance_id" gorm:"not null"` +// RoleID uint `json:"role_id" gorm:"not null"` +// } + +// // NOTE: related model: +// // - Role, UserGroup, Instance +// type ProjectMemberGroupRole struct { +// Model +// UserGroupID uint `json:"user_group_id" gorm:"not null"` +// InstanceID uint `json:"instance_id" gorm:"not null"` +// RoleID uint `json:"role_id" gorm:"not null"` +// } + +// type BindRole struct { +// InstanceName string `json:"instance_name" valid:"required"` +// RoleNames []string `json:"role_names" valid:"required"` +// } + +// func (s *Storage) UpdateUserRoles(userName, projectName string, bindRoles []BindRole) error { +// user, exist, err := s.GetUserByName(userName) +// if err != nil { +// return errors.ConnectStorageErrWrapper(err) +// } +// if !exist { +// return errors.ConnectStorageErrWrapper(fmt.Errorf("user not exist")) +// } + +// return s.db.Transaction(func(tx *gorm.DB) error { +// return errors.ConnectStorageErrWrapper(s.updateUserRoles(tx, user, projectName, bindRoles)) +// }) +// } + +// // 每次更新都是全量更新 InstID+UserID 定位到的角色 +// func (s *Storage) updateUserRoles(tx *gorm.DB, user *User, projectName string, bindRoles []BindRole) error { +// // 获取实例ID和角色ID +// instNames := []string{} +// roleNames := []string{} +// for _, role := range bindRoles { +// instNames = append(instNames, role.InstanceName) +// roleNames = append(roleNames, role.RoleNames...) +// } + +// instCache, err := s.getInstanceBindCacheByNames(instNames, projectName) +// if err != nil { +// return err +// } + +// roleCache, err := s.getRoleBindIDByNames(roleNames) +// if err != nil { +// return err +// } + +// // 删掉所有旧数据 +// err = tx.Exec(` +// DELETE project_member_roles +// FROM project_member_roles +// LEFT JOIN project_user ON project_user.user_id = project_member_roles.user_id +// LEFT JOIN projects ON projects.id = project_user.project_id +// JOIN instances ON projects.id = instances.project_id AND project_member_roles.instance_id = instances.id +// WHERE project_member_roles.user_id = ? +// AND projects.name = ? +// `, user.ID, projectName).Error +// if err != nil { +// return err +// } + +// // 写入新数据 +// duplicate := map[string]struct{}{} +// for _, role := range bindRoles { +// for _, name := range role.RoleNames { +// roleFg := fmt.Sprintf("%v-%v-%v", name, role.InstanceName, user.ID) +// if _, ok := duplicate[roleFg]; ok { +// continue +// } +// duplicate[roleFg] = struct{}{} +// if err = tx.Save(&ProjectMemberRole{ +// RoleID: roleCache[name], +// InstanceID: instCache[role.InstanceName], +// UserID: user.ID, +// }).Error; err != nil { +// return err +// } +// } +// } + +// return nil +// } + +// func (s *Storage) UpdateUserGroupRoles(groupName, projectName string, bindRoles []BindRole) error { +// user, exist, err := s.GetUserGroupByName(groupName) +// if err != nil { +// return errors.ConnectStorageErrWrapper(err) +// } +// if !exist { +// return errors.ConnectStorageErrWrapper(fmt.Errorf("user not exist")) +// } + +// return s.db.Transaction(func(tx *gorm.DB) error { +// return errors.ConnectStorageErrWrapper(s.updateUserGroupRoles(tx, user, projectName, bindRoles)) +// }) +// } + +// // 每次更新都是全量更新 InstID+UserGroupID 定位到的角色 +// func (s *Storage) updateUserGroupRoles(tx *gorm.DB, group *UserGroup, projectName string, bindRoles []BindRole) error { + +// // 获取实例ID和角色ID +// instNames := []string{} +// roleNames := []string{} +// for _, role := range bindRoles { +// instNames = append(instNames, role.InstanceName) +// roleNames = append(roleNames, role.RoleNames...) +// } + +// instCache, err := s.getInstanceBindCacheByNames(instNames, projectName) +// if err != nil { +// return err +// } + +// roleCache, err := s.getRoleBindIDByNames(roleNames) +// if err != nil { +// return err +// } + +// // 删掉所有旧数据 +// err = tx.Exec(` +// DELETE project_member_group_roles +// FROM project_member_group_roles +// LEFT JOIN project_user_group ON project_user_group.user_group_id = project_member_group_roles.user_group_id +// LEFT JOIN projects ON projects.id = project_user_group.project_id +// JOIN instances ON projects.id = instances.project_id AND project_member_group_roles.instance_id = instances.id +// WHERE project_member_group_roles.user_group_id = ? +// AND projects.name = ? +// `, group.ID, projectName).Error +// if err != nil { +// return err +// } + +// // 写入新数据 +// duplicate := map[string]struct{}{} +// for _, role := range bindRoles { +// for _, name := range role.RoleNames { +// roleFg := fmt.Sprintf("%v-%v-%v", name, role.InstanceName, group.ID) +// if _, ok := duplicate[roleFg]; ok { +// continue +// } +// duplicate[roleFg] = struct{}{} +// if err = tx.Save(&ProjectMemberGroupRole{ +// RoleID: roleCache[name], +// InstanceID: instCache[role.InstanceName], +// UserGroupID: group.ID, +// }).Error; err != nil { +// return err +// } +// } +// } + +// return nil +// } + +// func (s *Storage) getRoleBindIDByNames(roleNames []string) (map[string] /*role name*/ uint /*role id*/, error) { +// roleNames = utils.RemoveDuplicate(roleNames) + +// roles, err := s.GetRolesByNames(roleNames) +// if err != nil { +// return nil, err +// } + +// if len(roles) != len(roleNames) { +// return nil, errors.NewDataNotExistErr("some roles don't exist") +// } + +// roleCache := map[string] /*role name*/ uint /*role id*/ {} +// for _, role := range roles { +// roleCache[role.Name] = role.ID +// } + +// return roleCache, nil +// } + +// func (s *Storage) GetBindRolesByMemberNames(names []string, projectName string) (map[string] /*member name*/ []BindRole, error) { +// roles := []*struct { +// UserName string `json:"user_name"` +// InstanceName string `json:"instance_name"` +// RoleName string `json:"role_name"` +// }{} + +// err := s.db.Table("project_member_roles"). +// Select("users.login_name AS user_name , instances.name AS instance_name , roles.name AS role_name"). +// Joins("LEFT JOIN users ON users.id = project_member_roles.user_id"). +// Joins("LEFT JOIN instances ON instances.id = project_member_roles.instance_id"). +// Joins("LEFT JOIN projects ON projects.id = instances.project_id"). +// Joins("LEFT JOIN roles ON roles.id = project_member_roles.role_id"). +// Where("project_member_roles.deleted_at IS NULL"). +// Where("projects.deleted_at IS NULL"). +// Where("users.deleted_at IS NULL"). +// Where("instances.deleted_at IS NULL"). +// Where("roles.deleted_at IS NULL"). +// Where("projects.name = ?", projectName). +// Where("users.login_name in (?)", names). +// Scan(&roles).Error + +// if err != nil { +// return nil, errors.ConnectStorageErrWrapper(err) +// } + +// removeDuplicate := map[string]struct{}{} +// resp := map[string][]BindRole{} + +// A: +// for _, role := range roles { +// // 去重 +// fg := role.RoleName + role.InstanceName + role.UserName +// if _, ok := removeDuplicate[fg]; ok { +// continue +// } +// removeDuplicate[fg] = struct{}{} + +// // resp中已有此用户+实例的信息时走这里 +// for i, bindRole := range resp[role.UserName] { +// if bindRole.InstanceName == role.InstanceName { +// resp[role.UserName][i].RoleNames = append(resp[role.UserName][i].RoleNames, role.RoleName) +// continue A +// } +// } +// // resp还没记录过此用户或此用户+实例的信息时走这里 +// resp[role.UserName] = append(resp[role.UserName], BindRole{ +// InstanceName: role.InstanceName, +// RoleNames: []string{role.RoleName}, +// }) +// } + +// return resp, nil +// } + +// func (s *Storage) GetBindRolesByMemberGroupNames(names []string, projectName string) (map[string] /*member group name*/ []BindRole, error) { +// roles := []*struct { +// GroupName string `json:"group_name"` +// InstanceName string `json:"instance_name"` +// RoleName string `json:"role_name"` +// }{} + +// err := s.db.Table("project_member_group_roles"). +// Select("user_groups.name AS group_name , instances.name AS instance_name , roles.name AS role_name"). +// Joins("LEFT JOIN user_groups ON user_groups.id = project_member_group_roles.user_group_id"). +// Joins("LEFT JOIN instances ON instances.id = project_member_group_roles.instance_id"). +// Joins("LEFT JOIN projects ON projects.id = instances.project_id"). +// Joins("LEFT JOIN roles ON roles.id = project_member_group_roles.role_id"). +// Where("project_member_group_roles.deleted_at IS NULL"). +// Where("projects.deleted_at IS NULL"). +// Where("user_groups.deleted_at IS NULL"). +// Where("instances.deleted_at IS NULL"). +// Where("roles.deleted_at IS NULL"). +// Where("projects.name = ?", projectName). +// Where("user_groups.name in (?)", names). +// Scan(&roles).Error + +// if err != nil { +// return nil, errors.ConnectStorageErrWrapper(err) +// } + +// removeDuplicate := map[string]struct{}{} +// resp := map[string][]BindRole{} + +// A: +// for _, role := range roles { +// // 去重 +// fg := role.RoleName + role.InstanceName + role.GroupName +// if _, ok := removeDuplicate[fg]; ok { +// continue +// } +// removeDuplicate[fg] = struct{}{} + +// // resp中已有此用户组+实例的信息时走这里 +// for i, bindRole := range resp[role.GroupName] { +// if bindRole.InstanceName == role.InstanceName { +// resp[role.GroupName][i].RoleNames = append(resp[role.GroupName][i].RoleNames, role.RoleName) +// continue A +// } +// } +// // resp还没记录过此用户或此用户+实例的信息时走这里 +// resp[role.GroupName] = append(resp[role.GroupName], BindRole{ +// InstanceName: role.InstanceName, +// RoleNames: []string{role.RoleName}, +// }) +// } + +// return resp, nil +// } + +// func (s *Storage) GetRoleByName(name string) (*Role, bool, error) { +// role := &Role{} +// err := s.db.Where("name = ?", name).Find(role).Error +// if err == gorm.ErrRecordNotFound { +// return role, false, nil +// } +// return role, true, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetRolesByNames(names []string) ([]*Role, error) { +// roles := []*Role{} +// err := s.db.Where("name in (?)", names).Find(&roles).Error +// return roles, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) UpdateRoleUsers(role *Role, users ...*User) error { +// err := s.db.Model(role).Association("Users").Replace(users).Error +// return errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) UpdateRoleInstances(role *Role, instances ...*Instance) error { +// err := s.db.Model(role).Association("Instances").Replace(instances).Error +// return errors.New(errors.ConnectStorageError, err) +// } + +// var roleTipsQueryTpl = `SELECT roles.name, +// GROUP_CONCAT(DISTINCT COALESCE(role_operations.op_code,'')) AS operations_codes +// {{ template "body" . }} +// GROUP BY roles.id +// ` + +// var roleTipsQueryBodyTpl = ` +// {{ define "body" }} +// FROM roles +// LEFT JOIN role_operations ON role_operations.role_id = roles.id AND role_operations.deleted_at IS NULL +// WHERE +// roles.deleted_at IS NULL + +// {{- end }} +// ` + +// type RoleTips struct { +// Name string `json:"name"` +// OperationsCodes RowList `json:"operations_codes"` +// } + +// func (s *Storage) GetAllRoleTip() ([]*RoleTips, error) { +// result := []*RoleTips{} +// err := s.getListResult(roleTipsQueryBodyTpl, roleTipsQueryTpl, nil, &result) +// if err != nil { +// return nil, err +// } +// return result, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetAndCheckRoleExist(roleNames []string) (roles []*Role, err error) { +// roles, err = s.GetRolesByNames(roleNames) +// if err != nil { +// return roles, err +// } +// existRoleNames := map[string]struct{}{} +// for _, role := range roles { +// existRoleNames[role.Name] = struct{}{} +// } +// notExistRoleNames := []string{} +// for _, roleName := range roleNames { +// if _, ok := existRoleNames[roleName]; !ok { +// notExistRoleNames = append(notExistRoleNames, roleName) +// } +// } +// if len(notExistRoleNames) > 0 { +// return roles, errors.New(errors.DataNotExist, +// fmt.Errorf("user role %s not exist", strings.Join(notExistRoleNames, ", "))) +// } +// return roles, nil +// } + +// func (s *Storage) SaveRoleAndAssociations(role *Role, +// opCodes []uint) (err error) { +// return s.Tx(func(txDB *gorm.DB) (err error) { + +// // save role +// if err = txDB.Save(role).Error; err != nil { +// return errors.ConnectStorageErrWrapper(err) +// } + +// // sync operations +// { +// if opCodes != nil { +// if err := s.ReplaceRoleOperationsByOpCodes(role.ID, opCodes); err != nil { +// return err +// } +// } +// } + +// return +// }) +// } + +// func (s *Storage) DeleteRoleAndAssociations(role *Role) error { +// return s.Tx(func(txDB *gorm.DB) (err error) { + +// // delete role +// if err = txDB.Delete(role).Error; err != nil { +// txDB.Rollback() +// return errors.ConnectStorageErrWrapper(err) +// } + +// // delete role operations +// if err = s.DeleteRoleOperationByRoleID(role.ID); err != nil { +// txDB.Rollback() +// return err +// } + +// return nil +// }) +// } + +// func (s *Storage) CheckRolesExist(roleNames []string) (bool, error) { +// roleNames = utils.RemoveDuplicate(roleNames) + +// var count int +// err := s.db.Model(&Role{}).Where("name in (?)", roleNames).Count(&count).Error +// return len(roleNames) == count, errors.ConnectStorageErrWrapper(err) +// } + +// func (s *Storage) DeleteRoleByInstanceID(instanceID uint) error { +// sql := ` +// DELETE project_member_roles, project_member_group_roles +// FROM project_member_roles +// LEFT JOIN project_member_group_roles ON project_member_roles.instance_id = project_member_group_roles.instance_id +// WHERE project_member_roles.instance_id = ? +// ` + +// return errors.ConnectStorageErrWrapper(s.db.Exec(sql, instanceID).Error) +// } diff --git a/sqle/model/role_list.go b/sqle/model/role_list.go index c7adde0cc9..8cab2f5b9f 100644 --- a/sqle/model/role_list.go +++ b/sqle/model/role_list.go @@ -5,69 +5,69 @@ import ( "text/template" ) -type RoleDetail struct { - Id int - Name string `json:"name"` - Desc string `json:"desc"` - UserNames RowList `json:"user_names"` - InstanceNames RowList `json:"instance_names"` - - // New fields: Stat, UserGroupNames, OperationsCodes - // Issue: https://github.com/actiontech/sqle/issues/228 - // Version: >= sqle-v1.2202.0 - Stat int `json:"stat"` - UserGroupNames RowList `json:"user_group_names"` - OperationsCodes RowList `json:"operations_codes"` -} - -func (rd *RoleDetail) IsDisabled() bool { - return rd.Stat == Disabled -} - -var rolesQueryTpl = `SELECT roles.id, roles.name, roles.desc, roles.stat, -GROUP_CONCAT(DISTINCT COALESCE(role_operations.op_code,'')) AS operations_codes -FROM roles -LEFT JOIN role_operations ON role_operations.role_id = roles.id AND role_operations.deleted_at IS NULL -WHERE -roles.id in (SELECT DISTINCT(roles.id) - -{{- template "body" . -}} -) -GROUP BY roles.id -{{- if .limit }} -LIMIT :limit OFFSET :offset -{{- end -}} -` - -var rolesCountTpl = `SELECT COUNT(DISTINCT roles.id) - -{{- template "body" . -}} -` - -var rolesQueryBodyTpl = ` -{{ define "body" }} -FROM roles -LEFT JOIN role_operations ON role_operations.role_id = roles.id AND role_operations.deleted_at IS NULL -WHERE -roles.deleted_at IS NULL - -{{- if .filter_role_name }} -AND roles.name = :filter_role_name -{{- end }} - -{{- end }} -` - -func (s *Storage) GetRolesByReq(data map[string]interface{}) ( - result []*RoleDetail, count uint64, err error) { - - err = s.getListResult(rolesQueryBodyTpl, rolesQueryTpl, data, &result) - if err != nil { - return result, 0, err - } - count, err = s.getCountResult(rolesQueryBodyTpl, rolesCountTpl, data) - return result, count, err -} +// type RoleDetail struct { +// Id int +// Name string `json:"name"` +// Desc string `json:"desc"` +// UserNames RowList `json:"user_names"` +// InstanceNames RowList `json:"instance_names"` + +// // New fields: Stat, UserGroupNames, OperationsCodes +// // Issue: https://github.com/actiontech/sqle/issues/228 +// // Version: >= sqle-v1.2202.0 +// Stat int `json:"stat"` +// UserGroupNames RowList `json:"user_group_names"` +// OperationsCodes RowList `json:"operations_codes"` +// } + +// func (rd *RoleDetail) IsDisabled() bool { +// return rd.Stat == Disabled +// } + +// var rolesQueryTpl = `SELECT roles.id, roles.name, roles.desc, roles.stat, +// GROUP_CONCAT(DISTINCT COALESCE(role_operations.op_code,'')) AS operations_codes +// FROM roles +// LEFT JOIN role_operations ON role_operations.role_id = roles.id AND role_operations.deleted_at IS NULL +// WHERE +// roles.id in (SELECT DISTINCT(roles.id) + +// {{- template "body" . -}} +// ) +// GROUP BY roles.id +// {{- if .limit }} +// LIMIT :limit OFFSET :offset +// {{- end -}} +// ` + +// var rolesCountTpl = `SELECT COUNT(DISTINCT roles.id) + +// {{- template "body" . -}} +// ` + +// var rolesQueryBodyTpl = ` +// {{ define "body" }} +// FROM roles +// LEFT JOIN role_operations ON role_operations.role_id = roles.id AND role_operations.deleted_at IS NULL +// WHERE +// roles.deleted_at IS NULL + +// {{- if .filter_role_name }} +// AND roles.name = :filter_role_name +// {{- end }} + +// {{- end }} +// ` + +// func (s *Storage) GetRolesByReq(data map[string]interface{}) ( +// result []*RoleDetail, count uint64, err error) { + +// err = s.getListResult(rolesQueryBodyTpl, rolesQueryTpl, data, &result) +// if err != nil { +// return result, 0, err +// } +// count, err = s.getCountResult(rolesQueryBodyTpl, rolesCountTpl, data) +// return result, count, err +// } func getSelectQuery(bodyTpl, queryTpl string, data interface{}) (string, error) { var buff bytes.Buffer @@ -140,13 +140,13 @@ func (s *Storage) getCountResult(bodyTpl, countTpl string, data map[string]inter return count, nil } -func GetRoleIDsFromRoles(roles []*Role) (roleIDs []uint) { +// func GetRoleIDsFromRoles(roles []*Role) (roleIDs []uint) { - roleIDs = make([]uint, len(roles)) +// roleIDs = make([]uint, len(roles)) - for i := range roles { - roleIDs[i] = roles[i].ID - } +// for i := range roles { +// roleIDs[i] = roles[i].ID +// } - return roleIDs -} +// return roleIDs +// } diff --git a/sqle/model/rule.go b/sqle/model/rule.go index f88adfc371..50c0442aa6 100644 --- a/sqle/model/rule.go +++ b/sqle/model/rule.go @@ -13,11 +13,10 @@ import ( type RuleTemplate struct { Model // global rule-template has no ProjectId - ProjectId uint `gorm:"index"` + ProjectId ProjectUID `gorm:"index"` Name string `json:"name"` Desc string `json:"desc"` DBType string `json:"db_type"` - Instances []Instance `json:"instance_list" gorm:"many2many:instance_rule_template"` RuleList []RuleTemplateRule `json:"rule_list" gorm:"foreignkey:rule_template_id;association_foreignkey:id"` CustomRuleList []RuleTemplateCustomRule `json:"custom_rule_list" gorm:"foreignkey:rule_template_id;association_foreignkey:id"` } @@ -147,13 +146,11 @@ func (s *Storage) GetRuleTemplatesByInstance(inst *Instance) ([]RuleTemplate, er return associationRT, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetRuleTemplateNamesByProjectName(projectName string) ([]string, error) { +func (s *Storage) GetRuleTemplateNamesByProjectId(projectId string) ([]string, error) { records := []*RuleTemplate{} err := s.db.Model(&RuleTemplate{}). - Select("rule_templates.name"). - Joins("LEFT JOIN projects ON projects.id = rule_templates.project_id"). - Where("projects.deleted_at is null"). - Where("projects.name = ?", projectName). + Select("name"). + Where("project_id = ?", projectId). Find(&records). Error if err != nil { @@ -167,7 +164,7 @@ func (s *Storage) GetRuleTemplateNamesByProjectName(projectName string) ([]strin return templateNames, nil } -func (s *Storage) GetRuleTemplatesByInstanceNameAndProjectId(name string, projectId uint) (*RuleTemplate, bool, error) { +func (s *Storage) GetRuleTemplatesByInstanceNameAndProjectId(name string, projectId string) (*RuleTemplate, bool, error) { t := &RuleTemplate{} err := s.db.Joins("JOIN `instance_rule_template` ON `rule_templates`.`id` = `instance_rule_template`.`rule_template_id`"). Joins("JOIN `instances` ON `instance_rule_template`.`instance_id` = `instances`.`id`"). @@ -179,8 +176,8 @@ func (s *Storage) GetRuleTemplatesByInstanceNameAndProjectId(name string, projec return t, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetRulesFromRuleTemplateByName(projectIds []uint, name string) ([]*Rule, []*CustomRule, error) { - tpl, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds(projectIds, name) +func (s *Storage) GetRulesFromRuleTemplateByName(projectIds []string, name string) ([]*Rule, []*CustomRule, error) { + tpl, exist, err := s.GetRuleTemplateDetailByNameAndProjectIds(projectIds, name, "") if !exist { return nil, nil, errors.New(errors.DataNotExist, err) } @@ -199,21 +196,22 @@ func (s *Storage) GetRulesFromRuleTemplateByName(projectIds []uint, name string) return rules, customRules, nil } -func (s *Storage) GetAllRulesByInstanceId(instanceId string) ([]*Rule, []*CustomRule, error) { - instance, _, err := s.GetInstanceById(instanceId) - if err != nil { - return nil, nil, errors.New(errors.ConnectStorageError, err) - } - templates := instance.RuleTemplates - if len(templates) <= 0 { - return nil, nil, nil +func (s *Storage) GetAllRulesByInstance(instance *Instance) ([]*Rule, []*CustomRule, error) { + var template RuleTemplate + + if err := s.db.Where("id = ? ", instance.RuleTemplateId).First(&template).Error; err != nil { + if err != gorm.ErrRecordNotFound { + return nil, nil, errors.New(errors.ConnectStorageError, err) + } else { + return nil, nil, nil + } } - tplName := templates[0].Name + // 数据源可以绑定全局模板和项目模板 - return s.GetRulesFromRuleTemplateByName([]uint{instance.ProjectId, ProjectIdForGlobalRuleTemplate}, tplName) + return s.GetRulesFromRuleTemplateByName([]string{instance.ProjectId, ProjectIdForGlobalRuleTemplate}, instance.RuleTemplateName) } -func (s *Storage) GetRuleTemplateByProjectIdAndName(projectId uint, name string) (*RuleTemplate, bool, error) { +func (s *Storage) GetRuleTemplateByProjectIdAndName(projectId, name string) (*RuleTemplate, bool, error) { t := &RuleTemplate{} err := s.db.Where("name = ?", name).Where("project_id = ?", projectId).First(t).Error if err == gorm.ErrRecordNotFound { @@ -222,7 +220,7 @@ func (s *Storage) GetRuleTemplateByProjectIdAndName(projectId uint, name string) return t, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetGlobalAndProjectRuleTemplateByNameAndProjectId(name string, projectId uint) (*RuleTemplate, bool, error) { +func (s *Storage) GetGlobalAndProjectRuleTemplateByNameAndProjectId(name string, projectId string) (*RuleTemplate, bool, error) { t := &RuleTemplate{} err := s.db.Table("rule_templates"). Where("rule_templates.name = ?", name). @@ -234,18 +232,24 @@ func (s *Storage) GetGlobalAndProjectRuleTemplateByNameAndProjectId(name string, return t, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) IsRuleTemplateExistFromAnyProject(name string) (bool, error) { +func (s *Storage) IsRuleTemplateExistFromAnyProject(projectId ProjectUID, name string) (bool, error) { var count int - err := s.db.Model(&RuleTemplate{}).Where("name = ?", name).Count(&count).Error + err := s.db.Model(&RuleTemplate{}).Where("name = ? and project_id = ?", name, string(projectId)).Count(&count).Error return count > 0, errors.ConnectStorageErrWrapper(err) } -func (s *Storage) GetRuleTemplateDetailByNameAndProjectIds(projectIds []uint, name string) (*RuleTemplate, bool, error) { +func (s *Storage) GetRuleTemplateDetailByNameAndProjectIds(projectIds []string, name string, fuzzy_keyword_rule string) (*RuleTemplate, bool, error) { dbOrder := func(db *gorm.DB) *gorm.DB { return db.Order("rule_template_rule.rule_name ASC") } + fuzzy_condition := func(db *gorm.DB) *gorm.DB { + if fuzzy_keyword_rule == "" { + return db + } + return db.Where("`desc` like ? OR annotation like ?", fmt.Sprintf("%%%s%%", fuzzy_keyword_rule), fmt.Sprintf("%%%s%%", fuzzy_keyword_rule)) + } t := &RuleTemplate{Name: name} - err := s.db.Preload("RuleList", dbOrder).Preload("RuleList.Rule").Preload("Instances").Preload("CustomRuleList.CustomRule"). + err := s.db.Preload("RuleList", dbOrder).Preload("RuleList.Rule", fuzzy_condition).Preload("CustomRuleList.CustomRule", fuzzy_condition). Where(t). Where("project_id IN (?)", projectIds). First(t).Error @@ -276,11 +280,6 @@ func (s *Storage) UpdateRuleTemplateRules(tpl *RuleTemplate, rules ...RuleTempla return errors.New(errors.ConnectStorageError, err) } -func (s *Storage) UpdateRuleTemplateInstances(tpl *RuleTemplate, instances ...*Instance) error { - err := s.db.Model(tpl).Association("Instances").Replace(instances).Error - return errors.New(errors.ConnectStorageError, err) -} - func (s *Storage) CloneRuleTemplateRules(source, destination *RuleTemplate) error { return s.UpdateRuleTemplateRules(destination, source.RuleList...) } @@ -299,10 +298,17 @@ func GetRuleMapFromAllArray(allRules ...[]Rule) map[string]Rule { return ruleMap } -func (s *Storage) GetRuleTemplateTips(projectId uint, dbType string) ([]*RuleTemplate, error) { +func (s *Storage) GetRuleTemplateById(id uint64) (*RuleTemplate, error) { + ruleTemplate := new(RuleTemplate) + + err := s.db.Where("id = ?", id).First(ruleTemplate).Error + return ruleTemplate, errors.New(errors.ConnectStorageError, err) +} + +func (s *Storage) GetRuleTemplateTips(projectId, dbType string) ([]*RuleTemplate, error) { ruleTemplates := []*RuleTemplate{} - db := s.db.Select("name, db_type").Where("project_id = ?", projectId) + db := s.db.Select("id,name, db_type").Where("project_id = ?", projectId) if dbType != "" { db = db.Where("db_type = ?", dbType) } @@ -365,7 +371,7 @@ func (s *Storage) GetAndCheckRuleExist(ruleNames []string, dbType string) (map[s return existRules, nil } -func (s *Storage) IsRuleTemplateExist(ruleTemplateName string, projectIds []uint) (bool, error) { +func (s *Storage) IsRuleTemplateExist(ruleTemplateName string, projectIds []string) (bool, error) { if len(projectIds) <= 0 { return false, nil } @@ -400,7 +406,7 @@ func (s *Storage) GetAuditPlanNamesByRuleTemplate( } func (s *Storage) GetAuditPlanNamesByRuleTemplateAndProject( - ruleTemplateName string, projectID uint) (auditPlanNames []string, err error) { + ruleTemplateName string, projectID string) (auditPlanNames []string, err error) { var auditPlans []*AuditPlan @@ -576,21 +582,21 @@ func (s *Storage) UpdateRuleTemplateCustomRules(tpl *RuleTemplate, rules ...Rule return errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetAllRulesByTmpNameAndProjectIdInstanceDBType(ruleTemplateName string, projectId *uint, +func (s *Storage) GetAllRulesByTmpNameAndProjectIdInstanceDBType(ruleTemplateName string, projectId string, inst *Instance, dbType string) (rules []*Rule, customRules []*CustomRule, err error) { if ruleTemplateName != "" { - if projectId == nil { + if projectId == "" { return nil, nil, errors.New(errors.DataInvalid, fmt.Errorf("project id is needed when rule template name is given")) } - rules, customRules, err = s.GetRulesFromRuleTemplateByName([]uint{*projectId, ProjectIdForGlobalRuleTemplate}, ruleTemplateName) + rules, customRules, err = s.GetRulesFromRuleTemplateByName([]string{projectId, ProjectIdForGlobalRuleTemplate}, ruleTemplateName) } else { if inst != nil { - rules, customRules, err = s.GetAllRulesByInstanceId(fmt.Sprintf("%v", inst.ID)) + rules, customRules, err = s.GetAllRulesByInstance(inst) } else { templateName := s.GetDefaultRuleTemplateName(dbType) // 默认规则模板从全局模板里拿 - rules, customRules, err = s.GetRulesFromRuleTemplateByName([]uint{ProjectIdForGlobalRuleTemplate}, templateName) + rules, customRules, err = s.GetRulesFromRuleTemplateByName([]string{ProjectIdForGlobalRuleTemplate}, templateName) } } if err != nil { diff --git a/sqle/model/rule_list.go b/sqle/model/rule_list.go index a269c1fc92..ab8ddc16a0 100644 --- a/sqle/model/rule_list.go +++ b/sqle/model/rule_list.go @@ -1,37 +1,27 @@ package model import ( + "fmt" "strings" - - "github.com/actiontech/sqle/sqle/errors" ) type RuleTemplateDetail struct { - Name string `json:"name"` - Desc string `json:"desc"` - DBType string `json:"db_type"` - InstanceIds RowList `json:"instance_ids"` - InstanceNames RowList `json:"instance_names"` + Name string `json:"name"` + Desc string `json:"desc"` + DBType string `json:"db_type"` + // InstanceIds RowList `json:"instance_ids"` + // InstanceNames RowList `json:"instance_names"` } -var ruleTemplatesQueryTpl = `SELECT rt1.name, rt1.desc, rt1.db_type, -GROUP_CONCAT(DISTINCT COALESCE(instances.id,'')) AS instance_ids, -GROUP_CONCAT(DISTINCT COALESCE(instances.name,'')) AS instance_names -FROM rule_templates AS rt1 -LEFT JOIN instance_rule_template ON rt1.id = instance_rule_template.rule_template_id -LEFT JOIN instances ON instance_rule_template.instance_id = instances.id AND instances.deleted_at IS NULL -WHERE (SELECT COUNT(DISTINCT(rule_templates.id)) - +var ruleTemplatesQueryTpl = `SELECT rule_templates.name, rule_templates.desc, rule_templates.db_type {{- template "body" . }} -AND rt1.id = rule_templates.id -) > 0 -GROUP BY rt1.id + {{- if .limit }} LIMIT :limit OFFSET :offset {{- end -}} ` -var ruleTemplatesCountTpl = `SELECT COUNT(DISTINCT rule_templates.id) +var ruleTemplatesCountTpl = `SELECT COUNT(DISTINCT id) {{- template "body" . -}} ` @@ -39,15 +29,9 @@ var ruleTemplatesCountTpl = `SELECT COUNT(DISTINCT rule_templates.id) var ruleTemplatesQueryBodyTpl = ` {{ define "body" }} FROM rule_templates -LEFT JOIN instance_rule_template ON rule_templates.id = instance_rule_template.rule_template_id -LEFT JOIN instances ON instance_rule_template.instance_id = instances.id AND instances.deleted_at IS NULL WHERE -rule_templates.deleted_at IS NULL -AND rule_templates.project_id = :project_id - -{{- if .filter_instance_name }} -AND instances.name = :filter_instance_name -{{- end }} +deleted_at IS NULL +AND project_id = :project_id {{- end }} ` @@ -62,18 +46,6 @@ func (s *Storage) GetRuleTemplatesByReq(data map[string]interface{}) ( return result, count, err } -func (s *Storage) GetRuleTemplateTotalByProjectName(projectName string) (uint64, error) { - var count uint64 - err := s.db. - Table("rule_templates"). - Joins("LEFT JOIN projects ON rule_templates.project_id = projects.id"). - Where("projects.name = ?", projectName). - Where("rule_templates.deleted_at IS NULL"). - Count(&count). - Error - return count, errors.ConnectStorageErrWrapper(err) -} - func (s *Storage) GetRulesByReq(data map[string]interface{}) ( result []*Rule, err error) { db := s.db @@ -91,6 +63,9 @@ func (s *Storage) GetRulesByReq(data map[string]interface{}) ( db = db.Where("rules.name in (?)", strings.Split(namesStr, ",")) } } + if data["fuzzy_keyword_rule"] != "" { + db = db.Where("rules.`desc` like ? OR rules.annotation like ?", fmt.Sprintf("%%%s%%", data["fuzzy_keyword_rule"]), fmt.Sprintf("%%%s%%", data["fuzzy_keyword_rule"])) + } err = db.Find(&result).Error return result, err } @@ -113,6 +88,9 @@ func (s *Storage) GetCustomRulesByReq(data map[string]interface{}) ( db = db.Where("custom_rules.rule_id in (?)", strings.Split(namesStr, ",")) } } + if data["fuzzy_keyword_rule"] != "" { + db = db.Where("custom_rules.`desc` like ? OR custom_rules.annotation like ?", fmt.Sprintf("%%%s%%", data["fuzzy_keyword_rule"]), fmt.Sprintf("%%%s%%", data["fuzzy_keyword_rule"])) + } err = db.Find(&result).Error return result, err -} \ No newline at end of file +} diff --git a/sqle/model/sql_audit_record.go b/sqle/model/sql_audit_record.go index 9cdcae64dd..7a5d953bd9 100644 --- a/sqle/model/sql_audit_record.go +++ b/sqle/model/sql_audit_record.go @@ -15,8 +15,8 @@ type SQLAuditRecordTags struct { type SQLAuditRecord struct { Model - ProjectId uint `gorm:"index;not null"` - CreatorId uint `gorm:"not null"` + ProjectId string `gorm:"index;not null"` + CreatorId string `gorm:"not null"` AuditRecordId string `gorm:"unique;not null"` Tags JSON @@ -44,15 +44,7 @@ func (s *Storage) UpdateSQLAuditRecordById(SQLAuditRecordId string, data SQLAudi return errors.New(errors.ConnectStorageError, err) } -func (s *Storage) IsSQLAuditRecordBelongToCurrentUser(userId, projectId uint, SQLAuditRecordId string) (bool, error) { - isManager, err := s.IsProjectManagerByID(userId, projectId) - if err != nil { - return false, errors.New(errors.ConnectStorageError, fmt.Errorf("check project manager failed: %v", err)) - } - if isManager { - return true, nil - } - +func (s *Storage) IsSQLAuditRecordBelongToCurrentUser(userId, projectId string, SQLAuditRecordId string) (bool, error) { count := 0 if err := s.db.Table("sql_audit_records"). Where("audit_record_id = ?", SQLAuditRecordId). @@ -63,9 +55,9 @@ func (s *Storage) IsSQLAuditRecordBelongToCurrentUser(userId, projectId uint, SQ return count == 1, nil } -func (s *Storage) GetSQLAuditRecordById(projectId uint, SQLAuditRecordId string) (record *SQLAuditRecord, exist bool, err error) { +func (s *Storage) GetSQLAuditRecordById(projectId string, SQLAuditRecordId string) (record *SQLAuditRecord, exist bool, err error) { record = &SQLAuditRecord{} - if err = s.db.Preload("Task").Preload("Task.Instance").Preload("Task.ExecuteSQLs"). + if err = s.db.Preload("Task").Preload("Task.ExecuteSQLs"). Where("project_id = ?", projectId).Where("audit_record_id = ?", SQLAuditRecordId). Find(&record).Error; err != nil && err == gorm.ErrRecordNotFound { return nil, false, nil diff --git a/sqle/model/sql_audit_record_list.go b/sqle/model/sql_audit_record_list.go index 7fedb6baec..109e30e719 100644 --- a/sqle/model/sql_audit_record_list.go +++ b/sqle/model/sql_audit_record_list.go @@ -10,11 +10,9 @@ import ( type SQLAuditRecordListItem struct { AuditRecordId string `json:"audit_record_id"` RecordCreatedAt *time.Time `json:"record_created_at"` - CreatorName string `json:"creator_name"` + CreatorId string `json:"creator_id"` Tags sql.NullString `json:"tags"` - InstanceName sql.NullString `json:"instance_name"` - InstanceHost sql.NullString `json:"instance_host"` - InstancePort sql.NullString `json:"instance_port"` + InstanceId uint64 `json:"instance_id"` TaskId uint `json:"task_id"` DbType string `json:"db_type"` InstanceSchema string `json:"instance_schema"` @@ -29,12 +27,10 @@ var sqlAuditRecordQueryTpl = ` SELECT sql_audit_records.audit_record_id AS audit_record_id, sql_audit_records.created_at AS record_created_at, sql_audit_records.tags AS tags, - create_user.login_name AS creator_name, - instances.name AS instance_name, - instances.db_host AS instance_host, - instances.db_port AS instance_port, + sql_audit_records.creator_id AS creator_id, tasks.id AS task_id, tasks.db_type AS db_type, + tasks.instance_id AS instance_id, tasks.instance_schema AS instance_schema, tasks.audit_level AS audit_level, tasks.status AS task_status, @@ -58,17 +54,14 @@ SELECT COUNT(*) var sqlAuditRecordQueryBodyTpl = ` {{ define "body" }} FROM sql_audit_records -LEFT JOIN projects AS p ON sql_audit_records.project_id = p.id -LEFT JOIN users AS create_user ON sql_audit_records.creator_id = create_user.id LEFT JOIN tasks ON sql_audit_records.task_id = tasks.id -LEFT JOIN instances ON tasks.instance_id = instances.id WHERE sql_audit_records.deleted_at IS NULL -AND p.name = :filter_project_name +AND sql_audit_records.project_id = :filter_project_id {{- if .check_user_can_access }} -AND create_user.id = :filter_creator_id +AND sql_audit_records.creator_id = :filter_creator_id {{- end }} {{- if .fuzzy_search_tags }} @@ -83,8 +76,8 @@ AND tasks.status = :filter_task_status AND tasks.status <> :filter_task_status_exclude {{- end }} -{{- if .filter_instance_name }} -AND instances.name = :filter_instance_name +{{- if .filter_instance_id }} +AND tasks.instance_id = :filter_instance_id {{- end }} {{- if .filter_create_time_from }} diff --git a/sqle/model/sql_manage.go b/sqle/model/sql_manage.go index 86828a2723..82cdf151a6 100644 --- a/sqle/model/sql_manage.go +++ b/sqle/model/sql_manage.go @@ -18,12 +18,11 @@ type SqlManage struct { InstanceName string `json:"instance_name"` SchemaName string `json:"schema_name"` - Assignees []*User `gorm:"many2many:sql_manage_assignees;"` - Status string `json:"status" gorm:"default:\"unhandled\""` - Remark string `json:"remark" gorm:"type:varchar(4000)"` + Assignees string `json:"assignees"` + Status string `json:"status" gorm:"default:\"unhandled\""` + Remark string `json:"remark" gorm:"type:varchar(4000)"` - ProjectId uint `json:"project_id"` - Project *Project `gorm:"foreignkey:ProjectId"` + ProjectId string `json:"project_id"` AuditPlanId uint `json:"audit_plan_id"` AuditPlan *AuditPlan `gorm:"foreignkey:AuditPlanId"` diff --git a/sqle/model/sql_whitelist.go b/sqle/model/sql_whitelist.go index 5fda788b09..68d6f708e1 100644 --- a/sqle/model/sql_whitelist.go +++ b/sqle/model/sql_whitelist.go @@ -15,7 +15,7 @@ const ( type SqlWhitelist struct { Model - ProjectId uint `gorm:"index; not null"` + ProjectId ProjectUID `gorm:"index; not null"` // Value store SQL text. Value string `json:"value" gorm:"not null;type:text"` CapitalizedValue string `json:"-" gorm:"-"` @@ -41,12 +41,24 @@ func (s SqlWhitelist) TableName() string { return "sql_whitelist" } -func (s *Storage) GetSqlWhitelistByIdAndProjectName(sqlWhiteId, projectName string) (*SqlWhitelist, bool, error) { +// func (s *Storage) GetSqlWhitelistByIdAndProjectName(sqlWhiteId, projectName string) (*SqlWhitelist, bool, error) { +// sqlWhitelist := &SqlWhitelist{} +// err := s.db.Table("sql_whitelist"). +// Joins("LEFT JOIN projects ON projects.id = sql_whitelist.project_id"). +// Where("sql_whitelist.id = ?", sqlWhiteId). +// Where("projects.name = ?", projectName). +// First(sqlWhitelist).Error +// if err == gorm.ErrRecordNotFound { +// return sqlWhitelist, false, nil +// } +// return sqlWhitelist, true, errors.New(errors.ConnectStorageError, err) +// } + +func (s *Storage) GetSqlWhitelistByIdAndProjectUID(sqlWhiteId string, projectUID ProjectUID) (*SqlWhitelist, bool, error) { sqlWhitelist := &SqlWhitelist{} err := s.db.Table("sql_whitelist"). - Joins("LEFT JOIN projects ON projects.id = sql_whitelist.project_id"). Where("sql_whitelist.id = ?", sqlWhiteId). - Where("projects.name = ?", projectName). + Where("project_id = ?", projectUID). First(sqlWhitelist).Error if err == gorm.ErrRecordNotFound { return sqlWhitelist, false, nil @@ -54,12 +66,29 @@ func (s *Storage) GetSqlWhitelistByIdAndProjectName(sqlWhiteId, projectName stri return sqlWhitelist, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetSqlWhitelistByProjectName(pageIndex, pageSize uint32, projectName string) ([]SqlWhitelist, uint32, error) { +// func (s *Storage) GetSqlWhitelistByProjectName(pageIndex, pageSize uint32, projectName string) ([]SqlWhitelist, uint32, error) { +// var count uint32 +// sqlWhitelist := []SqlWhitelist{} +// query := s.db.Table("sql_whitelist"). +// Joins("LEFT JOIN projects ON projects.id = sql_whitelist.project_id"). +// Where("projects.name = ?", projectName) +// if pageSize == 0 { +// err := query.Order("id desc").Find(&sqlWhitelist).Count(&count).Error +// return sqlWhitelist, count, errors.New(errors.ConnectStorageError, err) +// } +// err := query.Count(&count).Error +// if err != nil { +// return sqlWhitelist, 0, errors.New(errors.ConnectStorageError, err) +// } +// err = query.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Order("id desc").Find(&sqlWhitelist).Error +// return sqlWhitelist, count, errors.New(errors.ConnectStorageError, err) +// } + +func (s *Storage) GetSqlWhitelistByProjectUID(pageIndex, pageSize uint32, projectUID ProjectUID) ([]SqlWhitelist, uint32, error) { var count uint32 sqlWhitelist := []SqlWhitelist{} query := s.db.Table("sql_whitelist"). - Joins("LEFT JOIN projects ON projects.id = sql_whitelist.project_id"). - Where("projects.name = ?", projectName) + Where("project_id = ?", projectUID) if pageSize == 0 { err := query.Order("id desc").Find(&sqlWhitelist).Count(&count).Error return sqlWhitelist, count, errors.New(errors.ConnectStorageError, err) @@ -72,25 +101,22 @@ func (s *Storage) GetSqlWhitelistByProjectName(pageIndex, pageSize uint32, proje return sqlWhitelist, count, errors.New(errors.ConnectStorageError, err) } - -func (s *Storage) GetSqlWhitelistByInstanceId(instanceId uint) ([]SqlWhitelist, error) { +func (s *Storage) GetSqlWhitelistByProjectId(projectId string) ([]SqlWhitelist, error) { sqlWhitelist := []SqlWhitelist{} err := s.db.Table("sql_whitelist"). - Joins("LEFT JOIN instances ON sql_whitelist.project_id = instances.project_id"). - Where("instances.id = ?", instanceId). + Where("sql_whitelist.project_id = ?", projectId). Find(&sqlWhitelist).Error - return sqlWhitelist, errors.New(errors.ConnectStorageError, err) + return sqlWhitelist, errors.New(errors.ConnectStorageError, err) } - -func (s *Storage) GetSqlWhitelistTotalByProjectName(projectName string) (uint64, error) { - var count uint64 - err := s.db. - Table("sql_whitelist"). - Joins("LEFT JOIN projects ON sql_whitelist.project_id = projects.id"). - Where("projects.name = ?", projectName). - Where("sql_whitelist.deleted_at IS NULL"). - Count(&count). - Error - return count, errors.ConnectStorageErrWrapper(err) -} +// func (s *Storage) GetSqlWhitelistTotalByProjectName(projectName string) (uint64, error) { +// var count uint64 +// err := s.db. +// Table("sql_whitelist"). +// Joins("LEFT JOIN projects ON sql_whitelist.project_id = projects.id"). +// Where("projects.name = ?", projectName). +// Where("sql_whitelist.deleted_at IS NULL"). +// Count(&count). +// Error +// return count, errors.ConnectStorageErrWrapper(err) +// } diff --git a/sqle/model/sync_instance_task.go b/sqle/model/sync_instance_task.go index 360cc8cbdf..98a3d651a2 100644 --- a/sqle/model/sync_instance_task.go +++ b/sqle/model/sync_instance_task.go @@ -1,21 +1,21 @@ package model -import ( - "time" -) +// import ( +// "time" +// ) -type SyncInstanceTask struct { - Model - Source string `json:"source" gorm:"not null"` - Version string `json:"version" gorm:"not null"` - URL string `json:"url" gorm:"not null"` - DbType string `json:"db_type" gorm:"not null"` - RuleTemplateID uint `json:"rule_template_id" gorm:"not null"` - // Cron表达式 - SyncInstanceInterval string `json:"sync_instance_interval" gorm:"not null"` - LastSyncStatus string `json:"last_sync_status" gorm:"default:\"initialized\""` - LastSyncSuccessTime *time.Time `json:"last_sync_success_time"` +// type SyncInstanceTask struct { +// Model +// Source string `json:"source" gorm:"not null"` +// Version string `json:"version" gorm:"not null"` +// URL string `json:"url" gorm:"not null"` +// DbType string `json:"db_type" gorm:"not null"` +// RuleTemplateID uint `json:"rule_template_id" gorm:"not null"` +// // Cron表达式 +// SyncInstanceInterval string `json:"sync_instance_interval" gorm:"not null"` +// LastSyncStatus string `json:"last_sync_status" gorm:"default:\"initialized\""` +// LastSyncSuccessTime *time.Time `json:"last_sync_success_time"` - // 关系表 - RuleTemplate *RuleTemplate `gorm:"foreignKey:RuleTemplateID"` -} +// // 关系表 +// RuleTemplate *RuleTemplate `gorm:"foreignKey:RuleTemplateID"` +// } diff --git a/sqle/model/task.go b/sqle/model/task.go index 6f482d3fa0..84ca78bd59 100644 --- a/sqle/model/task.go +++ b/sqle/model/task.go @@ -40,7 +40,7 @@ const TaskExecResultOK = "OK" type Task struct { Model - InstanceId uint `json:"instance_id"` + InstanceId uint64 `json:"instance_id"` Schema string `json:"instance_schema" gorm:"column:instance_schema" example:"db1"` PassRate float64 `json:"pass_rate"` Score int32 `json:"score"` @@ -49,12 +49,11 @@ type Task struct { DBType string `json:"db_type" gorm:"default:'mysql'" example:"mysql"` Status string `json:"status" gorm:"default:\"initialized\""` GroupId uint `json:"group_id" gorm:"column:group_id"` - CreateUserId uint + CreateUserId uint64 ExecStartAt *time.Time ExecEndAt *time.Time - CreateUser *User `gorm:"foreignkey:CreateUserId"` - Instance *Instance `json:"-" gorm:"foreignkey:InstanceId"` + Instance *Instance ExecuteSQLs []*ExecuteSQL `json:"-" gorm:"foreignkey:TaskId"` RollbackSQLs []*RollbackSQL `json:"-" gorm:"foreignkey:TaskId"` } @@ -280,7 +279,7 @@ func (s *Storage) GetTaskStatusByID(id string) (string, error) { func (s *Storage) GetTaskById(taskId string) (*Task, bool, error) { task := &Task{} - err := s.db.Where("id = ?", taskId).Preload("Instance").First(task).Error + err := s.db.Where("id = ?", taskId).First(task).Error if err == gorm.ErrRecordNotFound { return nil, false, nil } @@ -289,7 +288,7 @@ func (s *Storage) GetTaskById(taskId string) (*Task, bool, error) { func (s *Storage) GetTasksByIds(taskIds []uint) (tasks []*Task, foundAllIds bool, err error) { taskIds = utils.RemoveDuplicateUint(taskIds) - err = s.db.Where("id IN (?)", taskIds).Preload("Instance").Find(&tasks).Error + err = s.db.Where("id IN (?)", taskIds).Find(&tasks).Error if err != nil { return nil, false, errors.New(errors.ConnectStorageError, err) } @@ -301,7 +300,7 @@ func (s *Storage) GetTasksByIds(taskIds []uint) (tasks []*Task, foundAllIds bool func (s *Storage) GetTaskDetailById(taskId string) (*Task, bool, error) { task := &Task{} - err := s.db.Where("id = ?", taskId).Preload("Instance"). + err := s.db.Where("id = ?", taskId). Preload("ExecuteSQLs").Preload("RollbackSQLs").First(task).Error if err == gorm.ErrRecordNotFound { return nil, false, nil @@ -425,11 +424,11 @@ func (s *Storage) GetRelatedDDLTask(task *Task) ([]Task, error) { Schema: task.Schema, PassRate: 1, Status: TaskStatusAudited, - }).Preload("Instance").Preload("ExecuteSQLs").Find(&tasks).Error + }).Preload("ExecuteSQLs").Find(&tasks).Error return tasks, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetTaskByInstanceId(instanceId uint) ([]Task, error) { +func (s *Storage) GetTaskByInstanceId(instanceId uint64) ([]Task, error) { tasks := []Task{} err := s.db.Where(&Task{InstanceId: instanceId}).Find(&tasks).Error return tasks, errors.New(errors.ConnectStorageError, err) @@ -564,7 +563,7 @@ type TaskGroup struct { func (s *Storage) GetTaskGroupByGroupId(groupId uint) (*TaskGroup, error) { taskGroup := &TaskGroup{} - err := s.db.Preload("Tasks").Preload("Tasks.Instance"). + err := s.db.Preload("Tasks"). Where("id = ?", groupId).Find(&taskGroup).Error return taskGroup, errors.New(errors.ConnectStorageError, err) } @@ -596,48 +595,6 @@ func (s *Storage) GetSqlAvgExecutionTimeStatistic(limit uint) ([]*SqlExecuteStat } type SqlExecutionCount struct { - InstanceName string `json:"instance_name"` - Count uint `json:"count"` -} - -// GetSqlExecutionFailCount 获取sql上线失败统计 -func (s *Storage) GetSqlExecutionFailCount() ([]SqlExecutionCount, error) { - var sqlExecutionFailCount []SqlExecutionCount - - err := s.db.Model(&Workflow{}).Select("i.name as instance_name, count(*) as count"). - Joins("left join workflow_records wr on workflows.workflow_record_id = wr.id"). - Joins("left join workflow_instance_records wir on wr.id = wir.workflow_record_id"). - Joins("left join tasks t on wir.task_id = t.id"). - Joins("left join instances i on t.instance_id = i.id"). - Where("t.status = ?", TaskStatusExecuteFailed). - Where("t.exec_start_at is not null"). - Where("t.exec_end_at is not null"). - Group("t.instance_id"). - Scan(&sqlExecutionFailCount).Error - if err != nil { - return nil, errors.ConnectStorageErrWrapper(err) - } - - return sqlExecutionFailCount, nil -} - -// GetSqlExecutionTotalCount 获取sql上线总数统计 -// 上线总数(根据数据源划分)是指:正在上线,上线成功,上线失败 task的总数 -func (s *Storage) GetSqlExecutionTotalCount() ([]SqlExecutionCount, error) { - var sqlExecutionTotalCount []SqlExecutionCount - - err := s.db.Model(&Workflow{}).Select("i.name as instance_name, count(*) as count"). - Joins("left join workflow_records wr on workflows.workflow_record_id = wr.id"). - Joins("left join workflow_instance_records wir on wr.id = wir.workflow_record_id"). - Joins("left join tasks t on wir.task_id = t.id"). - Joins("left join instances i on t.instance_id = i.id"). - Where("t.status not in (?)", []string{TaskStatusInit, TaskStatusAudited}). - Where("t.exec_start_at is not null"). - Group("t.instance_id"). - Scan(&sqlExecutionTotalCount).Error - if err != nil { - return nil, errors.ConnectStorageErrWrapper(err) - } - - return sqlExecutionTotalCount, nil + Count uint `json:"count"` + InstanceId uint64 `json:"instance_id"` } diff --git a/sqle/model/user.go b/sqle/model/user.go index c22a9d031b..2637f69229 100644 --- a/sqle/model/user.go +++ b/sqle/model/user.go @@ -5,9 +5,6 @@ import ( "strings" "github.com/actiontech/sqle/sqle/errors" - "github.com/actiontech/sqle/sqle/log" - "github.com/actiontech/sqle/sqle/utils" - "github.com/jinzhu/gorm" ) const ( @@ -39,292 +36,292 @@ type User struct { SecretPassword string `json:"secret_password" gorm:"not null;column:password"` UserAuthenticationType UserAuthenticationType `json:"user_authentication_type" gorm:"not null"` - UserGroups []*UserGroup `gorm:"many2many:user_group_users"` - Stat uint `json:"stat" gorm:"not null; default: 0; comment:'0:正常 1:被禁用'"` - ThirdPartyUserID string `json:"third_party_user_id"` + // UserGroups []*UserGroup `gorm:"many2many:user_group_users"` + Stat uint `json:"stat" gorm:"not null; default: 0; comment:'0:正常 1:被禁用'"` + ThirdPartyUserID string `json:"third_party_user_id"` WorkflowStepTemplates []*WorkflowStepTemplate `gorm:"many2many:workflow_step_template_user"` WorkflowInstanceRecords []*WorkflowInstanceRecord `gorm:"many2many:workflow_instance_record_user"` } -func (u *User) IsDisabled() bool { - return u.Stat == Disabled -} - -func (u *User) SetStat(stat uint) { - u.Stat = stat -} - -// BeforeSave is a hook implement gorm model before exec create -func (i *User) BeforeSave() error { - return i.encryptPassword() -} - -// AfterFind is a hook implement gorm model after query, ignore err if query from db -func (i *User) AfterFind() error { - err := i.decryptPassword() - if err != nil { - log.NewEntry().Errorf("decrypt password for user %s failed, error: %v", i.Name, err) - } - return nil -} - -func (i *User) decryptPassword() error { - if i == nil { - return nil - } - if i.Password == "" { - data, err := utils.AesDecrypt(i.SecretPassword) - if err != nil { - return err - } else { - i.Password = data - } - } - return nil -} - -func (i *User) encryptPassword() error { - if i == nil { - return nil - } - if i.SecretPassword == "" { - data, err := utils.AesEncrypt(i.Password) - if err != nil { - return err - } - i.SecretPassword = data - } - return nil -} +// // BeforeSave is a hook implement gorm model before exec create +// func (i *User) BeforeSave() error { +// return i.encryptPassword() +// } + +// // AfterFind is a hook implement gorm model after query, ignore err if query from db +// func (i *User) AfterFind() error { +// err := i.decryptPassword() +// if err != nil { +// log.NewEntry().Errorf("decrypt password for user %s failed, error: %v", i.Name, err) +// } +// return nil +// } + +// func (i *User) decryptPassword() error { +// if i == nil { +// return nil +// } +// if i.Password == "" { +// data, err := utils.AesDecrypt(i.SecretPassword) +// if err != nil { +// return err +// } else { +// i.Password = data +// } +// } +// return nil +// } + +// func (i *User) encryptPassword() error { +// if i == nil { +// return nil +// } +// if i.SecretPassword == "" { +// data, err := utils.AesEncrypt(i.Password) +// if err != nil { +// return err +// } +// i.SecretPassword = data +// } +// return nil +// } func (i *User) FingerPrint() string { return fmt.Sprintf(`{"id":"%v", "secret_password":"%v" }`, i.ID, i.SecretPassword) } -func (s *Storage) GetUserByThirdPartyUserID(thirdPartyUserID string) (*User, bool, error) { - t := &User{} - err := s.db.Where("third_party_user_id = ?", thirdPartyUserID).First(t).Error - if err == gorm.ErrRecordNotFound { - return t, false, nil - } - return t, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetUserByName(name string) (*User, bool, error) { - t := &User{} - err := s.db.Where("login_name = ?", name).First(t).Error - if err == gorm.ErrRecordNotFound { - return t, false, nil - } - return t, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetUserDetailByName(name string) (*User, bool, error) { - t := &User{} - err := s.db.Preload("UserGroups"). - Where("login_name = ?", name).First(t).Error - if err == gorm.ErrRecordNotFound { - return t, false, nil - } - return t, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetUsersByNames(names []string) ([]*User, error) { - users := []*User{} - err := s.db.Where("login_name in (?)", names).Find(&users).Error - return users, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetUserTipsByProject(projectName string) ([]*User, error) { - if projectName == "" { - return s.GetAllUserTip() - } - - query := ` -SELECT DISTINCT users.login_name -FROM users -LEFT JOIN project_user on project_user.user_id = users.id -LEFT JOIN projects on project_user.project_id = projects.id -LEFT JOIN user_group_users on users.id = user_group_users.user_id -LEFT JOIN project_user_group on user_group_users.user_group_id = project_user_group.user_group_id -LEFT JOIN projects as p on project_user_group.project_id = p.id -WHERE users.stat = 0 -AND( - projects.name = ? - AND - projects.deleted_at IS NULL -OR - p.name = ? - AND - p.deleted_at IS NULL -) -` - - var users []*User - err := s.db.Raw(query, projectName, projectName).Scan(&users).Error - - return users, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetAllUserTip() ([]*User, error) { - users := []*User{} - err := s.db.Select("login_name").Where("stat=0").Find(&users).Error - return users, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetAllUserCount() (int64, error) { - var count int64 - return count, s.db.Model(&User{}).Count(&count).Error -} - -func (s *Storage) GetAndCheckUserExist(userNames []string) (users []*User, err error) { - users, err = s.GetUsersByNames(userNames) - if err != nil { - return users, err - } - existUserNames := map[string]struct{}{} +// func (s *Storage) GetUserByThirdPartyUserID(thirdPartyUserID string) (*User, bool, error) { +// t := &User{} +// err := s.db.Where("third_party_user_id = ?", thirdPartyUserID).First(t).Error +// if err == gorm.ErrRecordNotFound { +// return t, false, nil +// } +// return t, true, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetUserByName(name string) (*User, bool, error) { +// t := &User{} +// err := s.db.Where("login_name = ?", name).First(t).Error +// if err == gorm.ErrRecordNotFound { +// return t, false, nil +// } +// return t, true, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetUserDetailByName(name string) (*User, bool, error) { +// t := &User{} +// err := s.db.Preload("UserGroups"). +// Where("login_name = ?", name).First(t).Error +// if err == gorm.ErrRecordNotFound { +// return t, false, nil +// } +// return t, true, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetUsersByNames(names []string) ([]*User, error) { +// users := []*User{} +// err := s.db.Where("login_name in (?)", names).Find(&users).Error +// return users, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetUserTipsByProject(projectName string) ([]*User, error) { +// if projectName == "" { +// return s.GetAllUserTip() +// } + +// query := ` +// SELECT DISTINCT users.login_name +// FROM users +// LEFT JOIN project_user on project_user.user_id = users.id +// LEFT JOIN projects on project_user.project_id = projects.id +// LEFT JOIN user_group_users on users.id = user_group_users.user_id +// LEFT JOIN project_user_group on user_group_users.user_group_id = project_user_group.user_group_id +// LEFT JOIN projects as p on project_user_group.project_id = p.id +// WHERE users.stat = 0 +// AND( +// projects.name = ? +// AND +// projects.deleted_at IS NULL +// OR +// p.name = ? +// AND +// p.deleted_at IS NULL +// ) +// ` + +// var users []*User +// err := s.db.Raw(query, projectName, projectName).Scan(&users).Error + +// return users, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetAllUserTip() ([]*User, error) { +// users := []*User{} +// err := s.db.Select("login_name").Where("stat=0").Find(&users).Error +// return users, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetAllUserCount() (int64, error) { +// var count int64 +// return count, s.db.Model(&User{}).Count(&count).Error +// } + +// func (s *Storage) GetAndCheckUserExist(userNames []string) (users []*User, err error) { +// users, err = s.GetUsersByNames(userNames) +// if err != nil { +// return users, err +// } +// existUserNames := map[string]struct{}{} +// for _, user := range users { +// existUserNames[user.Name] = struct{}{} +// } +// notExistUserNames := []string{} +// for _, userName := range userNames { +// if _, ok := existUserNames[userName]; !ok { +// notExistUserNames = append(notExistUserNames, userName) +// } +// } +// if len(notExistUserNames) > 0 { +// return users, errors.New(errors.DataNotExist, +// fmt.Errorf("user %s not exist", strings.Join(notExistUserNames, ", "))) +// } +// return users, nil +// } + +// func (s *Storage) UpdatePassword(user *User, newPassword string) error { +// user.Password = newPassword +// // User{}.encryptPassword(): SecretPassword为空时才会对密码进行加密操作 +// user.SecretPassword = "" +// return s.Save(user) +// } + +// func (s *Storage) UserHasRunningWorkflow(userId uint) (bool, error) { +// // count how many running workflows have been assigned to this user +// query := `SELECT COUNT(user_id) FROM users +// LEFT JOIN workflow_step_user wstu ON users.id = wstu.user_id +// LEFT JOIN workflow_steps ws ON wstu.workflow_step_id = ws.id +// LEFT JOIN workflow_records wr ON ws.workflow_record_id = wr.id +// WHERE users.id = ? AND wr.status IN (?) AND ws.state = ?;` +// var count uint +// err := s.db.Raw(query, userId, []string{WorkflowStatusWaitForAudit, WorkflowStatusWaitForExecution}, WorkflowStepStateInit).Count(&count).Error +// if err != nil { +// return false, errors.New(errors.ConnectStorageError, err) +// } +// if count > 0 { +// return true, nil +// } + +// // count how many running workflows have been created by this user +// var workflows []*Workflow +// err = s.db.Model(workflows). +// Preload("Record", "status IN (?)", []string{WorkflowStatusWaitForAudit, WorkflowStatusWaitForExecution}). +// Where("create_user_id = ?", userId). +// Find(&workflows).Error +// return len(workflows) > 0 && workflows[0].Record != nil, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) UserHasBindWorkflowTemplate(user *User) (bool, error) { +// count := 0 +// err := s.db.Table("workflow_templates"). +// Joins("join workflow_step_templates on workflow_templates.id = workflow_step_templates.workflow_template_id"). +// Joins("join workflow_step_template_user on workflow_step_templates.id = workflow_step_template_user.workflow_step_template_id"). +// Where("workflow_templates.deleted_at is null"). +// Where("workflow_step_template_user.user_id = ?", user.ID). +// Count(&count).Error +// return count > 0, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) SaveUserAndAssociations( +// user *User, userGroups []*UserGroup, managementPermissionCodes *[]uint) (err error) { +// return s.Tx(func(txDB *gorm.DB) error { + +// // User +// if err := txDB.Save(user).Error; err != nil { +// txDB.Rollback() +// return errors.ConnectStorageErrWrapper(err) +// } + +// // user groups +// if userGroups != nil { +// if err := txDB.Model(user). +// Association("UserGroups"). +// Replace(userGroups).Error; err != nil { +// txDB.Rollback() +// return errors.ConnectStorageErrWrapper(err) +// } +// } + +// // permission +// if managementPermissionCodes != nil { +// if err := updateManagementPermission(txDB, user.ID, *managementPermissionCodes); err != nil { +// txDB.Rollback() +// return errors.ConnectStorageErrWrapper(err) +// } +// } + +// return nil +// }) +// } + +// func (s *Storage) GetUserByID(id uint) (*User, bool, error) { +// u := &User{} +// err := s.db.Model(User{}).Where("id = ?", id).Find(u).Error +// if err == gorm.ErrRecordNotFound { +// return u, false, nil +// } +// return u, true, errors.New(errors.ConnectStorageError, err) +// } + +// func (s *Storage) GetUserTotalInProjectByProjectName(projectName string) (uint64, error) { +// sql := ` +// SELECT +// COUNT(DISTINCT users.id) +// FROM +// users +// LEFT JOIN project_user ON users.id = project_user.user_id +// LEFT JOIN projects AS p ON p.id = project_user.project_id +// LEFT JOIN user_group_users ON user_group_users.user_id = users.id +// LEFT JOIN project_user_group ON project_user_group.user_group_id = user_group_users.user_group_id +// LEFT JOIN projects AS pg ON pg.id = project_user_group.project_id +// WHERE +// users.deleted_at IS NULL +// AND( +// ( +// p.name = ? +// AND +// p.deleted_at IS NULL +// ) +// OR +// ( +// pg.name = ? +// AND +// pg.deleted_at IS NULL +// ) +// ) +// ` +// var count uint64 +// err := s.db.Raw(sql, projectName, projectName).Count(&count).Error +// return count, errors.ConnectStorageErrWrapper(err) +// } + +// func (s *Storage) GetMemberTips(projectName string) ([]*User, error) { +// users := []*User{} +// err := s.db.Model(&User{}).Select("login_name"). +// Joins("LEFT JOIN project_user ON project_user.user_id = users.id"). +// Joins("LEFT JOIN projects ON projects.id = project_user.project_id"). +// Where("projects.deleted_at IS NULL"). +// Where("projects.name = ?", projectName). +// Find(&users).Error +// return users, errors.ConnectStorageErrWrapper(err) +// } + +func genIdsByUsers(users []*User) string { + ids := make([]string, 0) for _, user := range users { - existUserNames[user.Name] = struct{}{} - } - notExistUserNames := []string{} - for _, userName := range userNames { - if _, ok := existUserNames[userName]; !ok { - notExistUserNames = append(notExistUserNames, userName) - } - } - if len(notExistUserNames) > 0 { - return users, errors.New(errors.DataNotExist, - fmt.Errorf("user %s not exist", strings.Join(notExistUserNames, ", "))) - } - return users, nil -} - -func (s *Storage) UpdatePassword(user *User, newPassword string) error { - user.Password = newPassword - // User{}.encryptPassword(): SecretPassword为空时才会对密码进行加密操作 - user.SecretPassword = "" - return s.Save(user) -} - -func (s *Storage) UserHasRunningWorkflow(userId uint) (bool, error) { - // count how many running workflows have been assigned to this user - query := `SELECT COUNT(user_id) FROM users -LEFT JOIN workflow_step_user wstu ON users.id = wstu.user_id -LEFT JOIN workflow_steps ws ON wstu.workflow_step_id = ws.id -LEFT JOIN workflow_records wr ON ws.workflow_record_id = wr.id -WHERE users.id = ? AND wr.status IN (?) AND ws.state = ?;` - var count uint - err := s.db.Raw(query, userId, []string{WorkflowStatusWaitForAudit, WorkflowStatusWaitForExecution}, WorkflowStepStateInit).Count(&count).Error - if err != nil { - return false, errors.New(errors.ConnectStorageError, err) - } - if count > 0 { - return true, nil - } - - // count how many running workflows have been created by this user - var workflows []*Workflow - err = s.db.Model(workflows). - Preload("Record", "status IN (?)", []string{WorkflowStatusWaitForAudit, WorkflowStatusWaitForExecution}). - Where("create_user_id = ?", userId). - Find(&workflows).Error - return len(workflows) > 0 && workflows[0].Record != nil, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) UserHasBindWorkflowTemplate(user *User) (bool, error) { - count := 0 - err := s.db.Table("workflow_templates"). - Joins("join workflow_step_templates on workflow_templates.id = workflow_step_templates.workflow_template_id"). - Joins("join workflow_step_template_user on workflow_step_templates.id = workflow_step_template_user.workflow_step_template_id"). - Where("workflow_templates.deleted_at is null"). - Where("workflow_step_template_user.user_id = ?", user.ID). - Count(&count).Error - return count > 0, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) SaveUserAndAssociations( - user *User, userGroups []*UserGroup, managementPermissionCodes *[]uint) (err error) { - return s.Tx(func(txDB *gorm.DB) error { - - // User - if err := txDB.Save(user).Error; err != nil { - txDB.Rollback() - return errors.ConnectStorageErrWrapper(err) - } - - // user groups - if userGroups != nil { - if err := txDB.Model(user). - Association("UserGroups"). - Replace(userGroups).Error; err != nil { - txDB.Rollback() - return errors.ConnectStorageErrWrapper(err) - } - } - - // permission - if managementPermissionCodes != nil { - if err := updateManagementPermission(txDB, user.ID, *managementPermissionCodes); err != nil { - txDB.Rollback() - return errors.ConnectStorageErrWrapper(err) - } - } - - return nil - }) -} - -func (s *Storage) GetUserByID(id uint) (*User, bool, error) { - u := &User{} - err := s.db.Model(User{}).Where("id = ?", id).Find(u).Error - if err == gorm.ErrRecordNotFound { - return u, false, nil + ids = append(ids, user.GetIDStr()) } - return u, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetUserTotalInProjectByProjectName(projectName string) (uint64, error) { - sql := ` -SELECT - COUNT(DISTINCT users.id) -FROM - users - LEFT JOIN project_user ON users.id = project_user.user_id - LEFT JOIN projects AS p ON p.id = project_user.project_id - LEFT JOIN user_group_users ON user_group_users.user_id = users.id - LEFT JOIN project_user_group ON project_user_group.user_group_id = user_group_users.user_group_id - LEFT JOIN projects AS pg ON pg.id = project_user_group.project_id -WHERE - users.deleted_at IS NULL -AND( - ( - p.name = ? - AND - p.deleted_at IS NULL - ) - OR - ( - pg.name = ? - AND - pg.deleted_at IS NULL - ) -) -` - var count uint64 - err := s.db.Raw(sql, projectName, projectName).Count(&count).Error - return count, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) GetMemberTips(projectName string) ([]*User, error) { - users := []*User{} - err := s.db.Model(&User{}).Select("login_name"). - Joins("LEFT JOIN project_user ON project_user.user_id = users.id"). - Joins("LEFT JOIN projects ON projects.id = project_user.project_id"). - Where("projects.deleted_at IS NULL"). - Where("projects.name = ?", projectName). - Find(&users).Error - return users, errors.ConnectStorageErrWrapper(err) + return strings.Join(ids, ",") } type UserRole struct { @@ -357,17 +354,18 @@ func (s *Storage) GetUserRoleFromUserGroupByProjectName(projectName string) ([]* return userRoles, errors.ConnectStorageErrWrapper(err) } -func GetDistinctOfUsers(users1, users2 []*User) []*User { - resUsers := users1 +func GetDistinctOfUsers(users1, users2 []*User) []string { + resUsers := make([]string, 0) m := make(map[uint]struct{}) for _, user := range users1 { m[user.ID] = struct{}{} + resUsers = append(resUsers, user.GetIDStr()) } for _, user := range users2 { _, ok := m[user.ID] if !ok { - resUsers = append(resUsers, user) + resUsers = append(resUsers, user.GetIDStr()) } } diff --git a/sqle/model/user_group.go b/sqle/model/user_group.go index 5d21017dda..7f24e6919a 100644 --- a/sqle/model/user_group.go +++ b/sqle/model/user_group.go @@ -1,205 +1,205 @@ package model -import ( - "strings" - - "github.com/actiontech/sqle/sqle/errors" - "github.com/jinzhu/gorm" -) - -// NOTE: related model: -// - ProjectMemberGroupRole -type UserGroup struct { - Model - Name string `json:"name" gorm:"index"` - Desc string `json:"desc" gorm:"column:description"` - Users []*User `gorm:"many2many:user_group_users"` - Stat uint `json:"stat" gorm:"comment:'0:active,1:disabled'"` -} - -func (ug *UserGroup) TableName() string { - return "user_groups" -} - -func (ug *UserGroup) SetStat(stat int) { - ug.Stat = uint(stat) -} - -func (ug *UserGroup) IsDisabled() bool { - return ug.Stat == Disabled -} - -func (s *Storage) GetUserGroupByName(name string) ( - userGroup *UserGroup, isExist bool, err error) { - userGroup = &UserGroup{} - - err = s.db.Where("name = ?", name).First(userGroup).Error - if gorm.IsRecordNotFoundError(err) { - return nil, false, nil - } - - return userGroup, true, err -} - -func (s *Storage) SaveUserGroupAndAssociations( - ug *UserGroup, us []*User) (err error) { - - return s.Tx(func(txDB *gorm.DB) error { - if err := txDB.Save(ug).Error; err != nil { - return err - } - - // save user group users - if us != nil { - if err := txDB.Model(ug).Association("Users").Replace(us).Error; err != nil { - return err - } - } - - return nil - }) -} - -var userGroupTipsQueryTpl = `SELECT -user_groups.name AS group_name, -GROUP_CONCAT(DISTINCT COALESCE(users.login_name,'')) AS user_names -{{- template "body" . }} -GROUP BY user_groups.id -` - -var userGroupTipsQueryBodyTpl = ` -{{ define "body" }} -FROM user_groups -LEFT JOIN user_group_users ON user_groups.id = user_group_users.user_group_id -LEFT JOIN users ON user_group_users.user_id = users.id AND users.deleted_at IS NULL - -{{- if .project_name }} -LEFT JOIN project_user_group on project_user_group.user_group_id = user_groups.id -LEFT JOIN projects on project_user_group.project_id = projects.id -{{- end }} - -WHERE user_groups.deleted_at IS NULL -AND user_groups.stat=0 - -{{- if .project_name }} -AND projects.name = :project_name -AND projects.deleted_at IS NULL -{{- end }} - -{{- end }} - -` - -type UserGroupTips struct { - Name string `json:"group_name"` - UserNames RowList `json:"user_names"` -} - -func (s *Storage) GetUserGroupTipByProject(data map[string]interface{}) ([]*UserGroupTips, error) { - results := []*UserGroupTips{} - err := s.getListResult(userGroupTipsQueryTpl, userGroupTipsQueryBodyTpl, data, &results) - if err != nil { - return nil, err - } - - return results, errors.New(errors.ConnectStorageError, err) -} - -var userGroupsQueryTpl = `SELECT -user_groups.id, -user_groups.name, -user_groups.description, -user_groups.stat, -GROUP_CONCAT(DISTINCT COALESCE(users.login_name,'')) AS user_names -FROM user_groups -LEFT JOIN user_group_users ON user_groups.id = user_group_users.user_group_id -LEFT JOIN users ON user_group_users.user_id = users.id AND users.deleted_at IS NULL -WHERE -user_groups.id IN (SELECT DISTINCT(user_groups.id) - -{{- template "body" . -}} -) -GROUP BY user_groups.id -{{- if .limit }} -LIMIT :limit OFFSET :offset -{{- end -}} -` - -var userGroupCountTpl = `SELECT COUNT(DISTINCT user_groups.id) - -{{- template "body" . -}} -` -var userGroupsQueryBodyTpl = ` -{{ define "body" }} -FROM user_groups -LEFT JOIN user_group_users ON user_groups.id = user_group_users.user_group_id -LEFT JOIN users ON user_group_users.user_id = users.id AND users.deleted_at IS NULL -WHERE -user_groups.deleted_at IS NULL - -{{- if .filter_user_group_name }} -AND user_groups.name = :filter_user_group_name -{{- end -}} - -{{- end }} -` - -type UserGroupDetail struct { - Id int - Name string `json:"name"` - Desc string `json:"description"` - Stat uint `json:"stat"` - UserNames RowList `json:"user_names"` -} - -func (ugd *UserGroupDetail) IsDisabled() bool { - return ugd.Stat == Disabled -} - -func (s *Storage) GetUserGroupsByReq(data map[string]interface{}) ( - results []*UserGroupDetail, count uint64, err error) { - - err = s.getListResult(userGroupsQueryBodyTpl, userGroupsQueryTpl, data, &results) - if err != nil { - return nil, 0, err - } - - count, err = s.getCountResult(userGroupsQueryBodyTpl, userGroupCountTpl, data) - return results, count, err -} - -func (s *Storage) GetUserGroupsByNames(names []string) (ugs []*UserGroup, err error) { - ugs = []*UserGroup{} - err = s.db.Where("name IN (?)", names).Find(&ugs).Error - return ugs, errors.ConnectStorageErrWrapper(err) -} - -func (s *Storage) GetAndCheckUserGroupExist(userGroupNames []string) (ugs []*UserGroup, err error) { - ugs, err = s.GetUserGroupsByNames(userGroupNames) - if err != nil { - return nil, err - } - - existUserGroupNames := map[string]struct{}{} - { - for i := range ugs { - existUserGroupNames[ugs[i].Name] = struct{}{} - } - } - - notExistUserGroupNames := []string{} - { - for i := range userGroupNames { - if _, ok := existUserGroupNames[userGroupNames[i]]; !ok { - notExistUserGroupNames = append(notExistUserGroupNames, userGroupNames[i]) - } - } - } - - if len(notExistUserGroupNames) > 0 { - return ugs, errors.NewDataNotExistErr("user group <%v> not exist", - strings.Join(notExistUserGroupNames, ", ")) - } - - return ugs, nil -} +// import ( +// "strings" + +// "github.com/actiontech/sqle/sqle/errors" +// "github.com/jinzhu/gorm" +// ) + +// // NOTE: related model: +// // - ProjectMemberGroupRole +// type UserGroup struct { +// Model +// Name string `json:"name" gorm:"index"` +// Desc string `json:"desc" gorm:"column:description"` +// Users []*User `gorm:"many2many:user_group_users"` +// Stat uint `json:"stat" gorm:"comment:'0:active,1:disabled'"` +// } + +// func (ug *UserGroup) TableName() string { +// return "user_groups" +// } + +// func (ug *UserGroup) SetStat(stat int) { +// ug.Stat = uint(stat) +// } + +// func (ug *UserGroup) IsDisabled() bool { +// return ug.Stat == Disabled +// } + +// func (s *Storage) GetUserGroupByName(name string) ( +// userGroup *UserGroup, isExist bool, err error) { +// userGroup = &UserGroup{} + +// err = s.db.Where("name = ?", name).First(userGroup).Error +// if gorm.IsRecordNotFoundError(err) { +// return nil, false, nil +// } + +// return userGroup, true, err +// } + +// func (s *Storage) SaveUserGroupAndAssociations( +// ug *UserGroup, us []*User) (err error) { + +// return s.Tx(func(txDB *gorm.DB) error { +// if err := txDB.Save(ug).Error; err != nil { +// return err +// } + +// // save user group users +// if us != nil { +// if err := txDB.Model(ug).Association("Users").Replace(us).Error; err != nil { +// return err +// } +// } + +// return nil +// }) +// } + +// var userGroupTipsQueryTpl = `SELECT +// user_groups.name AS group_name, +// GROUP_CONCAT(DISTINCT COALESCE(users.login_name,'')) AS user_names +// {{- template "body" . }} +// GROUP BY user_groups.id +// ` + +// var userGroupTipsQueryBodyTpl = ` +// {{ define "body" }} +// FROM user_groups +// LEFT JOIN user_group_users ON user_groups.id = user_group_users.user_group_id +// LEFT JOIN users ON user_group_users.user_id = users.id AND users.deleted_at IS NULL + +// {{- if .project_name }} +// LEFT JOIN project_user_group on project_user_group.user_group_id = user_groups.id +// LEFT JOIN projects on project_user_group.project_id = projects.id +// {{- end }} + +// WHERE user_groups.deleted_at IS NULL +// AND user_groups.stat=0 + +// {{- if .project_name }} +// AND projects.name = :project_name +// AND projects.deleted_at IS NULL +// {{- end }} + +// {{- end }} + +// ` + +// type UserGroupTips struct { +// Name string `json:"group_name"` +// UserNames RowList `json:"user_names"` +// } + +// func (s *Storage) GetUserGroupTipByProject(data map[string]interface{}) ([]*UserGroupTips, error) { +// results := []*UserGroupTips{} +// err := s.getListResult(userGroupTipsQueryTpl, userGroupTipsQueryBodyTpl, data, &results) +// if err != nil { +// return nil, err +// } + +// return results, errors.New(errors.ConnectStorageError, err) +// } + +// var userGroupsQueryTpl = `SELECT +// user_groups.id, +// user_groups.name, +// user_groups.description, +// user_groups.stat, +// GROUP_CONCAT(DISTINCT COALESCE(users.login_name,'')) AS user_names +// FROM user_groups +// LEFT JOIN user_group_users ON user_groups.id = user_group_users.user_group_id +// LEFT JOIN users ON user_group_users.user_id = users.id AND users.deleted_at IS NULL +// WHERE +// user_groups.id IN (SELECT DISTINCT(user_groups.id) + +// {{- template "body" . -}} +// ) +// GROUP BY user_groups.id +// {{- if .limit }} +// LIMIT :limit OFFSET :offset +// {{- end -}} +// ` + +// var userGroupCountTpl = `SELECT COUNT(DISTINCT user_groups.id) + +// {{- template "body" . -}} +// ` +// var userGroupsQueryBodyTpl = ` +// {{ define "body" }} +// FROM user_groups +// LEFT JOIN user_group_users ON user_groups.id = user_group_users.user_group_id +// LEFT JOIN users ON user_group_users.user_id = users.id AND users.deleted_at IS NULL +// WHERE +// user_groups.deleted_at IS NULL + +// {{- if .filter_user_group_name }} +// AND user_groups.name = :filter_user_group_name +// {{- end -}} + +// {{- end }} +// ` + +// type UserGroupDetail struct { +// Id int +// Name string `json:"name"` +// Desc string `json:"description"` +// Stat uint `json:"stat"` +// UserNames RowList `json:"user_names"` +// } + +// func (ugd *UserGroupDetail) IsDisabled() bool { +// return ugd.Stat == Disabled +// } + +// func (s *Storage) GetUserGroupsByReq(data map[string]interface{}) ( +// results []*UserGroupDetail, count uint64, err error) { + +// err = s.getListResult(userGroupsQueryBodyTpl, userGroupsQueryTpl, data, &results) +// if err != nil { +// return nil, 0, err +// } + +// count, err = s.getCountResult(userGroupsQueryBodyTpl, userGroupCountTpl, data) +// return results, count, err +// } + +// func (s *Storage) GetUserGroupsByNames(names []string) (ugs []*UserGroup, err error) { +// ugs = []*UserGroup{} +// err = s.db.Where("name IN (?)", names).Find(&ugs).Error +// return ugs, errors.ConnectStorageErrWrapper(err) +// } + +// func (s *Storage) GetAndCheckUserGroupExist(userGroupNames []string) (ugs []*UserGroup, err error) { +// ugs, err = s.GetUserGroupsByNames(userGroupNames) +// if err != nil { +// return nil, err +// } + +// existUserGroupNames := map[string]struct{}{} +// { +// for i := range ugs { +// existUserGroupNames[ugs[i].Name] = struct{}{} +// } +// } + +// notExistUserGroupNames := []string{} +// { +// for i := range userGroupNames { +// if _, ok := existUserGroupNames[userGroupNames[i]]; !ok { +// notExistUserGroupNames = append(notExistUserGroupNames, userGroupNames[i]) +// } +// } +// } + +// if len(notExistUserGroupNames) > 0 { +// return ugs, errors.NewDataNotExistErr("user group <%v> not exist", +// strings.Join(notExistUserGroupNames, ", ")) +// } + +// return ugs, nil +// } diff --git a/sqle/model/user_list.go b/sqle/model/user_list.go index db28e7e8db..cf46b63020 100644 --- a/sqle/model/user_list.go +++ b/sqle/model/user_list.go @@ -1,62 +1,62 @@ package model -import "database/sql" - -type UserDetail struct { - Id int - Name string `json:"login_name"` - Email string - Phone sql.NullString `json:"phone"` - WeChatID sql.NullString `json:"wechat_id"` - LoginType string `json:"user_authentication_type"` - Stat int `json:"stat"` - RoleNames RowList `json:"role_names"` - UserGroupNames RowList `json:"user_group_names"` -} - -func (u *UserDetail) IsDisabled() bool { - return u.Stat == Disabled -} - -var usersQueryTpl = `SELECT -users.id, users.login_name, users.email, users.phone, users.wechat_id, -users.user_authentication_type, users.stat, -GROUP_CONCAT(DISTINCT COALESCE(user_groups.name,'')) AS user_group_names -FROM users -LEFT JOIN user_group_users ON users.id = user_group_users.user_id -LEFT JOIN user_groups ON user_group_users.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL -WHERE -users.id in (SELECT DISTINCT(users.id) -{{- template "body" . -}} -) -GROUP BY users.id -{{- if .limit }} -LIMIT :limit OFFSET :offset -{{- end -}} -` - -var usersCountTpl = `SELECT COUNT(DISTINCT users.id) -{{- template "body" . -}} -` - -var usersQueryBodyTpl = ` -{{ define "body" }} -FROM users -WHERE -users.deleted_at IS NULL -{{- if .filter_user_name }} -AND users.login_name = :filter_user_name -{{- end }} -{{- end }} -` - -func (s *Storage) GetUsersByReq(data map[string]interface{}) ( - result []*UserDetail, count uint64, err error) { - - err = s.getListResult(usersQueryBodyTpl, usersQueryTpl, data, &result) - if err != nil { - return result, 0, err - } - count, err = s.getCountResult(usersQueryBodyTpl, usersCountTpl, data) - return result, count, err -} +// import "database/sql" + +// type UserDetail struct { +// Id int +// Name string `json:"login_name"` +// Email string +// Phone sql.NullString `json:"phone"` +// WeChatID sql.NullString `json:"wechat_id"` +// LoginType string `json:"user_authentication_type"` +// Stat int `json:"stat"` +// RoleNames RowList `json:"role_names"` +// UserGroupNames RowList `json:"user_group_names"` +// } + +// func (u *UserDetail) IsDisabled() bool { +// return u.Stat == Disabled +// } + +// var usersQueryTpl = `SELECT +// users.id, users.login_name, users.email, users.phone, users.wechat_id, +// users.user_authentication_type, users.stat, +// GROUP_CONCAT(DISTINCT COALESCE(user_groups.name,'')) AS user_group_names +// FROM users +// LEFT JOIN user_group_users ON users.id = user_group_users.user_id +// LEFT JOIN user_groups ON user_group_users.user_group_id = user_groups.id AND user_groups.deleted_at IS NULL +// WHERE +// users.id in (SELECT DISTINCT(users.id) +// {{- template "body" . -}} +// ) +// GROUP BY users.id +// {{- if .limit }} +// LIMIT :limit OFFSET :offset +// {{- end -}} +// ` + +// var usersCountTpl = `SELECT COUNT(DISTINCT users.id) +// {{- template "body" . -}} +// ` + +// var usersQueryBodyTpl = ` +// {{ define "body" }} +// FROM users +// WHERE +// users.deleted_at IS NULL +// {{- if .filter_user_name }} +// AND users.login_name = :filter_user_name +// {{- end }} +// {{- end }} +// ` + +// func (s *Storage) GetUsersByReq(data map[string]interface{}) ( +// result []*UserDetail, count uint64, err error) { + +// err = s.getListResult(usersQueryBodyTpl, usersQueryTpl, data, &result) +// if err != nil { +// return result, 0, err +// } +// count, err = s.getCountResult(usersQueryBodyTpl, usersCountTpl, data) +// return result, count, err +// } diff --git a/sqle/model/utils.go b/sqle/model/utils.go index 61210aef1e..8e1f4ad4f3 100644 --- a/sqle/model/utils.go +++ b/sqle/model/utils.go @@ -84,6 +84,10 @@ type Model struct { DeletedAt *time.Time `json:"-" sql:"index"` } +func (m Model) GetIDStr() string { + return fmt.Sprintf("%d", m.ID) +} + func NewStorage(user, password, host, port, schema string, debug bool) (*Storage, error) { log.Logger().Infof("connecting to storage, host: %s, port: %s, user: %s, schema: %s", host, port, user, schema) @@ -111,22 +115,14 @@ var autoMigrateList = []interface{}{ &AuditPlanSQLV2{}, &AuditPlan{}, &ExecuteSQL{}, - &Instance{}, - &WeChatConfiguration{}, - &LDAPConfiguration{}, - &Oauth2Configuration{}, &RoleOperation{}, - &Role{}, &RollbackSQL{}, &RuleTemplateRule{}, &RuleTemplate{}, &Rule{}, - &SMTPConfiguration{}, &SqlWhitelist{}, &SystemVariable{}, &Task{}, - &UserGroup{}, - &User{}, &WorkflowRecord{}, &WorkflowStepTemplate{}, &WorkflowStep{}, @@ -136,20 +132,10 @@ var autoMigrateList = []interface{}{ &SqlQueryHistory{}, &TaskGroup{}, &WorkflowInstanceRecord{}, - &CloudBeaverUserCache{}, - &CloudBeaverInstanceCache{}, - &Project{}, - &ProjectMemberRole{}, - &ProjectMemberGroupRole{}, - &ManagementPermission{}, + &FeishuInstance{}, &IM{}, &DingTalkInstance{}, - &FeishuInstance{}, - &SyncInstanceTask{}, &OperationRecord{}, - &PersonaliseConfig{}, - &LogoConfig{}, - &WebHookConfig{}, &CustomRule{}, &RuleTemplateCustomRule{}, &SQLAuditRecord{}, @@ -166,26 +152,12 @@ func (s *Storage) AutoMigrate() error { if err != nil { return errors.New(errors.ConnectStorageError, err) } - err = s.db.Model(&User{}).AddIndex("idx_users_id_name", "id", "login_name").Error - if err != nil { - return errors.New(errors.ConnectStorageError, err) - } - err = s.db.Model(&Instance{}).AddIndex("idx_instances_id_name", "id", "name").Error - if err != nil { - return errors.New(errors.ConnectStorageError, err) - } err = s.db.Model(AuditPlanSQLV2{}).AddUniqueIndex("uniq_audit_plan_sqls_v2_audit_plan_id_fingerprint_md5", "audit_plan_id", "fingerprint_md5").Error if err != nil { return errors.New(errors.ConnectStorageError, err) } - err = s.db.Model(&ProjectMemberRole{}).AddUniqueIndex("uniq_project_member_roles_user_id_instance_id_role_id", - "user_id", "instance_id", "role_id").Error - if err != nil { - return errors.New(errors.ConnectStorageError, err) - } - err = s.db.Model(&ProjectMemberGroupRole{}).AddUniqueIndex("uniq_project_user_group_role_user_group_id_instance_id_role_id", - "user_group_id", "instance_id", "role_id").Error + err = s.db.Model(BlackListAuditPlanSQL{}).AddUniqueIndex("uniq_type_content", "filter_type", "filter_content").Error if err != nil { return errors.New(errors.ConnectStorageError, err) } @@ -194,10 +166,6 @@ func (s *Storage) AutoMigrate() error { return errors.New(errors.ConnectStorageError, err) } - err = s.db.Model(BlackListAuditPlanSQL{}).AddUniqueIndex("uniq_type_content", "filter_type", "filter_content").Error - if err != nil { - return errors.New(errors.ConnectStorageError, err) - } if s.db.Dialect().HasColumn(Rule{}.TableName(), "is_default") { if err = s.db.Model(&Rule{}).DropColumn("is_default").Error; err != nil { return errors.New(errors.ConnectStorageError, err) @@ -264,39 +232,56 @@ func (s *Storage) CreateRulesIfNotExist(rules map[string][]*driverV2.Rule) error return nil } -func (s *Storage) CreateDefaultRole() error { - roles, err := s.GetAllRoleTip() +// func (s *Storage) CreateDefaultRole() error { +// roles, err := s.GetAllRoleTip() +// if err != nil { +// return err +// } +// if len(roles) > 0 { +// return nil +// } + +// // dev +// err = s.SaveRoleAndAssociations(&Role{ +// Name: "dev", +// Desc: "dev", +// }, []uint{OP_WORKFLOW_SAVE, OP_AUDIT_PLAN_SAVE, OP_SQL_QUERY_QUERY}) +// if err != nil { +// return err +// } + +// // dba +// err = s.SaveRoleAndAssociations(&Role{ +// Name: "dba", +// Desc: "dba", +// }, []uint{OP_WORKFLOW_AUDIT, OP_SQL_QUERY_QUERY}) +// if err != nil { +// return err +// } + +// return nil +// } + +const DefaultProjectUid string = "700300" + +func (s *Storage) CreateDefaultWorkflowTemplateIfNotExist() error { + _, exist, err := s.GetWorkflowTemplateByProjectId(ProjectUID(DefaultProjectUid)) if err != nil { return err } - if len(roles) > 0 { - return nil - } - - // dev - err = s.SaveRoleAndAssociations(&Role{ - Name: "dev", - Desc: "dev", - }, []uint{OP_WORKFLOW_SAVE, OP_AUDIT_PLAN_SAVE, OP_SQL_QUERY_QUERY}) - if err != nil { - return err - } - - // dba - err = s.SaveRoleAndAssociations(&Role{ - Name: "dba", - Desc: "dba", - }, []uint{OP_WORKFLOW_AUDIT, OP_SQL_QUERY_QUERY}) - if err != nil { - return err + if !exist { + td := DefaultWorkflowTemplate(DefaultProjectUid) + err = s.SaveWorkflowTemplate(td) + if err != nil { + return err + } } - return nil } -func (s *Storage) CreateDefaultTemplate(rules map[string][]*driverV2.Rule) error { +func (s *Storage) CreateDefaultTemplateIfNotExist(projectId ProjectUID, rules map[string][]*driverV2.Rule) error { for dbType, r := range rules { templateName := s.GetDefaultRuleTemplateName(dbType) - exist, err := s.IsRuleTemplateExistFromAnyProject(templateName) + exist, err := s.IsRuleTemplateExistFromAnyProject(projectId, templateName) if err != nil { return xerrors.Wrap(err, "get rule template failed") } @@ -305,9 +290,10 @@ func (s *Storage) CreateDefaultTemplate(rules map[string][]*driverV2.Rule) error } t := &RuleTemplate{ - Name: templateName, - Desc: "默认规则模板", - DBType: dbType, + ProjectId: projectId, + Name: templateName, + Desc: "默认规则模板", + DBType: dbType, } if err := s.Save(t); err != nil { return err @@ -339,42 +325,34 @@ func (s *Storage) GetDefaultRuleTemplateName(dbType string) string { return fmt.Sprintf("default_%v", dbType) } -func (s *Storage) CreateAdminUser() error { - _, exist, err := s.GetUserByName(DefaultAdminUser) - if err != nil { - return err - } - if !exist { - return s.Save(&User{ - Name: DefaultAdminUser, - Password: "admin", - }) - } - return nil -} +// func (s *Storage) CreateAdminUser() error { +// _, exist, err := s.GetUserByName(DefaultAdminUser) +// if err != nil { +// return err +// } +// if !exist { +// return s.Save(&User{ +// Name: DefaultAdminUser, +// Password: "admin", +// }) +// } +// return nil +// } const DefaultProject = "default" -func (s *Storage) CreateDefaultProject() error { - exist, err := s.IsProjectExist() - if err != nil { - return err - } - if exist { - return nil - } - - defaultUser, exist, err := s.GetUserByName(DefaultAdminUser) - if err != nil { - return err - } - if !exist { - return fmt.Errorf("admin not exist, unable to create project") - } - - err = s.CreateProject(DefaultProject, "", defaultUser.ID) - return err -} +// func (s *Storage) CreateDefaultProject() error { +// exist, err := s.IsProjectExist() +// if err != nil { +// return err +// } +// if exist { +// return nil +// } + +// err = s.CreateProject(DefaultProject, "", 700200 /* TODO 从公共包传?*/) +// return err +// } func (s *Storage) Exist(model interface{}) (bool, error) { var count int diff --git a/sqle/model/workflow.go b/sqle/model/workflow.go index b5ab1a2fd8..58d4829c3c 100644 --- a/sqle/model/workflow.go +++ b/sqle/model/workflow.go @@ -3,23 +3,24 @@ package model import ( "database/sql" "fmt" - "strconv" + "strings" "time" + driverV2 "github.com/actiontech/sqle/sqle/driver/v2" "github.com/actiontech/sqle/sqle/errors" + "github.com/jinzhu/gorm" ) -var UnScopedFunc = func(db *gorm.DB) *gorm.DB { return db.Unscoped() } - type WorkflowTemplate struct { Model + ProjectId ProjectUID `gorm:"index; not null"` Name string Desc string AllowSubmitWhenLessAuditLevel string - Steps []*WorkflowStepTemplate `json:"-" gorm:"foreignkey:workflowTemplateId"` - Instances []*Instance `gorm:"foreignkey:WorkflowTemplateId"` + Steps []*WorkflowStepTemplate `json:"-" gorm:"foreignkey:workflowTemplateId"` + // Instances []*Instance `gorm:"foreignkey:WorkflowTemplateId"` } const ( @@ -38,7 +39,34 @@ type WorkflowStepTemplate struct { ApprovedByAuthorized sql.NullBool `gorm:"column:approved_by_authorized"` ExecuteByAuthorized sql.NullBool `gorm:"column:execute_by_authorized"` - Users []*User `gorm:"many2many:workflow_step_template_user"` + Users string // `gorm:"many2many:workflow_step_template_user"` // dms-todo: 调整存储格式 +} + +func DefaultWorkflowTemplate(projectId string) *WorkflowTemplate { + return &WorkflowTemplate{ + ProjectId: ProjectUID(projectId), + Name: fmt.Sprintf("%s-WorkflowTemplate", projectId), + Desc: fmt.Sprintf("%s 默认模板", projectId), + AllowSubmitWhenLessAuditLevel: string(driverV2.RuleLevelWarn), + Steps: []*WorkflowStepTemplate{ + { + Number: 1, + Typ: WorkflowStepTypeSQLReview, + ApprovedByAuthorized: sql.NullBool{ + Bool: true, + Valid: true, + }, + }, + { + Number: 2, + Typ: WorkflowStepTypeSQLExecute, + ExecuteByAuthorized: sql.NullBool{ + Bool: true, + Valid: true, + }, + }, + }, + } } func (s *Storage) GetWorkflowTemplateByName(name string) (*WorkflowTemplate, bool, error) { @@ -59,15 +87,24 @@ func (s *Storage) GetWorkflowTemplateById(id uint) (*WorkflowTemplate, bool, err return workflowTemplate, true, errors.New(errors.ConnectStorageError, err) } +func (s *Storage) GetWorkflowTemplateByProjectId(projectId ProjectUID) (*WorkflowTemplate, bool, error) { + workflowTemplate := &WorkflowTemplate{} + err := s.db.Where("project_id = ?", projectId).First(workflowTemplate).Error + if err == gorm.ErrRecordNotFound { + return workflowTemplate, false, nil + } + return workflowTemplate, true, errors.New(errors.ConnectStorageError, err) +} + func (s *Storage) GetWorkflowStepsByTemplateId(id uint) ([]*WorkflowStepTemplate, error) { steps := []*WorkflowStepTemplate{} - err := s.db.Preload("Users").Where("workflow_template_id = ?", id).Find(&steps).Error + err := s.db.Where("workflow_template_id = ?", id).Find(&steps).Error return steps, errors.New(errors.ConnectStorageError, err) } func (s *Storage) GetWorkflowStepsDetailByTemplateId(id uint) ([]*WorkflowStepTemplate, error) { steps := []*WorkflowStepTemplate{} - err := s.db.Preload("Users").Where("workflow_template_id = ?", id).Find(&steps).Error + err := s.db.Where("workflow_template_id = ?", id).Find(&steps).Error return steps, errors.New(errors.ConnectStorageError, err) } @@ -79,8 +116,8 @@ func (s *Storage) SaveWorkflowTemplate(template *WorkflowTemplate) error { } func saveWorkflowTemplate(template *WorkflowTemplate, tx *sql.Tx) (templateId int64, err error) { - result, err := tx.Exec("INSERT INTO workflow_templates (name, `desc`, `allow_submit_when_less_audit_level`) values (?, ?, ?)", - template.Name, template.Desc, template.AllowSubmitWhenLessAuditLevel) + result, err := tx.Exec("INSERT INTO workflow_templates (name, `desc`, `allow_submit_when_less_audit_level`, `project_id`) values (?, ?, ?, ?)", + template.Name, template.Desc, template.AllowSubmitWhenLessAuditLevel, template.ProjectId) if err != nil { return 0, err } @@ -90,8 +127,8 @@ func saveWorkflowTemplate(template *WorkflowTemplate, tx *sql.Tx) (templateId in } template.ID = uint(templateId) for _, step := range template.Steps { - result, err = tx.Exec("INSERT INTO workflow_step_templates (step_number, workflow_template_id, type, `desc`, approved_by_authorized,execute_by_authorized) values (?,?,?,?,?,?)", - step.Number, templateId, step.Typ, step.Desc, step.ApprovedByAuthorized, step.ExecuteByAuthorized) + result, err = tx.Exec("INSERT INTO workflow_step_templates (step_number, workflow_template_id, type, users, `desc`, approved_by_authorized,execute_by_authorized) values (?,?,?,?,?,?,?)", + step.Number, templateId, step.Typ, step.Users, step.Desc, step.ApprovedByAuthorized, step.ExecuteByAuthorized) if err != nil { return 0, err } @@ -100,13 +137,6 @@ func saveWorkflowTemplate(template *WorkflowTemplate, tx *sql.Tx) (templateId in return 0, err } step.ID = uint(stepId) - for _, user := range step.Users { - _, err = tx.Exec("INSERT INTO workflow_step_template_user (workflow_step_template_id, user_id) values (?,?)", - stepId, user.ID) - if err != nil { - return 0, err - } - } } return templateId, nil } @@ -119,8 +149,8 @@ func (s *Storage) UpdateWorkflowTemplateSteps(templateId uint, steps []*Workflow return err } for _, step := range steps { - result, err := tx.Exec("INSERT INTO workflow_step_templates (step_number, workflow_template_id, type, `desc`, approved_by_authorized,execute_by_authorized) values (?,?,?,?,?,?)", - step.Number, templateId, step.Typ, step.Desc, step.ApprovedByAuthorized, step.ExecuteByAuthorized) + result, err := tx.Exec("INSERT INTO workflow_step_templates (step_number, workflow_template_id, type,users, `desc`, approved_by_authorized,execute_by_authorized) values (?,?,?,?,?,?,?)", + step.Number, templateId, step.Typ, step.Users, step.Desc, step.ApprovedByAuthorized, step.ExecuteByAuthorized) if err != nil { return err } @@ -129,23 +159,16 @@ func (s *Storage) UpdateWorkflowTemplateSteps(templateId uint, steps []*Workflow return err } step.ID = uint(stepId) - for _, user := range step.Users { - _, err = tx.Exec("INSERT INTO workflow_step_template_user (workflow_step_template_id, user_id) values (?,?)", - stepId, user.ID) - if err != nil { - return err - } - } } return nil }) } -func (s *Storage) UpdateWorkflowTemplateInstances(workflowTemplate *WorkflowTemplate, - instances ...*Instance) error { - err := s.db.Model(workflowTemplate).Association("Instances").Replace(instances).Error - return errors.New(errors.ConnectStorageError, err) -} +// func (s *Storage) UpdateWorkflowTemplateInstances(workflowTemplate *WorkflowTemplate, +// instances ...*Instance) error { +// err := s.db.Model(workflowTemplate).Association("Instances").Replace(instances).Error +// return errors.New(errors.ConnectStorageError, err) +// } func (s *Storage) GetWorkflowTemplateTip() ([]*WorkflowTemplate, error) { templates := []*WorkflowTemplate{} @@ -158,15 +181,15 @@ type Workflow struct { Subject string WorkflowId string `gorm:"unique"` Desc string `gorm:"type:varchar(3000)"` - CreateUserId uint + CreateUserId string WorkflowRecordId uint - ProjectId uint `gorm:"index; not null"` + ProjectId ProjectUID `gorm:"index; not null"` - CreateUser *User `gorm:"foreignkey:CreateUserId"` - Record *WorkflowRecord `gorm:"foreignkey:WorkflowRecordId"` - Project *Project `gorm:"foreignkey:ProjectId"` - RecordHistory []*WorkflowRecord `gorm:"many2many:workflow_record_history;"` - Mode string + Record *WorkflowRecord `gorm:"foreignkey:WorkflowRecordId"` + // Project *Project `gorm:"foreignkey:ProjectId"` + RecordHistory []*WorkflowRecord `gorm:"many2many:workflow_record_history"` + + Mode string } const ( @@ -207,42 +230,31 @@ type WorkflowInstanceRecord struct { Model TaskId uint `gorm:"index"` WorkflowRecordId uint `gorm:"index; not null"` - InstanceId uint + InstanceId uint64 ScheduledAt *time.Time - ScheduleUserId uint + ScheduleUserId string // 用于区分工单处于上线步骤时,某个数据源是否已上线,因为数据源可以分批上线 IsSQLExecuted bool - ExecutionUserId uint + ExecutionUserId string - ExecutionAssignees []*User `gorm:"many2many:workflow_instance_record_user"` - Instance *Instance `gorm:"foreignkey:InstanceId"` - Task *Task `gorm:"foreignkey:TaskId"` - User *User `gorm:"foreignkey:ExecutionUserId"` -} - -func (wir *WorkflowInstanceRecord) ExecuteUserName() string { - if wir.User == nil { - return "" - } - return wir.User.Name + Instance *Instance `gorm:"foreignkey:InstanceId"` + Task *Task `gorm:"foreignkey:TaskId"` + // User *User `gorm:"foreignkey:ExecutionUserId"` + ExecutionAssignees string } func (s *Storage) GetWorkInstanceRecordByTaskId(id string) (instanceRecord WorkflowInstanceRecord, err error) { return instanceRecord, s.db.Where("task_id = ?", id).First(&instanceRecord).Error } -func (s *Storage) GetInstanceByTaskIDList(taskIds []uint) (instances []*Instance, err error) { - var instanceRecords []*WorkflowInstanceRecord - err = s.db.Model(&WorkflowInstanceRecord{}).Preload("Instance").Where("task_id in (?)", taskIds).Find(&instanceRecords).Error +func (s *Storage) GetWorkInstanceRecordByTaskIds(taskIds []uint) ([]*WorkflowInstanceRecord, error) { + var workflowInstanceRecords []*WorkflowInstanceRecord + err := s.db.Model(&WorkflowInstanceRecord{}).Where("task_id in (?)", taskIds).Find(&workflowInstanceRecords).Error if err != nil { return nil, errors.New(errors.ConnectStorageError, err) } - for _, instanceRecord := range instanceRecords { - instances = append(instances, instanceRecord.Instance) - } - - return instances, nil + return workflowInstanceRecords, nil } const ( @@ -253,17 +265,17 @@ const ( type WorkflowStep struct { Model - OperationUserId uint + OperationUserId string OperateAt *time.Time - WorkflowId uint `gorm:"index; not null"` + WorkflowId string `gorm:"index; not null"` WorkflowRecordId uint `gorm:"index; not null"` WorkflowStepTemplateId uint `gorm:"index; not null"` State string `gorm:"default:\"initialized\""` Reason string - Assignees []*User `gorm:"many2many:workflow_step_user"` - Template *WorkflowStepTemplate `gorm:"foreignkey:WorkflowStepTemplateId"` - OperationUser *User `gorm:"foreignkey:OperationUserId"` + Assignees string // `gorm:"many2many:workflow_step_user"` + Template *WorkflowStepTemplate `gorm:"foreignkey:WorkflowStepTemplateId"` + // OperationUser string // `gorm:"foreignkey:OperationUserId"` } func (ws *WorkflowStep) OperationTime() string { @@ -273,13 +285,6 @@ func (ws *WorkflowStep) OperationTime() string { return ws.OperateAt.Format("2006-01-02 15:04:05") } -func (ws *WorkflowStep) OperationUserName() string { - if ws.OperationUser == nil { - return "" - } - return ws.OperationUser.Name -} - func generateWorkflowStepByTemplate(stepsTemplate []*WorkflowStepTemplate, allInspector []*User, allExecutor []*User) []*WorkflowStep { steps := make([]*WorkflowStep, 0, len(stepsTemplate)) for i, st := range stepsTemplate { @@ -289,10 +294,10 @@ func generateWorkflowStepByTemplate(stepsTemplate []*WorkflowStepTemplate, allIn Assignees: st.Users, } if st.ApprovedByAuthorized.Bool { - step.Assignees = allInspector + step.Assignees = genIdsByUsers(allInspector) } if i == len(stepsTemplate)-1 && st.ExecuteByAuthorized.Bool { - step.Assignees = allExecutor + step.Assignees = genIdsByUsers(allExecutor) } steps = append(steps, step) @@ -305,30 +310,23 @@ func (w *Workflow) cloneWorkflowStep() []*WorkflowStep { for _, step := range w.Record.Steps { steps = append(steps, &WorkflowStep{ WorkflowStepTemplateId: step.Template.ID, - WorkflowId: w.ID, + WorkflowId: w.WorkflowId, Assignees: step.Assignees, }) } return steps } -func (w *Workflow) CreateUserName() string { - if w.CreateUser != nil { - return w.CreateUser.Name - } - return "" -} - func (w *Workflow) CurrentStep() *WorkflowStep { return w.Record.CurrentStep } -func (w *Workflow) CurrentAssigneeUser() []*User { +func (w *Workflow) CurrentAssigneeUser() []string { currentStep := w.CurrentStep() if currentStep == nil { - return []*User{} + return []string{} } - return currentStep.Assignees + return strings.Split(currentStep.Assignees, ",") } func (w *Workflow) NextStep() *WorkflowStep { @@ -361,8 +359,8 @@ func (w *Workflow) IsOperationUser(user *User) bool { if w.CurrentStep() == nil { return false } - for _, assUser := range w.CurrentStep().Assignees { - if user.ID == assUser.ID { + for _, assUser := range strings.Split(w.CurrentStep().Assignees, ",") { + if user.GetIDStr() == assUser { return true } } @@ -389,7 +387,7 @@ func (w *Workflow) GetTaskIds() []uint { return taskIds } -func (s *Storage) CreateWorkflowV2(subject, workflowId, desc string, user *User, tasks []*Task, stepTemplates []*WorkflowStepTemplate, projectId uint) error { +func (s *Storage) CreateWorkflowV2(subject, workflowId, desc string, user *User, tasks []*Task, stepTemplates []*WorkflowStepTemplate, projectId ProjectUID, getOpExecUser func([]*Task) (canAuditUsers [][]*User, canExecUsers [][]*User)) error { if len(tasks) <= 0 { return errors.New(errors.DataConflict, fmt.Errorf("there is no task for creating workflow")) } @@ -431,7 +429,7 @@ func (s *Storage) CreateWorkflowV2(subject, workflowId, desc string, user *User, WorkflowId: workflowId, Desc: desc, ProjectId: projectId, - CreateUserId: user.ID, + CreateUserId: user.GetIDStr(), Mode: workflowMode, WorkflowRecordId: record.ID, } @@ -442,22 +440,7 @@ func (s *Storage) CreateWorkflowV2(subject, workflowId, desc string, user *User, return errors.New(errors.ConnectStorageError, err) } - allUsers := make([][]*User, len(tasks)) - allExecutor := make([][]*User, len(tasks)) - for i, task := range tasks { - users, err := s.GetCanAuditWorkflowUsers(task.Instance) - if err != nil { - return err - } - allUsers[i] = users - - executor, err := s.GetCanExecuteWorkflowUsers(task.Instance) - if err != nil { - return err - } - allExecutor[i] = executor - } - + allUsers, allExecutor := getOpExecUser(tasks) canOptUsers := allUsers[0] canExecUsers := allExecutor[0] for i := 1; i < len(allUsers); i++ { @@ -466,9 +449,12 @@ func (s *Storage) CreateWorkflowV2(subject, workflowId, desc string, user *User, } if len(canOptUsers) == 0 || len(canExecUsers) == 0 { - adminUser, _, err := s.GetUserByName(DefaultAdminUser) - if err != nil { - return err + // TODO 获取管理用户 + adminUser := &User{ + Model: Model{ + ID: 700200, + }, + Name: "admin", } if len(canOptUsers) == 0 { canOptUsers = append(canOptUsers, adminUser) @@ -486,21 +472,11 @@ func (s *Storage) CreateWorkflowV2(subject, workflowId, desc string, user *User, for _, instanceRecord := range instanceRecords { instRecord := instanceRecord instRecord.WorkflowRecordId = record.ID - assignees := instRecord.ExecutionAssignees - // 置为nil,防止用户被更新 - // 相关issue:https://github.com/actiontech/sqle/issues/1775 - instRecord.ExecutionAssignees = nil err = tx.Save(instRecord).Error if err != nil { tx.Rollback() return errors.New(errors.ConnectStorageError, err) } - - err = tx.Model(instRecord).Association("ExecutionAssignees").Replace(assignees).Error - if err != nil { - tx.Rollback() - return errors.New(errors.ConnectStorageError, err) - } } } @@ -510,19 +486,12 @@ func (s *Storage) CreateWorkflowV2(subject, workflowId, desc string, user *User, for _, step := range steps { currentStep := step currentStep.WorkflowRecordId = record.ID - currentStep.WorkflowId = workflow.ID - users := currentStep.Assignees - currentStep.Assignees = nil + currentStep.WorkflowId = workflow.WorkflowId err = tx.Save(currentStep).Error if err != nil { tx.Rollback() return errors.New(errors.ConnectStorageError, err) } - err = tx.Model(currentStep).Association("Assignees").Replace(users).Error - if err != nil { - tx.Rollback() - return errors.New(errors.ConnectStorageError, err) - } } if len(steps) > 0 { @@ -550,7 +519,7 @@ func UpdateInstanceRecord(stepTemplates []*WorkflowStepTemplate, tasks []*Task, if isExecuteByAuthorized { distinctOfUsers := GetDistinctOfUsers(stepExecUsers, allExecutor[i]) - instanceRecords[i].ExecutionAssignees = distinctOfUsers + instanceRecords[i].ExecutionAssignees = strings.Join(distinctOfUsers, ",") } else { instanceRecords[i].ExecutionAssignees = stepTemplateAssignees } @@ -587,18 +556,11 @@ func (s *Storage) UpdateWorkflowRecord(w *Workflow, tasks []*Task) error { for _, step := range steps { currentStep := step currentStep.WorkflowRecordId = record.ID - users := currentStep.Assignees - currentStep.Assignees = nil err = tx.Save(currentStep).Error if err != nil { tx.Rollback() return errors.New(errors.ConnectStorageError, err) } - err = tx.Model(currentStep).Association("Assignees").Replace(users).Error - if err != nil { - tx.Rollback() - return errors.New(errors.ConnectStorageError, err) - } } if len(steps) > 0 { err = tx.Model(record).Update("current_workflow_step_id", steps[0].ID).Error @@ -616,7 +578,7 @@ func (s *Storage) UpdateWorkflowRecord(w *Workflow, tasks []*Task) error { } // update workflow record to new - if err := tx.Model(&Workflow{}).Where("id = ?", w.ID). + if err := tx.Model(&Workflow{}).Where("workflow_id = ?", w.WorkflowId). Update("workflow_record_id", record.ID).Error; err != nil { tx.Rollback() return errors.New(errors.ConnectStorageError, err) @@ -670,8 +632,8 @@ func updateWorkflowStatus(tx *gorm.DB, w *Workflow) error { func updateWorkflowStep(tx *gorm.DB, operateStep *WorkflowStep) error { // 必须保证更新前的操作用户未填写,通过数据库的特性保证数据不会重复写 - db := tx.Exec("UPDATE workflow_steps SET operation_user_id = ?, operate_at = ?, state = ?, reason = ? WHERE id = ? AND operation_user_id = 0", - operateStep.OperationUserId, operateStep.OperateAt, operateStep.State, operateStep.Reason, operateStep.ID) + db := tx.Exec("UPDATE workflow_steps SET operation_user_id = ?, operate_at = ?, state = ?, reason = ? WHERE id = ? AND operation_user_id = ?", + operateStep.OperationUserId, operateStep.OperateAt, operateStep.State, operateStep.Reason, operateStep.ID, "") if db.Error != nil { return db.Error } @@ -734,7 +696,7 @@ func (s *Storage) UpdateWorkflowRecordByID(id uint, workFlow map[string]interfac return s.db.Model(&WorkflowRecord{}).Where("id = ?", id).Updates(workFlow).Error } -func (s *Storage) UpdateInstanceRecordSchedule(ir *WorkflowInstanceRecord, userId uint, scheduleTime *time.Time) error { +func (s *Storage) UpdateInstanceRecordSchedule(ir *WorkflowInstanceRecord, userId string, scheduleTime *time.Time) error { err := s.db.Model(&WorkflowInstanceRecord{}).Where("id = ?", ir.ID).Update(map[string]interface{}{ "scheduled_at": scheduleTime, "schedule_user_id": userId, @@ -745,11 +707,11 @@ func (s *Storage) UpdateInstanceRecordSchedule(ir *WorkflowInstanceRecord, userI func (s *Storage) getWorkflowStepsByRecordIds(ids []uint) ([]*WorkflowStep, error) { steps := []*WorkflowStep{} err := s.db.Where("workflow_record_id in (?)", ids). - Preload("Assignees"). - Preload("OperationUser").Find(&steps).Error + Find(&steps).Error if err != nil { return nil, errors.New(errors.ConnectStorageError, err) } + stepTemplateIds := make([]uint, 0, len(steps)) for _, step := range steps { stepTemplateIds = append(stepTemplateIds, step.WorkflowStepTemplateId) @@ -771,7 +733,7 @@ func (s *Storage) getWorkflowStepsByRecordIds(ids []uint) ([]*WorkflowStep, erro func (s *Storage) getWorkflowInstanceRecordsByRecordId(id uint) ([]*WorkflowInstanceRecord, error) { instanceRecords := []*WorkflowInstanceRecord{} - err := s.db.Preload("Instance").Preload("Task").Preload("ExecutionAssignees").Where("workflow_record_id = ?", id). + err := s.db.Preload("Task").Where("workflow_record_id = ?", id). Find(&instanceRecords).Error if err != nil { return nil, errors.New(errors.ConnectStorageError, err) @@ -779,64 +741,20 @@ func (s *Storage) getWorkflowInstanceRecordsByRecordId(id uint) ([]*WorkflowInst return instanceRecords, nil } -func (s *Storage) GetWorkflowDetailByTaskID(taskID uint) (*Workflow, error) { - workflow, exist, err := s.GetWorkflowByTaskId(taskID) - if err != nil { - return nil, err - } - if !exist { - return nil, fmt.Errorf("workflow not exist by task_id(%v)", taskID) - } - - workflow, exist, err = s.GetWorkflowDetailById(strconv.Itoa(int(workflow.ID))) - if err != nil { - return nil, err - } - if !exist { - return nil, fmt.Errorf("workflow not exist by workflow.id(%v)", workflow.ID) - } - - return workflow, nil -} - -func (s *Storage) GetWorkflowDetailById(id string) (*Workflow, bool, error) { +func (s *Storage) GetWorkflowByProjectAndWorkflowId(projectId, workflowId string) (*Workflow, bool, error) { workflow := &Workflow{} - err := s.db.Preload("CreateUser", func(db *gorm.DB) *gorm.DB { return db.Unscoped() }). - Preload("Record").Preload("Project"). - Where("id = ?", id).First(workflow).Error + err := s.db.Preload("Record").Where("project_id = ?", projectId).Where("workflow_id = ?", workflowId). + First(&workflow).Error if err == gorm.ErrRecordNotFound { - return nil, false, nil - } - if err != nil { - return nil, false, errors.New(errors.ConnectStorageError, err) - } - if workflow.Record == nil { - return nil, false, errors.New(errors.DataConflict, fmt.Errorf("workflow record not exist")) - } - - instanceRecords, err := s.getWorkflowInstanceRecordsByRecordId(workflow.Record.ID) - if err != nil { - return nil, false, errors.New(errors.ConnectStorageError, err) + return workflow, false, nil } - workflow.Record.InstanceRecords = instanceRecords - steps, err := s.getWorkflowStepsByRecordIds([]uint{workflow.Record.ID}) - if err != nil { - return nil, false, errors.New(errors.ConnectStorageError, err) - } - workflow.Record.Steps = steps - for _, step := range steps { - if step.ID == workflow.Record.CurrentWorkflowStepId { - workflow.Record.CurrentStep = step - } - } - return workflow, true, nil + return workflow, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetWorkflowExportById(id string) (*Workflow, bool, error) { +func (s *Storage) GetWorkflowExportById(workflowId string) (*Workflow, bool, error) { w := new(Workflow) - err := s.db.Preload("CreateUser", UnScopedFunc). - Preload("Record").Where("id = ?", id).First(&w).Error + err := s.db.Preload("Record").Where("workflow_id = ?", workflowId).First(&w).Error if err == gorm.ErrRecordNotFound { return nil, false, nil } @@ -849,8 +767,7 @@ func (s *Storage) GetWorkflowExportById(id string) (*Workflow, bool, error) { } instanceRecordList := make([]*WorkflowInstanceRecord, 0) - err = s.db.Preload("Instance", UnScopedFunc).Preload("Task"). - Preload("User", UnScopedFunc). + err = s.db.Preload("Task"). Where("workflow_record_id = ?", w.Record.ID). Find(&instanceRecordList).Error if err != nil { @@ -867,9 +784,7 @@ func (s *Storage) GetWorkflowExportById(id string) (*Workflow, bool, error) { w.Record.InstanceRecords = instanceRecordList steps := make([]*WorkflowStep, 0) - err = s.db.Where("workflow_record_id = ?", w.Record.ID). - Preload("OperationUser", UnScopedFunc). - Find(&steps).Error + err = s.db.Where("workflow_record_id = ?", w.Record.ID).Find(&steps).Error if err != nil { return nil, false, errors.New(errors.ConnectStorageError, err) } @@ -878,49 +793,13 @@ func (s *Storage) GetWorkflowExportById(id string) (*Workflow, bool, error) { return w, true, nil } -func (s *Storage) GetWorkflowDetailBySubject(projectName, workflowName string) (*Workflow, bool, error) { +func (s *Storage) GetWorkflowDetailWithoutInstancesByWorkflowID(projectId, workflowID string) (*Workflow, bool, error) { workflow := &Workflow{} - err := s.db.Model(&Workflow{}).Preload("CreateUser", func(db *gorm.DB) *gorm.DB { return db.Unscoped() }). - Preload("Record").Joins("left join projects on workflows.project_id = projects.id"). - Where("subject = ?", workflowName). - Where("projects.name = ?", projectName). - First(workflow).Error - if err == gorm.ErrRecordNotFound { - return nil, false, nil - } - if err != nil { - return nil, false, errors.New(errors.ConnectStorageError, err) - } - if workflow.Record == nil { - return nil, false, errors.New(errors.DataConflict, fmt.Errorf("workflow record not exist")) - } - - instanceRecords, err := s.getWorkflowInstanceRecordsByRecordId(workflow.Record.ID) - if err != nil { - return nil, false, errors.New(errors.ConnectStorageError, err) - } - workflow.Record.InstanceRecords = instanceRecords - - steps, err := s.getWorkflowStepsByRecordIds([]uint{workflow.Record.ID}) - if err != nil { - return nil, false, errors.New(errors.ConnectStorageError, err) + db := s.db.Model(&Workflow{}).Preload("Record").Where("workflow_id = ?", workflowID) + if projectId != "" { + db = db.Where("project_id = ?", projectId) } - workflow.Record.Steps = steps - for _, step := range steps { - if step.ID == workflow.Record.CurrentWorkflowStepId { - workflow.Record.CurrentStep = step - } - } - return workflow, true, nil -} - -func (s *Storage) GetWorkflowDetailByWorkflowID(projectName, workflowID string) (*Workflow, bool, error) { - workflow := &Workflow{} - err := s.db.Model(&Workflow{}).Preload("CreateUser", func(db *gorm.DB) *gorm.DB { return db.Unscoped() }). - Preload("Record").Joins("left join projects on workflows.project_id = projects.id"). - Where("workflow_id = ?", workflowID). - Where("projects.name = ?", projectName). - First(workflow).Error + err := db.First(workflow).Error if err == gorm.ErrRecordNotFound { return nil, false, nil } @@ -950,7 +829,7 @@ func (s *Storage) GetWorkflowDetailByWorkflowID(projectName, workflowID string) return workflow, true, nil } -func (s *Storage) GetWorkflowHistoryById(id string) ([]*WorkflowRecord, error) { +func (s *Storage) GetWorkflowHistoryById(id uint) ([]*WorkflowRecord, error) { records := []*WorkflowRecord{} err := s.db.Model(&WorkflowRecord{}).Select("workflow_records.*"). Joins("JOIN workflow_record_history AS wrh ON workflow_records.id = wrh.workflow_record_id"). @@ -1029,7 +908,7 @@ func (s *Storage) DeleteWorkflow(workflow *Workflow) error { } func (s *Storage) deleteWorkflow(tx *gorm.DB, workflow *Workflow) error { - err := tx.Exec("DELETE FROM workflows WHERE id = ?", workflow.ID).Error + err := tx.Exec("DELETE FROM workflows WHERE workflow_id = ?", workflow.WorkflowId).Error if err != nil { return err } @@ -1037,7 +916,7 @@ func (s *Storage) deleteWorkflow(tx *gorm.DB, workflow *Workflow) error { if err != nil { return err } - err = tx.Exec("DELETE FROM workflow_steps WHERE workflow_id = ?", workflow.ID).Error + err = tx.Exec("DELETE FROM workflow_steps WHERE workflow_id = ?", workflow.WorkflowId).Error if err != nil { return err } @@ -1054,7 +933,7 @@ func (s *Storage) deleteWorkflow(tx *gorm.DB, workflow *Workflow) error { func (s *Storage) GetExpiredWorkflows(start time.Time) ([]*Workflow, error) { workflows := []*Workflow{} - err := s.db.Model(&Workflow{}).Select("workflows.id, workflows.workflow_record_id"). + err := s.db.Model(&Workflow{}).Select("workflows.id,workflows.workflow_id, workflows.workflow_record_id"). Joins("LEFT JOIN workflow_records ON workflows.workflow_record_id = workflow_records.id"). Where("workflows.created_at < ? "+ "AND (workflow_records.status = 'finished' "+ @@ -1067,7 +946,7 @@ func (s *Storage) GetExpiredWorkflows(start time.Time) ([]*Workflow, error) { func (s *Storage) GetNeedScheduledWorkflows() ([]*Workflow, error) { workflows := []*Workflow{} - err := s.db.Model(&Workflow{}).Select("workflows.id, workflows.workflow_record_id"). + err := s.db.Model(&Workflow{}).Select("workflows.id,workflows.workflow_id, workflows.workflow_record_id"). Joins("LEFT JOIN workflow_records ON workflows.workflow_record_id = workflow_records.id"). Joins("LEFT JOIN workflow_instance_records ON workflow_records.id = workflow_instance_records.workflow_record_id"). Where("workflow_records.status = 'wait_for_execution' "+ @@ -1087,7 +966,7 @@ func (s *Storage) GetWorkflowBySubject(subject string) (*Workflow, bool, error) return workflow, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) IsWorkflowUnFinishedByInstanceId(instanceId uint) (bool, error) { +func (s *Storage) IsWorkflowUnFinishedByInstanceId(instanceId int64) (bool, error) { count := 0 err := s.db.Table("workflow_records"). Joins("LEFT JOIN workflow_instance_records ON workflow_records.id = workflow_instance_records.workflow_record_id"). @@ -1098,21 +977,26 @@ func (s *Storage) IsWorkflowUnFinishedByInstanceId(instanceId uint) (bool, error return count > 0, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetInstancesByWorkflowID(workflowID uint) ([]*Instance, error) { +func (s *Storage) GetInstanceIdsByWorkflowID(workflowID string) ([]uint64, error) { query := ` -SELECT instances.id ,instances.maintenance_period +SELECT wir.instance_id id FROM workflows AS w LEFT JOIN workflow_records AS wr ON wr.id = w.workflow_record_id LEFT JOIN workflow_instance_records AS wir ON wr.id = wir.workflow_record_id -LEFT JOIN instances ON instances.id = wir.instance_id WHERE -w.id = ?` +w.workflow_id = ?` instances := []*Instance{} err := s.db.Raw(query, workflowID).Scan(&instances).Error if err != nil { return nil, errors.ConnectStorageErrWrapper(err) } - return instances, err + + instanceIds := make([]uint64, 0, len(instances)) + for _, instance := range instances { + instanceIds = append(instanceIds, instance.ID) + } + + return instanceIds, err } // GetWorkFlowStepIdsHasAudit 返回走完所有审核流程的workflow_steps的id @@ -1201,15 +1085,14 @@ func (s *Storage) GetWorkflowCountByStatus(status string) (int, error) { } // 执行成功, 执行失败, 已取消三种工单会被当作已结束工单 -func (s *Storage) HasNotEndWorkflowByProjectName(projectName string) (bool, error) { +func (s *Storage) HasNotEndWorkflowByProjectId(projectId string) (bool, error) { endStatus := []string{WorkflowStatusExecFailed, WorkflowStatusFinish, WorkflowStatusCancel} var count int err := s.db.Table("workflows"). Joins("LEFT JOIN workflow_records ON workflows.workflow_record_id = workflow_records.id"). - Joins("LEFT JOIN projects ON projects.id = workflows.project_id"). Where("workflow_records.status NOT IN (?)", endStatus). - Where("projects.name = ?", projectName). + Where("workflows.project_id = ?", projectId). Count(&count).Error return count > 0, err } @@ -1259,20 +1142,20 @@ func (s *Storage) GetWorkflowDailyCountBetweenStartTimeAndEndTime(startTime, end } type WorkflowTasksSummaryDetail struct { - WorkflowRecordStatus string `json:"workflow_record_status"` - TaskId uint `json:"task_id"` - TaskExecStartAt *time.Time `json:"task_exec_start_at"` - TaskExecEndAt *time.Time `json:"task_exec_end_at"` - TaskPassRate float64 `json:"task_pass_rate"` - TaskScore int32 `json:"task_score"` - TaskStatus string `json:"task_status"` - InstanceName string `json:"instance_name"` - InstanceDeletedAt *time.Time `json:"instance_deleted_at"` - InstanceMaintenancePeriod Periods `json:"instance_maintenance_period" gorm:"text"` - InstanceScheduledAt *time.Time `json:"instance_scheduled_at"` - ExecutionUserDeletedAt *time.Time `json:"execution_user_deleted_at"` - ExecutionUserName string `json:"execution_user_name"` - CurrentStepAssigneeUsers RowList `json:"current_step_assignee_users"` + WorkflowRecordStatus string `json:"workflow_record_status"` + TaskId uint `json:"task_id"` + TaskExecStartAt *time.Time `json:"task_exec_start_at"` + TaskExecEndAt *time.Time `json:"task_exec_end_at"` + TaskPassRate float64 `json:"task_pass_rate"` + TaskScore int32 `json:"task_score"` + TaskStatus string `json:"task_status"` + InstanceId uint64 `json:"instance_id"` + InstanceName string `json:"instance_name"` + InstanceDeletedAt *time.Time `json:"instance_deleted_at"` + InstanceMaintenancePeriod Periods `json:"instance_maintenance_period" gorm:"text"` + InstanceScheduledAt *time.Time `json:"instance_scheduled_at"` + ExecutionUserId string `json:"execution_user_id"` + CurrentStepAssigneeUserIds sql.NullString `json:"current_step_assignee_user_ids"` } var workflowStepSummaryQueryTpl = ` @@ -1283,16 +1166,16 @@ SELECT wr.status AS workflow tasks.pass_rate AS task_pass_rate, tasks.score AS task_score, tasks.status AS task_status, - inst.name AS instance_name, - inst.deleted_at AS instance_deleted_at, - inst.maintenance_period AS instance_maintenance_period, + tasks.instance_id AS instance_id, wir.scheduled_at AS instance_scheduled_at, - exec_user.deleted_at AS execution_user_deleted_at, - COALESCE(exec_user.login_name, '') AS execution_user_name, - GROUP_CONCAT(DISTINCT COALESCE(curr_ass_user.login_name, '')) AS current_step_assignee_users + wir.execution_user_id AS execution_user_id, + curr_ws.assignees AS current_step_assignee_user_ids {{- template "body" . -}} -GROUP BY tasks.id, wir.id +{{- if .is_executing }} +ORDER BY curr_ws.id DESC +LIMIT 1 +{{- end }} ` var workflowStepSummaryQueryBodyTplV2 = ` @@ -1300,18 +1183,14 @@ var workflowStepSummaryQueryBodyTplV2 = ` FROM workflow_instance_records AS wir LEFT JOIN workflow_records AS wr ON wir.workflow_record_id = wr.id LEFT JOIN workflows AS w ON w.workflow_record_id = wr.id -LEFT JOIN projects ON projects.id = w.project_id -LEFT JOIN users AS exec_user ON wir.execution_user_id = exec_user.id LEFT JOIN tasks ON wir.task_id = tasks.id -LEFT JOIN instances AS inst ON tasks.instance_id = inst.id LEFT JOIN workflow_steps AS curr_ws ON wr.current_workflow_step_id = curr_ws.id -LEFT JOIN workflow_step_user AS curr_ws_user ON curr_ws.id = curr_ws_user.workflow_step_id -LEFT JOIN users AS curr_ass_user ON curr_ws_user.user_id = curr_ass_user.id + WHERE w.deleted_at IS NULL AND w.workflow_id = :workflow_id -AND projects.name = :project_name +AND w.project_id = :project_id {{ end }} ` @@ -1319,8 +1198,8 @@ AND projects.name = :project_name func (s *Storage) GetWorkflowStepSummaryByReqV2(data map[string]interface{}) ( result []*WorkflowTasksSummaryDetail, err error) { - if data["workflow_id"] == nil || data["project_name"] == nil { - return result, errors.New(errors.DataInvalid, fmt.Errorf("project name and workflow name must be specified")) + if data["workflow_id"] == nil || data["project_id"] == nil { + return result, errors.New(errors.DataInvalid, fmt.Errorf("project id and workflow name must be specified")) } err = s.getListResult(workflowStepSummaryQueryBodyTplV2, workflowStepSummaryQueryTpl, data, &result) @@ -1339,16 +1218,12 @@ SELECT wr.status A tasks.pass_rate AS task_pass_rate, tasks.score AS task_score, tasks.status AS task_status, - inst.name AS instance_name, - inst.deleted_at AS instance_deleted_at, - inst.maintenance_period AS instance_maintenance_period, + tasks.instance_id AS instance_id, wir.scheduled_at AS instance_scheduled_at, - exec_user.deleted_at AS execution_user_deleted_at, - COALESCE(exec_user.login_name, '') AS execution_user_name, + wir.execution_user_id AS execution_user_id, IF(tasks.status = 'audited' || tasks.status = 'executing' || - tasks.status = 'terminating', GROUP_CONCAT(ass_user.login_name), '') AS current_step_assignee_users + tasks.status = 'terminating', wir.execution_assignees, '') AS current_step_assignee_user_ids {{- template "body" . -}} -GROUP BY tasks.id, wir.id ` var workflowTaskSummaryQueryBodyTpl = ` @@ -1356,20 +1231,15 @@ var workflowTaskSummaryQueryBodyTpl = ` FROM workflow_instance_records AS wir LEFT JOIN workflow_records AS wr ON wir.workflow_record_id = wr.id LEFT JOIN workflows AS w ON w.workflow_record_id = wr.id - LEFT JOIN projects ON projects.id = w.project_id - LEFT JOIN users AS exec_user ON wir.execution_user_id = exec_user.id LEFT JOIN tasks ON wir.task_id = tasks.id - LEFT JOIN instances AS inst ON tasks.instance_id = inst.id - LEFT JOIN workflow_instance_record_user wiru ON wir.id = wiru.workflow_instance_record_id - LEFT JOIN users ass_user ON ass_user.id = wiru.user_id -WHERE w.deleted_at IS NULL - AND w.workflow_id = :workflow_id - AND projects.name = :project_name + WHERE w.deleted_at IS NULL + AND w.workflow_id = :workflow_id + AND w.project_id = :project_id {{ end }} ` func (s *Storage) GetWorkflowTaskSummaryByReq(data map[string]interface{}) (result []*WorkflowTasksSummaryDetail, err error) { - if data["workflow_id"] == nil || data["project_name"] == nil { + if data["workflow_id"] == nil || data["project_id"] == nil { return result, errors.New(errors.DataInvalid, fmt.Errorf("project name and workflow name must be specified")) } @@ -1393,24 +1263,10 @@ func (s *Storage) GetTasksByWorkFlowRecordID(id uint) ([]*Task, error) { return tasks, nil } -func (s *Storage) GetWorkflowByProjectAndWorkflowName(projectName, workflowName string) (*Workflow, bool, error) { +func (s *Storage) GetWorkflowByProjectAndWorkflowName(projectId, workflowName string) (*Workflow, bool, error) { workflow := &Workflow{} - err := s.db.Model(&Workflow{}).Joins("left join projects on workflows.project_id = projects.id"). - Where("projects.name = ?", projectName). - Where("workflows.subject = ?", workflowName). - First(&workflow).Error - if err == gorm.ErrRecordNotFound { - return workflow, false, nil - } - - return workflow, true, errors.New(errors.ConnectStorageError, err) -} - -func (s *Storage) GetWorkflowByProjectNameAndWorkflowId(projectName, workflowId string) (*Workflow, bool, error) { - workflow := &Workflow{} - err := s.db.Model(&Workflow{}).Preload("Record").Joins("left join projects on workflows.project_id = projects.id"). - Where("projects.name = ?", projectName). - Where("workflows.workflow_id = ?", workflowId). + err := s.db.Model(&Workflow{}).Where("project_id = ?", projectId). + Where("subject = ?", workflowName). First(&workflow).Error if err == gorm.ErrRecordNotFound { return workflow, false, nil @@ -1419,7 +1275,7 @@ func (s *Storage) GetWorkflowByProjectNameAndWorkflowId(projectName, workflowId return workflow, true, errors.New(errors.ConnectStorageError, err) } -func (s *Storage) GetWorkflowsByProjectID(projectID uint) ([]*Workflow, error) { +func (s *Storage) GetWorkflowsByProjectID(projectID ProjectUID) ([]*Workflow, error) { workflows := []*Workflow{} err := s.db.Model(&Workflow{}).Where("project_id = ?", projectID).Scan(&workflows).Error return workflows, errors.ConnectStorageErrWrapper(err) @@ -1436,22 +1292,21 @@ func (s *Storage) GetWorkflowNamesByIDs(ids []string) ([]string, error) { } type WorkflowStatusDetail struct { - Subject string `json:"subject"` - WorkflowId string `json:"workflow_id"` - Status string `json:"status"` - LoginName string `json:"login_name"` - UpdatedAt *time.Time `json:"updated_at"` + Subject string `json:"subject"` + WorkflowId string `json:"workflow_id"` + Status string `json:"status"` + CreateUserId string `json:"create_user_id"` + LoginName string `json:"login_name"` + UpdatedAt *time.Time `json:"updated_at"` } -func (s *Storage) GetProjectWorkflowStatusDetail(projectName string, queryStatus []string) ([]WorkflowStatusDetail, error) { +func (s *Storage) GetProjectWorkflowStatusDetail(projectUid string, queryStatus []string) ([]WorkflowStatusDetail, error) { WorkflowStatusDetails := []WorkflowStatusDetail{} err := s.db.Model(&Workflow{}). - Select("workflows.subject, workflows.workflow_id, wr.status, wr.updated_at, users.login_name"). + Select("workflows.subject, workflows.workflow_id, wr.status, wr.updated_at, workflows.create_user_id"). Joins("left join workflow_records wr on workflows.workflow_record_id = wr.id"). - Joins("left join users on users.id=workflows.create_user_id"). - Joins("left join projects on projects.id=workflows.project_id"). - Where("wr.status in (?) and projects.name=?", queryStatus, projectName). + Where("wr.status in (?) and workflows.project_id=?", queryStatus, projectUid). Order("wr.updated_at desc"). Scan(&WorkflowStatusDetails).Error if err != nil { @@ -1465,25 +1320,23 @@ type SqlCountAndTriggerRuleCount struct { TriggerRuleCount uint `json:"trigger_rule_count"` } -func (s *Storage) GetSqlCountAndTriggerRuleCountFromWorkflowByProject(projectName string) (SqlCountAndTriggerRuleCount, error) { +func (s *Storage) GetSqlCountAndTriggerRuleCountFromWorkflowByProject(projectUid string) (SqlCountAndTriggerRuleCount, error) { sqlCountAndTriggerRuleCount := SqlCountAndTriggerRuleCount{} err := s.db.Model(&Workflow{}). Select("count(1) sql_count, count(case when JSON_TYPE(execute_sql_detail.audit_results)<>'NULL' then 1 else null end) trigger_rule_count"). Joins("left join workflow_instance_records on workflows.workflow_record_id=workflow_instance_records.workflow_record_id"). Joins("left join tasks on workflow_instance_records.task_id=tasks.id"). Joins("left join execute_sql_detail on execute_sql_detail.task_id=tasks.id"). - Joins("left join projects on projects.id=workflows.project_id"). - Where("projects.name=?", projectName). + Where("workflows.project_id=?", projectUid). Scan(&sqlCountAndTriggerRuleCount).Error return sqlCountAndTriggerRuleCount, errors.ConnectStorageErrWrapper(err) } -func (s *Storage) GetWorkflowCountByStatusAndProject(status string, projectName string) (int, error) { +func (s *Storage) GetWorkflowCountByStatusAndProject(status string, projectUid string) (int, error) { var count int err := s.db.Table("workflows"). Joins("left join workflow_records on workflows.workflow_record_id = workflow_records.id"). - Joins("left join projects on projects.id=workflows.project_id"). - Where("workflow_records.status = ? and projects.name=?", status, projectName). + Where("workflow_records.status = ? and workflows.project_id=?", status, projectUid). Count(&count).Error if err != nil { return 0, errors.New(errors.ConnectStorageError, err) diff --git a/sqle/model/workflow_list.go b/sqle/model/workflow_list.go index f5012a00d9..7cfcdb356e 100644 --- a/sqle/model/workflow_list.go +++ b/sqle/model/workflow_list.go @@ -3,36 +3,34 @@ package model import ( "database/sql" "time" - - "github.com/actiontech/sqle/sqle/utils" ) type WorkflowListDetail struct { - ProjectName string `json:"project_name"` - Subject string `json:"subject"` - WorkflowId string `json:"workflow_id"` - Desc string `json:"desc"` - CreateUser sql.NullString `json:"create_user_name"` - CreateUserDeletedAt *time.Time `json:"create_user_deleted_at"` - CreateTime *time.Time `json:"create_time"` - CurrentStepType sql.NullString `json:"current_step_type" enums:"sql_review,sql_execute"` - CurrentStepAssigneeUser RowList `json:"current_step_assignee_user_name_list"` - Status string `json:"status"` - TaskInstanceType RowList `json:"task_instance_type"` + ProjectId string `json:"project_id"` + Subject string `json:"subject"` + WorkflowId string `json:"workflow_id"` + Desc string `json:"desc"` + CreateUser sql.NullString `json:"create_user_id"` + CreateUserDeletedAt *time.Time `json:"create_user_deleted_at"` + CreateTime *time.Time `json:"create_time"` + CurrentStepType sql.NullString `json:"current_step_type" enums:"sql_review,sql_execute"` + CurrentStepAssigneeUserIds sql.NullString `json:"current_step_assignee_user_id_list"` + Status string `json:"status"` + TaskInstanceType RowList `json:"task_instance_type"` } var workflowsQueryTpl = ` -SELECT p.name AS project_name, +SELECT + w.project_id, w.subject, w.workflow_id, w.desc, - create_user.login_name AS create_user_name, - create_user.deleted_at AS create_user_deleted_at, + w.create_user_id, + CAST("" AS DATETIME) AS create_user_deleted_at, w.created_at AS create_time, curr_wst.type AS current_step_type, - GROUP_CONCAT(DISTINCT COALESCE(curr_ass_user.login_name, '')) AS current_step_assignee_user_name_list, - wr.status, - GROUP_CONCAT(inst.db_type) AS task_instance_type + curr_ws.assignees AS current_step_assignee_user_id_list, + wr.status {{- template "body" . -}} GROUP BY w.id ORDER BY w.id DESC @@ -56,25 +54,15 @@ ORDER BY w.id DESC var workflowsQueryBodyTpl = ` {{ define "body" }} FROM workflows w -LEFT JOIN projects AS p ON w.project_id = p.id -LEFT JOIN users AS create_user ON w.create_user_id = create_user.id LEFT JOIN workflow_records AS wr ON w.workflow_record_id = wr.id LEFT JOIN workflow_instance_records wir on wir.workflow_record_id = wr.id LEFT JOIN tasks ON wir.task_id = tasks.id -LEFT JOIN instances AS inst ON tasks.instance_id = inst.id LEFT JOIN workflow_steps AS curr_ws ON wr.current_workflow_step_id = curr_ws.id LEFT JOIN workflow_step_templates AS curr_wst ON curr_ws.workflow_step_template_id = curr_wst.id -LEFT JOIN workflow_step_user AS curr_wst_re_user ON curr_ws.id = curr_wst_re_user.workflow_step_id -LEFT JOIN users AS curr_ass_user ON curr_wst_re_user.user_id = curr_ass_user.id -LEFT JOIN workflow_instance_record_user wiru ON wiru.workflow_instance_record_id = wir.id -LEFT JOIN users inst_assign_user ON inst_assign_user.id = wiru.user_id {{- if .check_user_can_access }} LEFT JOIN workflow_steps AS all_ws ON w.id = all_ws.workflow_id AND all_ws.state !='initialized' LEFT JOIN workflow_step_templates AS all_wst ON all_ws.workflow_step_template_id = all_wst.id -LEFT JOIN workflow_step_user AS all_wst_re_user ON all_ws.id = all_wst_re_user.workflow_step_id -LEFT JOIN users AS all_ass_user ON all_wst_re_user.user_id = all_ass_user.id -LEFT JOIN workflow_instance_record_user all_wiru ON all_wiru.workflow_instance_record_id = wir.id {{- end }} WHERE w.deleted_at IS NULL @@ -82,14 +70,14 @@ w.deleted_at IS NULL {{- if .check_user_can_access }} AND ( w.create_user_id = :current_user_id -OR curr_ass_user.id = :current_user_id -OR all_ass_user.id = :current_user_id +OR all_ws.assignees REGEXP :current_user_id +OR curr_ws.assignees REGEXP :current_user_id OR IF(wr.status = 'wait_for_execution' - , all_wiru.user_id = :current_user_id - , '') + , wir.execution_assignees REGEXP :current_user_id + , '') {{- if .viewable_instance_ids }} -OR inst.id IN ( {{ .viewable_instance_ids }}) +OR tasks.instance_id IN ( {{ .viewable_instance_ids }}) {{- end }} ) @@ -115,8 +103,8 @@ AND tasks.exec_start_at > :filter_task_execute_start_time_from AND tasks.exec_start_at < :filter_task_execute_start_time_to {{- end }} -{{- if .filter_create_user_name }} -AND create_user.login_name = :filter_create_user_name +{{- if .filter_create_user_id }} +AND w.create_user_id = :filter_create_user_id {{- end }} {{- if .filter_current_step_type }} @@ -127,10 +115,10 @@ AND curr_wst.type = :filter_current_step_type AND wr.status IN (:filter_status) {{- end }} -{{- if .filter_current_step_assignee_user_name }} -AND (curr_ass_user.login_name = :filter_current_step_assignee_user_name +{{- if .filter_current_step_assignee_user_id }} +AND (curr_ws.assignees REGEXP :filter_current_step_assignee_user_id OR IF(wr.status = 'wait_for_execution' - , inst_assign_user.login_name = :filter_current_step_assignee_user_name + , wir.execution_assignees REGEXP :filter_current_step_assignee_user_id , '') ) {{- end }} @@ -147,34 +135,21 @@ AND inst.name = :filter_task_instance_name AND w.workflow_id = :filter_workflow_id {{- end }} -{{- if .fuzzy_search_workflow_desc }} -AND w.desc LIKE '%{{ .fuzzy_search_workflow_desc }}%' +{{- if .filter_project_id }} +AND w.project_id = :filter_project_id {{- end }} -{{- if .filter_project_name }} -AND p.name = :filter_project_name +{{- if .fuzzy_keyword }} +AND (w.subject like :fuzzy_keyword or w.workflow_id like :fuzzy_keyword or w.desc like :fuzzy_keyword) {{- end }} {{ end }} ` -func (s *Storage) GetWorkflowsByReq(data map[string]interface{}, user *User) ( +func (s *Storage) GetWorkflowsByReq(data map[string]interface{}) ( result []*WorkflowListDetail, count uint64, err error) { - var ids []uint - { - instances, err := s.GetUserCanOpInstances(user, []uint{OP_WORKFLOW_VIEW_OTHERS}) - if err != nil { - return result, 0, err - } - ids = getInstanceIDsFromInstances(instances) - } - - if len(ids) > 0 { - data["viewable_instance_ids"] = utils.JoinUintSliceToString(ids, ", ") - } - err = s.getListResult(workflowsQueryBodyTpl, workflowsQueryTpl, data, &result) if err != nil { return result, 0, err @@ -189,15 +164,16 @@ func (s *Storage) GetWorkflowCountByReq(data map[string]interface{}) (uint64, er return s.getCountResult(workflowsQueryBodyTpl, workflowsCountTpl, data) } -func (s *Storage) GetWorkflowTotalByProjectName(projectName string) (uint64, error) { - data := map[string]interface{}{ - "filter_project_name": projectName, - } - return s.GetWorkflowCountByReq(data) -} +// func (s *Storage) GetWorkflowTotalByProjectId(projectId string) (uint64, error) { +// data := map[string]interface{}{ +// "filter_project_id": projectId, +// } +// return s.GetWorkflowCountByReq(data) +// } +// dms-todo: using project id as name, 临时方案 var projectWorkflowCountTpl = ` -SELECT p.name AS project_name, COUNT(DISTINCT w.id) AS workflow_count +SELECT w.project_id AS project_name, COUNT(DISTINCT w.id) AS workflow_count {{- template "body" . -}} GROUP BY p.name ` @@ -255,19 +231,6 @@ func (s *Storage) GetWorkflowTemplatesByReq(data map[string]interface{}) ( } func (s *Storage) GetExportWorkflowIDListByReq(data map[string]interface{}, user *User) (idList []string, err error) { - var ids []uint - { - instances, err := s.GetUserCanOpInstances(user, []uint{OP_WORKFLOW_VIEW_OTHERS}) - if err != nil { - return idList, err - } - ids = getInstanceIDsFromInstances(instances) - } - - if len(ids) > 0 { - data["viewable_instance_ids"] = utils.JoinUintSliceToString(ids, ", ") - } - err = s.getListResult(workflowsQueryBodyTpl, exportWorkflowIDListTpl, data, &idList) if err != nil { return idList, err diff --git a/sqle/notification/email.go b/sqle/notification/email.go deleted file mode 100644 index dce125a8a2..0000000000 --- a/sqle/notification/email.go +++ /dev/null @@ -1,67 +0,0 @@ -package notification - -import ( - "crypto/tls" - "fmt" - "strconv" - "strings" - - "github.com/actiontech/sqle/sqle/model" - - "gopkg.in/gomail.v2" -) - -func init() { - Notifiers = append(Notifiers, &EmailNotifier{}) -} - -type EmailNotifier struct{} - -func (n *EmailNotifier) Notify(notification Notification, users []*model.User) error { - // workflow has been finished. - if len(users) == 0 { - return nil - } - - var emails []string - for _, user := range users { - if user.Email != "" { - emails = append(emails, user.Email) - } - } - - // no user has configured email, don't send. - if len(emails) == 0 { - return nil - } - - s := model.GetStorage() - smtpC, exist, err := s.GetSMTPConfiguration() - if err != nil { - return err - } - if !exist { - return nil - } - - if !smtpC.EnableSMTPNotify.Bool { - return nil - } - - message := gomail.NewMessage() - message.SetHeader("From", smtpC.Username) - message.SetHeader("To", emails...) - message.SetHeader("Subject", notification.NotificationSubject()) - body := notification.NotificationBody() - message.SetBody("text/html", strings.Replace(body, "\n", "
\n", -1)) - - port, _ := strconv.Atoi(smtpC.Port) - dialer := gomail.NewDialer(smtpC.Host, port, smtpC.Username, smtpC.Password) - if smtpC.IsSkipVerify { - dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true} - } - if err := dialer.DialAndSend(message); err != nil { - return fmt.Errorf("send email to %v error: %v", emails, err) - } - return nil -} diff --git a/sqle/notification/feishu.go b/sqle/notification/feishu.go deleted file mode 100644 index 3cf5594fee..0000000000 --- a/sqle/notification/feishu.go +++ /dev/null @@ -1,91 +0,0 @@ -package notification - -import ( - "fmt" - "strings" - - "github.com/actiontech/sqle/sqle/log" - "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/pkg/im/feishu" - larkContact "github.com/larksuite/oapi-sdk-go/v3/service/contact/v3" - larkIm "github.com/larksuite/oapi-sdk-go/v3/service/im/v1" -) - -func init() { - Notifiers = append(Notifiers, &FeishuNotifier{}) -} - -type FeishuNotifier struct{} - -func (n *FeishuNotifier) Notify(notification Notification, users []*model.User) error { - // workflow has been finished. - if len(users) == 0 { - return nil - } - - s := model.GetStorage() - cfg, exist, err := s.GetImConfigByType(model.ImTypeFeishu) - if err != nil { - return fmt.Errorf("get im config failed: %v", err) - } - if !exist { - return nil - } - - if !cfg.IsEnable { - return nil - } - - // 通过邮箱、手机从飞书获取用户ids - var emails, mobiles []string - userCount := 0 - for _, u := range users { - if u.Email == "" && u.Phone == "" { - continue - } - if u.Email != "" { - emails = append(emails, u.Email) - } - if u.Phone != "" { - mobiles = append(mobiles, u.Phone) - } - userCount++ - if userCount == feishu.MaxCountOfIdThatUsedToFindUser { - break - } - } - - client := feishu.NewFeishuClient(cfg.AppKey, cfg.AppSecret) - feishuUsers, err := client.GetUsersByEmailOrMobileWithLimitation(emails, mobiles, larkContact.UserIdTypeGetUserUserId) - if err != nil { - return fmt.Errorf("get user_ids from feishu failed: %v", err) - } - - content, err := BuildFeishuMessageBody(notification) - if err != nil { - return fmt.Errorf("convert content failed: %v", err) - } - errMsgs := []string{} - l := log.NewEntry() - for id, u := range feishuUsers { - l.Infof("send message to feishu, email=%v, phone=%v, userId=%v", u.Email, u.Mobile, id) - if err = client.SendMessage(feishu.FeishuReceiverIdTypeUserId, id, feishu.FeishuSendMessageMsgTypePost, content); err != nil { - errMsgs = append(errMsgs, fmt.Sprintf("send message to feishu failed: %v; email=%v; phone=%v", err, u.Email, u.Mobile)) - } - } - if len(errMsgs) > 0 { - return fmt.Errorf(strings.Join(errMsgs, "\n")) - } - return nil -} - -func BuildFeishuMessageBody(n Notification) (string, error) { - zhCnPostText := &larkIm.MessagePostText{Text: n.NotificationBody()} - zhCnMessagePostContent := &larkIm.MessagePostContent{Title: n.NotificationSubject(), Content: [][]larkIm.MessagePostElement{{zhCnPostText}}} - messagePostText := &larkIm.MessagePost{ZhCN: zhCnMessagePostContent} - content, err := messagePostText.String() - if err != nil { - return "", err - } - return content, nil -} diff --git a/sqle/notification/notification.go b/sqle/notification/notification.go index f3425b4d45..f75bb6c1d7 100644 --- a/sqle/notification/notification.go +++ b/sqle/notification/notification.go @@ -2,15 +2,19 @@ package notification import ( "bytes" + "context" "fmt" "strings" "sync" "time" + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/dms" driverV2 "github.com/actiontech/sqle/sqle/driver/v2" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/notification/webhook" ) type Notification interface { @@ -26,16 +30,14 @@ type WorkflowNotifyConfig struct { SQLEUrl *string } -var Notifiers = []Notifier{} - -func Notify(notification Notification, users []*model.User) error { - for _, n := range Notifiers { - err := n.Notify(notification, users) - if err != nil { - return err - } - } - return nil +func Notify(notification Notification, userIds []string) error { + return dmsobject.Notify(context.TODO(), controller.GetDMSServerAddress(), v1.NotificationReq{ + Notification: &v1.Notification{ + NotificationSubject: notification.NotificationSubject(), + NotificationBody: notification.NotificationBody(), + UserUids: userIds, + }, + }) } type WorkflowNotifyType int @@ -118,7 +120,7 @@ func (w *WorkflowNotification) NotificationBody() string { w.workflow.Subject, w.workflow.WorkflowId, w.workflow.Desc, - w.workflow.CreateUserName(), + dms.GetUserNameWithDelTag(w.workflow.CreateUserId), w.workflow.CreatedAt) } @@ -132,21 +134,41 @@ func (w *WorkflowNotification) NotificationBody() string { w.workflow.Subject, w.workflow.WorkflowId, w.workflow.Desc, - w.workflow.CreateUserName(), + dms.GetUserNameWithDelTag(w.workflow.CreateUserId), w.workflow.CreatedAt) buf.WriteString(head) if w.config.SQLEUrl != nil { buf.WriteString(fmt.Sprintf("\n- 工单链接: %v/project/%v/order/%v", strings.TrimRight(*w.config.SQLEUrl, "/"), - w.workflow.Project.Name, + w.workflow.ProjectId, w.workflow.WorkflowId, )) } else { buf.WriteString("\n- 工单链接: 请在系统设置-全局配置中补充全局url") } + instanceIds := make([]uint64, 0, len(tasks)) + for _, task := range tasks { + instanceIds = append(instanceIds, task.InstanceId) + } + + instances, err := dms.GetInstancesInProjectByIds(context.Background(), string(w.workflow.ProjectId), instanceIds) + if err != nil { + buf.WriteString(fmt.Sprintf("\n 获取数据源实例失败: %v\n", err)) + return buf.String() + } + + instanceMap := map[uint64]*model.Instance{} + for _, instance := range instances { + instanceMap[instance.ID] = instance + } + for _, t := range tasks { + if instance, ok := instanceMap[t.InstanceId]; ok { + t.Instance = instance + } + buf.WriteString("\n--------------\n") buf.WriteString(w.buildNotifyBody(t)) } @@ -207,40 +229,33 @@ func (w *WorkflowNotification) buildNotifyBody(task *model.Task) string { } } -func (w *WorkflowNotification) notifyUser() []*model.User { +func (w *WorkflowNotification) notifyUser() []string { switch w.notifyType { case WorkflowNotifyTypeApprove, WorkflowNotifyTypeCreate: return w.workflow.CurrentAssigneeUser() // if workflow is rejected, the creator needs to be notified. case WorkflowNotifyTypeReject: - return []*model.User{ - w.workflow.CreateUser, + return []string{ + w.workflow.CreateUserId, } // if workflow is executed, the creator and executor needs to be notified. case WorkflowNotifyTypeExecuteSuccess, WorkflowNotifyTypeExecuteFail: - users := []*model.User{ - w.workflow.CreateUser, + users := []string{ + w.workflow.CreateUserId, } - if executeUser := w.workflow.FinalStep().OperationUser; executeUser != nil { + if executeUser := w.workflow.FinalStep().OperationUserId; executeUser != "" { users = append(users, executeUser) } return users default: - return []*model.User{} + return []string{} } } func notifyWorkflowWebhook(workflow *model.Workflow, wt WorkflowNotifyType) { - cfg := webhook.WorkflowCfg - if cfg == nil { - log.NewEntry().Error("workflow webhook failed: config missing") - return - } - if !cfg.Enable { - return - } - err := workflowSendRequest(getWorkflowNotifyTypeAction(wt), workflow.Project.Name, workflow. + // dms-todo 使用projectid代替name + err := workflowSendRequest(getWorkflowNotifyTypeAction(wt), string(workflow.ProjectId), workflow. WorkflowId, workflow.Subject, workflow.Record.Status) if err != nil { log.NewEntry().Errorf("workflow webhook failed: %v", err) @@ -253,28 +268,26 @@ func notifyWorkflow(sqleUrl string, workflow *model.Workflow, wt WorkflowNotifyT config.SQLEUrl = &sqleUrl } wn := NewWorkflowNotification(workflow, wt, config) - users := wn.notifyUser() + userIds := wn.notifyUser() // workflow has been finished. - if len(users) == 0 { + if len(userIds) == 0 { return } - err := Notify(wn, users) + + err := Notify(wn, userIds) if err != nil { log.NewEntry().Errorf("notify workflow error, %v", err) } } -func NotifyWorkflow(workflowId string, wt WorkflowNotifyType) { +func NotifyWorkflow(projectId, workflowId string, wt WorkflowNotifyType) { s := model.GetStorage() - workflow, exist, err := s.GetWorkflowDetailById(workflowId) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectId, workflowId, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { - log.NewEntry().Errorf("notify workflow error, %v", err) - return - } - if !exist { log.NewEntry().Error("notify workflow error, workflow not exits") return } + go func() { notifyWorkflowWebhook(workflow, wt) }() sqleUrl, err := s.GetSqleUrl() @@ -329,10 +342,10 @@ func (a *AuditPlanNotification) NotificationBody() string { a.report.AuditLevel, )) - if a.config.SQLEUrl != nil && a.config.ProjectName != nil { + if a.config.SQLEUrl != nil && a.auditPlan.ProjectId != "" { builder.WriteString(fmt.Sprintf("\n- 扫描任务链接: %v/project/%v/auditPlan/detail/%v/report/%v", strings.TrimRight(*a.config.SQLEUrl, "/"), - *a.config.ProjectName, + a.auditPlan.ProjectId, a.auditPlan.Name, a.report.ID, )) @@ -358,10 +371,10 @@ func NotifyAuditPlan(auditPlanId uint, report *model.AuditPlanReportV2) error { if err != nil { return err } - ap.CreateUser, _, err = s.GetUserByID(ap.CreateUserID) - if err != nil { - return err - } + // ap.CreateUser, _, err = s.GetUserByID(ap.CreateUserID) + // if err != nil { + // return err + // } url, err := s.GetSqleUrl() if err != nil { return err @@ -371,11 +384,12 @@ func NotifyAuditPlan(auditPlanId uint, report *model.AuditPlanReportV2) error { if len(url) > 0 { config.SQLEUrl = &url - project, _, err := s.GetProjectByID(ap.ProjectId) - if err != nil { - return err - } - config.ProjectName = &project.Name + // dms-todo: 从 dms 获取 project 名称,但最终考虑将告警移走. + // project, _, err := s.GetProjectByID(ap.ProjectId) + // if err != nil { + // return err + // } + // config.ProjectName = &project.Name } if driverV2.RuleLevelLessOrEqual(ap.NotifyLevel, report.AuditLevel) { @@ -393,16 +407,16 @@ func GetAuditPlanNotifier() *AuditPlanNotifier { } type AuditPlanNotifier struct { - lastSend map[string] /*audit plan name*/ time.Time /*last send time*/ - mutex *sync.RWMutex - emailNotifier *EmailNotifier + lastSend map[string] /*audit plan name*/ time.Time /*last send time*/ + mutex *sync.RWMutex + // emailNotifier *EmailNotifier } func NewAuditPlanNotifier() *AuditPlanNotifier { return &AuditPlanNotifier{ - lastSend: map[string]time.Time{}, - mutex: &sync.RWMutex{}, - emailNotifier: &EmailNotifier{}, + lastSend: map[string]time.Time{}, + mutex: &sync.RWMutex{}, + // emailNotifier: &EmailNotifier{}, } } @@ -429,7 +443,12 @@ func (n *AuditPlanNotifier) shouldNotify(auditPlan *model.AuditPlan) bool { func (n *AuditPlanNotifier) Send(notification Notification, auditPlan *model.AuditPlan) (err error) { if auditPlan.EnableEmailNotify { - err = n.sendEmail(notification, auditPlan.CreateUser) + user, err := dms.GetUser(context.TODO(), auditPlan.CreateUserID, controller.GetDMSServerAddress()) + if err != nil { + log.NewEntry().Errorf("get user error, %v", err) + return err + } + err = n.sendEmail(notification, user) if err != nil { return err } @@ -444,7 +463,14 @@ func (n *AuditPlanNotifier) Send(notification Notification, auditPlan *model.Aud } func (n *AuditPlanNotifier) sendEmail(notification Notification, user *model.User) error { - return n.emailNotifier.Notify(notification, []*model.User{user}) + // dms-todo 只发送邮件告警 + return dmsobject.Notify(context.TODO(), controller.GetDMSServerAddress(), v1.NotificationReq{ + Notification: &v1.Notification{ + NotificationSubject: notification.NotificationSubject(), + NotificationBody: notification.NotificationBody(), + UserUids: []string{user.GetIDStr()}, + }, + }) } func (n *AuditPlanNotifier) updateRecord(auditPlanName string) { diff --git a/sqle/notification/webhook.go b/sqle/notification/webhook.go index 4daa891f44..fe486e2121 100644 --- a/sqle/notification/webhook.go +++ b/sqle/notification/webhook.go @@ -1,15 +1,13 @@ package notification import ( - "bytes" + "context" "encoding/json" - "fmt" - "io/ioutil" - "net/http" "time" - "github.com/actiontech/sqle/sqle/notification/webhook" - "github.com/actiontech/sqle/sqle/utils/retry" + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + "github.com/actiontech/sqle/sqle/api/controller" ) type webHookRequestBody struct { @@ -30,21 +28,13 @@ type httpBodyPayload struct { Workflow *workflowPayload `json:"workflow"` } -func TestWorkflowConfig() (err error) { - return workflowSendRequest("create", - "test_project", "1658637666259832832", "test_workflow", "wait_for_audit") -} +// func TestWorkflowConfig() (err error) { +// return workflowSendRequest("create", +// "test_project", "1658637666259832832", "test_workflow", "wait_for_audit") +// } func workflowSendRequest(action, projectName, workflowID, workflowSubject, workflowStatus string) (err error) { - cfg := webhook.WorkflowCfg - if cfg == nil { - return fmt.Errorf("workflow webhook config missing") - } - - if cfg.URL == "" { - return fmt.Errorf("url is missing, please check webhook config") - } reqBody := &webHookRequestBody{ Event: "workflow", @@ -65,32 +55,11 @@ func workflowSendRequest(action, return err } - req, err := http.NewRequest(http.MethodPost, cfg.URL, bytes.NewBuffer(b)) - if err != nil { - return - } - if cfg.Token != "" { - req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", cfg.Token)) - } - - doneChan := make(chan struct{}) - return retry.Do(func() error { - resp, err := http.DefaultClient.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusOK { - return nil - } - respBytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - return fmt.Errorf("response status_code(%v) body(%s)", resp.StatusCode, respBytes) - }, doneChan, - retry.Delay(time.Duration(cfg.RetryIntervalSeconds)*time.Second), - retry.Attempts(uint(cfg.MaxRetryTimes))) + return dmsobject.WebHookSendMessage(context.TODO(), controller.GetDMSServerAddress(), &v1.WebHookSendMessageReq{ + WebHookMessage: &v1.WebHooksMessage{ + Message: string(b), + TriggerEventType: v1.TriggerEventTypeWorkflow, + }, + }) } diff --git a/sqle/notification/wechat.go b/sqle/notification/wechat.go deleted file mode 100644 index 453da036c5..0000000000 --- a/sqle/notification/wechat.go +++ /dev/null @@ -1,102 +0,0 @@ -package notification - -import ( - "fmt" - "net" - "net/http" - "net/url" - "strings" - "time" - - "github.com/actiontech/sqle/sqle/model" - - "gopkg.in/chanxuehong/wechat.v1/corp" - "gopkg.in/chanxuehong/wechat.v1/corp/message/send" -) - -func init() { - Notifiers = append(Notifiers, &WeChatNotifier{}) -} - -type WeChatNotifier struct{} - -func (n *WeChatNotifier) Notify(notification Notification, users []*model.User) error { - // workflow has been finished. - if len(users) == 0 { - return nil - } - wechatUsers := map[string] /*user name*/ string /*wechat id*/ {} - for _, user := range users { - if user.WeChatID != "" { - wechatUsers[user.Name] = user.WeChatID - } - } - - // no user has configured wechat, don't send. - if len(wechatUsers) == 0 { - return nil - } - - s := model.GetStorage() - wechatC, exist, err := s.GetWeChatConfiguration() - if err != nil { - return err - } - if !exist { - return nil - } - if !wechatC.EnableWeChatNotify { - return nil - } - - client := generateWeChatClient(wechatC) - safe := 0 - if wechatC.SafeEnabled { - safe = 1 - } - errs := []string{} - for name, id := range wechatUsers { - req := &send.Text{ - MessageHeader: send.MessageHeader{ - ToUser: id, - MsgType: "text", - AgentId: int64(wechatC.AgentID), - Safe: &safe, - }, - } - req.Text.Content = fmt.Sprintf("%v \n\n %v", notification.NotificationSubject(), notification.NotificationBody()) - _, err := client.SendText(req) - if err != nil { - errs = append(errs, fmt.Sprintf("send message to %v failed, error: %v", name, err)) - } - } - if len(errs) > 0 { - return fmt.Errorf("%v", strings.Join(errs, "\n")) - } - return nil -} - -func generateWeChatClient(conf *model.WeChatConfiguration) *send.Client { - proxy := http.ProxyFromEnvironment - if conf.ProxyIP != "" { - proxy = func(req *http.Request) (*url.URL, error) { - return url.Parse(conf.ProxyIP) - } - } - var transport http.RoundTripper = &http.Transport{ - Proxy: proxy, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - } - httpClient := &http.Client{ - Transport: transport, - } - accessTokenServer := corp.NewDefaultAccessTokenServer(conf.CorpID, conf.CorpSecret, httpClient) - return send.NewClient(accessTokenServer, httpClient) -} diff --git a/sqle/pkg/im/dingding/dingding.go b/sqle/pkg/im/dingding/dingding.go index 3d4f025310..c1b2421fb3 100644 --- a/sqle/pkg/im/dingding/dingding.go +++ b/sqle/pkg/im/dingding/dingding.go @@ -167,7 +167,7 @@ func (d *DingTalk) CreateApprovalTemplate() error { processCode = *resp.Body.Result.ProcessCode } goto End - // https://github.com/actiontech/sqle/issues/1487 + // https://github.com/actiontech/sqle/issues/1487 } else if !tea.BoolValue(util.Empty(sdkErr.Code)) && *sdkErr.Code == "formName.error" { getProcessCodeByNameHeaders := &dingTalkWorkflow.GetProcessCodeByNameHeaders{} getProcessCodeByNameHeaders.XAcsDingtalkAccessToken = tea.String(token) @@ -210,7 +210,7 @@ End: // CreateApprovalInstance // https://open.dingtalk.com/document/orgapp-server/create-an-approval-instance -func (d *DingTalk) CreateApprovalInstance(workflowName string, workflowId uint, originUserId *string, userIds []*string, auditResult, projectName, desc, workflowUrl string) error { +func (d *DingTalk) CreateApprovalInstance(workflowName string, workflowId string, originUserId *string, userIds []*string, auditResult, projectName, desc, workflowUrl string) error { token, err := GetToken(d.AppKey, d.AppSecret) if err != nil { return fmt.Errorf("get token error: %v", err) @@ -283,7 +283,7 @@ func (d *DingTalk) CreateApprovalInstance(workflowName string, workflowId uint, // UpdateApprovalStatus // https://open.dingtalk.com/document/orgapp-server/approve-or-reject-the-approval-task -func (d *DingTalk) UpdateApprovalStatus(workflowId uint, status, userId, reason string) error { +func (d *DingTalk) UpdateApprovalStatus(workflowId string, status, userId, reason string) error { s := model.GetStorage() dingTalkInstance, exist, err := s.GetDingTalkInstanceByWorkflowID(workflowId) if err != nil { diff --git a/sqle/pkg/im/im.go b/sqle/pkg/im/im.go index dd49586fce..b2df3fa293 100644 --- a/sqle/pkg/im/im.go +++ b/sqle/pkg/im/im.go @@ -5,6 +5,9 @@ import ( "fmt" "strings" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + "github.com/actiontech/sqle/sqle/api/controller" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" "github.com/actiontech/sqle/sqle/pkg/im/dingding" @@ -56,25 +59,40 @@ func CreateApprovalTemplate(imType string) { } } -func CreateApprove(id string) { +func CreateApprove(projectId, workflowId string) { newLog := log.NewEntry() s := model.GetStorage() - workflow, exist, err := s.GetWorkflowDetailById(id) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectId, workflowId, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { - newLog.Error("get workflow detail error: ", err) - return - } - if !exist { newLog.Error("workflow not exist") return } + user, err := dms.GetUser(context.TODO(), workflow.CreateUserId, dms.GetDMSServerAddress()) + if err != nil { + newLog.Errorf("get user phone failed err: %v", err) + return + } + if user.Phone == "" { + newLog.Error("create user phone is empty") + return + } if workflow.CurrentStep() == nil { - newLog.Infof("workflow %v has no current step, no need to create approve instance", workflow.ID) + newLog.Infof("workflow %v has no current step, no need to create approve instance", workflow.WorkflowId) + } + + if len(workflow.Record.Steps) == 1 || workflow.CurrentStep() == workflow.Record.Steps[len(workflow.Record.Steps)-1] { + newLog.Infof("workflow %v only has one approve step or has been approved, no need to create approve instance", workflow.WorkflowId) return } - users := workflow.CurrentAssigneeUser() + assignUserIds := workflow.CurrentAssigneeUser() + + assignUsers, err := dms.GetUsers(context.TODO(), assignUserIds, controller.GetDMSServerAddress()) + if err != nil { + newLog.Errorf("get user error: %v", err) + return + } ims, err := s.GetAllIMConfig() if err != nil { @@ -94,7 +112,7 @@ func CreateApprove(id string) { } sqleUrl := systemVariables[model.SystemVariableSqleUrl].Value - workflowUrl := fmt.Sprintf("%v/project/%s/order/%s", sqleUrl, workflow.Project.Name, workflow.WorkflowId) + workflowUrl := fmt.Sprintf("%v/project/%s/order/%s", sqleUrl, workflow.ProjectId, workflow.WorkflowId) if sqleUrl == "" { newLog.Errorf("sqle url is empty") workflowUrl = "" @@ -103,14 +121,14 @@ func CreateApprove(id string) { switch im.Type { case model.ImTypeDingTalk: if len(workflow.Record.Steps) == 1 || workflow.CurrentStep() == workflow.Record.Steps[len(workflow.Record.Steps)-1] { - newLog.Infof("workflow %v is the last step, no need to create approve instance", workflow.ID) + newLog.Infof("workflow %v is the last step, no need to create approve instance", workflow.WorkflowId) return } - if workflow.CreateUser.Phone == "" { - newLog.Error("create user phone is empty") - return - } + // if workflow.CreateUser.Phone == "" { + // newLog.Error("create user phone is empty") + // return + // } var tableRows []string for _, record := range workflow.Record.InstanceRecords { @@ -126,35 +144,37 @@ func CreateApprove(id string) { AppSecret: im.AppSecret, ProcessCode: im.ProcessCode, } - - createUserId, err := dingTalk.GetUserIDByPhone(workflow.CreateUser.Phone) + workflowCreateUser, err := dmsobject.GetUser(context.TODO(), workflow.CreateUserId, dms.GetDMSServerAddress()) + if err != nil { + newLog.Errorf("get user error: %v", err) + return + } + createUserId, err := dingTalk.GetUserIDByPhone(workflowCreateUser.Phone) if err != nil { newLog.Errorf("get origin user id by phone error: %v", err) continue } - userIds := make([]*string, 0, len(users)) - for _, user := range users { + var userIds []*string + for _, assignUser := range assignUsers { if user.Phone == "" { - newLog.Infof("user %v phone is empty, skip", user.ID) + newLog.Infof("user %v phone is empty, skip", assignUser) continue } - - userId, err := dingTalk.GetUserIDByPhone(user.Phone) + userId, err := dingTalk.GetUserIDByPhone(assignUser.Phone) if err != nil { newLog.Errorf("get user id by phone error: %v", err) continue } - userIds = append(userIds, userId) } - if err := dingTalk.CreateApprovalInstance(workflow.Subject, workflow.ID, createUserId, userIds, auditResult, workflow.Project.Name, workflow.Desc, workflowUrl); err != nil { + if err := dingTalk.CreateApprovalInstance(workflow.Subject, workflow.WorkflowId, createUserId, userIds, auditResult, string(workflow.ProjectId), workflow.Desc, workflowUrl); err != nil { newLog.Errorf("create dingtalk approval instance error: %v", err) continue } case model.ImTypeFeishuAudit: - if err := CreateFeishuAuditInst(context.TODO(), im, workflow, users, workflowUrl); err != nil { + if err := CreateFeishuAuditInst(context.TODO(), im, workflow, assignUsers, workflowUrl); err != nil { newLog.Errorf("create feishu audit instance error: %v", err) continue } @@ -164,7 +184,7 @@ func CreateApprove(id string) { } } -func UpdateApprove(workflowId uint, user *model.User, status, reason string) { +func UpdateApprove(workflowId string, user *model.User, status, reason string) { newLog := log.NewEntry() s := model.GetStorage() @@ -205,7 +225,7 @@ func UpdateApprove(workflowId uint, user *model.User, status, reason string) { } } -func BatchCancelApprove(workflowIds []uint, user *model.User) { +func BatchCancelApprove(workflowIds []string, user *model.User) { newLog := log.NewEntry() s := model.GetStorage() ims, err := s.GetAllIMConfig() diff --git a/sqle/pkg/im/im_ce.go b/sqle/pkg/im/im_ce.go index 803bd748d8..6d0d10a1da 100644 --- a/sqle/pkg/im/im_ce.go +++ b/sqle/pkg/im/im_ce.go @@ -20,10 +20,10 @@ func CreateFeishuAuditInst(ctx context.Context, im model.IM, workflow *model.Wor return ErrCommunityEditionNotSupportFeishuAudit } -func UpdateFeishuAuditStatus(ctx context.Context, im model.IM, workflowId uint, user *model.User, status string, reason string) error { +func UpdateFeishuAuditStatus(ctx context.Context, im model.IM, workflowId string, user *model.User, status string, reason string) error { return ErrCommunityEditionNotSupportFeishuAudit } -func CancelFeishuAuditInst(ctx context.Context, im model.IM, workflowIDs []uint, user *model.User) error { +func CancelFeishuAuditInst(ctx context.Context, im model.IM, workflowIDs []string, user *model.User) error { return ErrCommunityEditionNotSupportFeishuAudit } diff --git a/sqle/server/audit.go b/sqle/server/audit.go index ba81eea268..9b7e5f8bd7 100644 --- a/sqle/server/audit.go +++ b/sqle/server/audit.go @@ -17,13 +17,13 @@ import ( "github.com/sirupsen/logrus" ) -func Audit(l *logrus.Entry, task *model.Task, projectId *uint, ruleTemplateName string) (err error) { +func Audit(l *logrus.Entry, task *model.Task, projectId *model.ProjectUID, ruleTemplateName string) (err error) { return HookAudit(l, task, &EmptyAuditHook{}, projectId, ruleTemplateName) } -func HookAudit(l *logrus.Entry, task *model.Task, hook AuditHook, projectId *uint, ruleTemplateName string) (err error) { +func HookAudit(l *logrus.Entry, task *model.Task, hook AuditHook, projectId *model.ProjectUID, ruleTemplateName string) (err error) { st := model.GetStorage() - rules, customRules, err := st.GetAllRulesByTmpNameAndProjectIdInstanceDBType(ruleTemplateName, projectId, task.Instance, task.DBType) + rules, customRules, err := st.GetAllRulesByTmpNameAndProjectIdInstanceDBType(ruleTemplateName, string(*projectId), task.Instance, task.DBType) if err != nil { return err } @@ -33,6 +33,11 @@ func HookAudit(l *logrus.Entry, task *model.Task, hook AuditHook, projectId *uin } defer plugin.Close(context.TODO()) + // possible task is self build object, not model.Task{} + if task.Instance == nil { + task.Instance = &model.Instance{ProjectId: string(*projectId)} + } + return hookAudit(l, task, plugin, hook, customRules) } @@ -40,7 +45,7 @@ const AuditSchema = "AuditSchema" func DirectAuditByInstance(l *logrus.Entry, sql, schemaName string, instance *model.Instance) (*model.Task, error) { st := model.GetStorage() - rules, customRules, err := st.GetAllRulesByTmpNameAndProjectIdInstanceDBType("", nil, instance, instance.DbType) + rules, customRules, err := st.GetAllRulesByTmpNameAndProjectIdInstanceDBType("", "", instance, instance.DbType) if err != nil { return nil, err } @@ -59,9 +64,9 @@ func DirectAuditByInstance(l *logrus.Entry, sql, schemaName string, instance *mo return task, audit(l, task, plugin, customRules) } -func AuditSQLByDBType(l *logrus.Entry, sql string, dbType string, projectId *uint, ruleTemplateName string) (*model.Task, error) { +func AuditSQLByDBType(l *logrus.Entry, sql string, dbType string) (*model.Task, error) { st := model.GetStorage() - rules, customRules, err := st.GetAllRulesByTmpNameAndProjectIdInstanceDBType(ruleTemplateName, projectId, nil, dbType) + rules, customRules, err := st.GetAllRulesByTmpNameAndProjectIdInstanceDBType("", "", nil, dbType) if err != nil { return nil, err } @@ -125,7 +130,12 @@ func hookAudit(l *logrus.Entry, task *model.Task, p driver.Plugin, hook AuditHoo }() st := model.GetStorage() - whitelist, err := st.GetSqlWhitelistByInstanceId(task.InstanceId) + + projectId := "" + if task.Instance != nil { + projectId = task.Instance.ProjectId + } + whitelist, err := st.GetSqlWhitelistByProjectId(projectId) if err != nil { return err } diff --git a/sqle/server/auditplan/huawei_task.go b/sqle/server/auditplan/huawei_task.go new file mode 100644 index 0000000000..afdbd99148 --- /dev/null +++ b/sqle/server/auditplan/huawei_task.go @@ -0,0 +1,325 @@ +package auditplan + +import ( + "fmt" + "strconv" + "time" + + "github.com/actiontech/sqle/sqle/model" + "github.com/actiontech/sqle/sqle/utils" + "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic" + + rdsCoreRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/region" + rds "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/rds/v3" + rdsModel "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/rds/v3/model" + rdsRegion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/rds/v3/region" + "github.com/percona/go-mysql/query" + "github.com/sirupsen/logrus" +) + +const huaweiCloudRequestTimeFormat = "2006-01-02T15:04:05-0700" +const huaweiCloudResponseTimeFormat = "2006-01-02T15:04:05" + +type SqlFromHuaweiCloud struct { + sql string + executionStartTime time.Time + schema string +} + +func NewHuaweiRdsMySQLSlowLogTask(entry *logrus.Entry, ap *model.AuditPlan) Task { + sqlCollector := newSQLCollector(entry, ap) + a := &HuaweiRdsMySQLSlowLogTask{} + task := &huaweiRdsMySQLTask{ + sqlCollector: sqlCollector, + lastEndTime: nil, + pullLogs: a.pullLogs, + } + sqlCollector.do = task.collectorDo + a.huaweiRdsMySQLTask = task + return a +} + +type HuaweiRdsMySQLSlowLogTask struct { + *huaweiRdsMySQLTask +} + +func (hr *HuaweiRdsMySQLSlowLogTask) pullLogs(client *rds.RdsClient, instanceId string, startTime, endTime time.Time, pageSize, pageNum int32) (sqls []SqlFromHuaweiCloud, err error) { + request := hr.newSlowSqlsRequest(instanceId, startTime, endTime, pageSize, pageNum) + response := &rdsModel.ListSlowLogsResponse{} + + tryErr := func() (err error) { + defer func() { + if r := recover(); r != nil { + if e, ok := r.(error); ok { + err = e + } else { + err = fmt.Errorf("panic: %v", r) + } + } + }() + response, err = client.ListSlowLogs(request) + if err != nil { + return err + } + return nil + }() + + if tryErr != nil { + return nil, fmt.Errorf("get huawei cloud slow log failed: %+v", tryErr) + } + + sqls = make([]SqlFromHuaweiCloud, len(*response.SlowLogList)) + for i, slowRecord := range *response.SlowLogList { + execStartTime, err := time.Parse(huaweiCloudResponseTimeFormat, utils.NvlString(&slowRecord.StartTime)) + if err != nil { + return nil, fmt.Errorf("parse huawei cloud execution-start-time failed: %v", err) + } + sqls[i] = SqlFromHuaweiCloud{ + sql: utils.NvlString(&slowRecord.QuerySample), + executionStartTime: execStartTime, + schema: slowRecord.Database, + } + } + return sqls, nil +} + +func (at *HuaweiRdsMySQLSlowLogTask) Audit() (*AuditResultResp, error) { + task := &model.Task{ + DBType: at.ap.DBType, + } + return at.baseTask.audit(task) +} + +// huaweiRdsMySQLTask implement the Task interface. +// +// huaweiRdsMySQLTask is a loop task which collect slow log from ali rds MySQL instance. +type huaweiRdsMySQLTask struct { + *sqlCollector + lastEndTime *time.Time + pullLogs func(client *rds.RdsClient, instanceId string, startTime, endTime time.Time, pageSize, pageNum int32) (sqls []SqlFromHuaweiCloud, err error) +} + +var staticFields = map[string]struct{}{ + "af-south-1": {}, + "cn-north-4": {}, + "cn-north-1": {}, + "cn-east-2": {}, + "cn-east-3": {}, + "cn-south-1": {}, + "cn-southwest-2": {}, + "ap-southeast-2": {}, + "ap-southeast-1": {}, + "ap-southeast-3": {}, + "ru-northwest-2": {}, + "sa-brazil-1": {}, + "la-north-2": {}, + "cn-south-2": {}, + "na-mexico-1": {}, + "la-south-2": {}, + "cn-north-9": {}, + "cn-north-2": {}, + "tr-west-1": {}, + "ap-southeast-4": {}, + "ae-ad-1": {}, + "eu-west-101": {}, +} + +func isHuaweiRdsRegionExist(region string) bool { + var provider = rdsCoreRegion.DefaultProviderChain("RDS") + reg := provider.GetRegion(region) + if reg == nil { + _, exist := staticFields[region] + return exist + } + return true +} + +func (at *huaweiRdsMySQLTask) collectorDo() { + //1. Load Configuration + // if at.ap.InstanceName == "" { + // at.logger.Warnf("instance is not configured") + // return + // } + accessKeyId := at.ap.Params.GetParam(paramKeyAccessKeyId).String() + if accessKeyId == "" { + at.logger.Warnf("huawei cloud access key id is not configured") + return + } + secretAccessKey := at.ap.Params.GetParam(paramKeyAccessKeySecret).String() + if secretAccessKey == "" { + at.logger.Warnf("huawei cloud secret access key is not configured") + return + } + projectId := at.ap.Params.GetParam(paramKeyProjectId).String() + if projectId == "" { + at.logger.Warnf("huawei cloud project id is not configured") + return + } + instanceId := at.ap.Params.GetParam(paramKeyDBInstanceId).String() + if instanceId == "" { + at.logger.Warnf("huawei cloud instance id is not configured") + return + } + region := at.ap.Params.GetParam(paramKeyRegion).String() + if region == "" { + at.logger.Warnf("huawei cloud region is not configured") + return + } + if !isHuaweiRdsRegionExist(region) { + at.logger.Warnf("huawei cloud region is not exist") + return + } + periodHours := at.ap.Params.GetParam(paramKeyFirstSqlsScrappedInLastPeriodHours).String() + if periodHours == "" { + at.logger.Warnf("huawei cloud period hours is not configured") + return + } + firstScrapInLastHours, err := strconv.Atoi(periodHours) + if err != nil { + at.sqlCollector.logger.Warnf("convert first sqls scrapped in last period hours failed: %v", err) + return + } + + if firstScrapInLastHours == 0 { + firstScrapInLastHours = 24 + } + theMaxSupportedDays := 30 // 支持往前查看慢日志的最大天数 + hoursDuringADay := 24 + if firstScrapInLastHours > theMaxSupportedDays*hoursDuringADay { + at.logger.Warnf("Can not get slow logs from so early time. firstScrapInLastHours=%v", firstScrapInLastHours) + return + } + //2. Init Client + client := at.CreateClient(accessKeyId, secretAccessKey, projectId, region) + if client == nil { + at.logger.Warnf("create client for huawei rdb mysql failed") + return + } + + // 3. Request for slow logs + + now := time.Now() + slowSqls := []SqlFromHuaweiCloud{} + var pageNum int32 = 1 + var pageSize int32 = 100 + var startTime time.Time + if at.isFirstScrap() { + startTime = now.Add(time.Duration(-1*firstScrapInLastHours) * time.Hour) + } else { + startTime = *at.lastEndTime + } + + for { + newSlowSqls, err := at.pullLogs(client, instanceId, startTime, now, pageSize, pageNum) + if err != nil { + at.logger.Warnf("pull rds logs failed: %v", err) + return + } + filteredNewSlowSqls := at.filterSlowSqlsByExecutionTime(newSlowSqls, startTime) + slowSqls = append(slowSqls, filteredNewSlowSqls...) + + if len(newSlowSqls) < int(pageSize) { + break + } + pageNum++ + } + + //4. Merge SQL + mergedSlowSqls := mergeSQLsFromHuaweiCloud(slowSqls) + if len(mergedSlowSqls) > 0 { + if at.isFirstScrap() { + err = at.persist.OverrideAuditPlanSQLs(at.ap.ID, at.convertSQLInfosToModelSQLs(mergedSlowSqls, now)) + if err != nil { + at.logger.Errorf("save sqls to storage fail, error: %v", err) + return + } + } else { + err = at.persist.UpdateDefaultAuditPlanSQLs(at.ap.ID, at.convertSQLInfosToModelSQLs(mergedSlowSqls, now)) + if err != nil { + at.logger.Errorf("save sqls to storage fail, error: %v", err) + return + } + } + } + // update lastEndTime + // 查询的起始时间为上一次查询到的最后一条慢语句的开始执行时间 + if len(slowSqls) > 0 { + lastSlowSql := slowSqls[len(slowSqls)-1] + at.lastEndTime = &lastSlowSql.executionStartTime + } + +} + +func (at *huaweiRdsMySQLTask) convertSQLInfosToModelSQLs(sqls []sqlInfo, now time.Time) []*model.AuditPlanSQLV2 { + return convertRawSlowSQLWitchFromSqlInfo(sqls, now) +} + +func mergeSQLsFromHuaweiCloud(sqls []SqlFromHuaweiCloud) []sqlInfo { + sqlInfos := []sqlInfo{} + + counter := map[string]int /*slice subscript*/ {} + for _, sql := range sqls { + fp := query.Fingerprint(sql.sql) + if index, exist := counter[fp]; exist { + sqlInfos[index].counter += 1 + sqlInfos[index].fingerprint = fp + sqlInfos[index].sql = sql.sql + sqlInfos[index].schema = sql.schema + } else { + sqlInfos = append(sqlInfos, sqlInfo{ + counter: 1, + fingerprint: fp, + sql: sql.sql, + schema: sql.schema, + }) + counter[fp] = len(sqlInfos) - 1 + } + + } + return sqlInfos +} +func (at *huaweiRdsMySQLTask) CreateClient(accessKeyId, secretAccessKey, projectId, region string) *rds.RdsClient { + defer func() { + if err := recover(); err != nil { + at.logger.Warnf("in huawei rds of audit plan, recovered from panic: %+v", err) + } + }() + credential := basic.NewCredentialsBuilder(). + WithAk(accessKeyId). + WithSk(secretAccessKey). + WithProjectId(projectId). + Build() + hcClient := rds.RdsClientBuilder(). + WithRegion(rdsRegion.ValueOf(region)). + WithCredential(credential). + Build() + return rds.NewRdsClient(hcClient) +} + +func (at *huaweiRdsMySQLTask) newSlowSqlsRequest(instanceId string, startTime, endTime time.Time, pageSize, pageNum int32) *rdsModel.ListSlowLogsRequest { + startDate := startTime.Format(huaweiCloudRequestTimeFormat) + endDate := endTime.Format(huaweiCloudRequestTimeFormat) + + return &rdsModel.ListSlowLogsRequest{ + InstanceId: instanceId, + StartDate: startDate, + EndDate: endDate, + Offset: &pageNum, + Limit: &pageSize, + } +} + +func (at *huaweiRdsMySQLTask) isFirstScrap() bool { + return at.lastEndTime == nil +} + +// 因为查询的起始时间为上一次查询到的最后一条慢语句的executionStartTime(精确到秒),而查询起始时间只能精确到分钟,所以有可能还是会查询到上一次查询过的慢语句,需要将其过滤掉 +func (at *huaweiRdsMySQLTask) filterSlowSqlsByExecutionTime(slowSqls []SqlFromHuaweiCloud, executionTime time.Time) (res []SqlFromHuaweiCloud) { + for _, sql := range slowSqls { + if !sql.executionStartTime.After(executionTime) { + continue + } + res = append(res, sql) + } + return +} diff --git a/sqle/server/auditplan/manager.go b/sqle/server/auditplan/manager.go index 1a5025a4fb..4b29d35844 100644 --- a/sqle/server/auditplan/manager.go +++ b/sqle/server/auditplan/manager.go @@ -5,6 +5,7 @@ import ( "fmt" "time" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" @@ -147,7 +148,7 @@ func (mgr *Manager) Start() { func (mgr *Manager) sync() error { // 全量同步智能扫描任务,仅需成功做一次 if !mgr.isFullSyncDone { - aps, err := mgr.persist.GetActiveAuditPlans() + aps, err := dms.GetActiveAuditPlansWithInstance(mgr.persist.GetActiveAuditPlans) if err != nil { return err } diff --git a/sqle/server/auditplan/manager_test.go b/sqle/server/auditplan/manager_test.go index ff0d0c9679..f8978a32c3 100644 --- a/sqle/server/auditplan/manager_test.go +++ b/sqle/server/auditplan/manager_test.go @@ -26,16 +26,16 @@ func TestManager(t *testing.T) { nextTime := m.lastSyncTime.Add(5 * time.Second) // test init - mockHandle.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.status = 'active'))"). - WithArgs(). + mockHandle.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_status = ?))"). + WithArgs("active"). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "type", "cron_expression"}).AddRow(1, "test_ap_1", "default", "*/1 * * * *")) mockHandle.ExpectQuery("SELECT id, updated_at FROM `audit_plans` WHERE (updated_at > ?) ORDER BY updated_at"). WithArgs(m.lastSyncTime). WillReturnRows(sqlmock.NewRows([]string{"id", "updated_at"}).AddRow(2, nextTime)) - mockHandle.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.status = 'active') AND (audit_plans.id = ?))"). - WithArgs(2). + mockHandle.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_status = ?) AND (id = ?)) "). + WithArgs("active", 2). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "type", "cron_expression"}).AddRow(2, "test_ap_2", "default", "*/2 * * * *")) assert.NoError(t, m.sync()) @@ -65,8 +65,8 @@ func TestManager(t *testing.T) { WithArgs(nextTime). WillReturnRows(sqlmock.NewRows([]string{"id", "updated_at"}).AddRow(3, nextTimeMore)) - mockHandle.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.status = 'active') AND (audit_plans.id = ?))"). - WithArgs(3). + mockHandle.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_status = ?) AND (id = ?))"). + WithArgs("active", 3). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "type", "cron_expression"}).AddRow(3, "test_ap_3", "default", "*/3 * * * *")) m.sync() @@ -87,8 +87,8 @@ func TestManager(t *testing.T) { WithArgs(nextTimeMore). WillReturnRows(sqlmock.NewRows([]string{"id", "updated_at"}).AddRow(3, nextTimeMore2)) - mockHandle.ExpectQuery("SELECT `audit_plans`.* FROM `audit_plans` LEFT JOIN projects ON projects.id = audit_plans.project_id WHERE `audit_plans`.`deleted_at` IS NULL AND ((projects.status = 'active') AND (audit_plans.id = ?))"). - WithArgs(3). + mockHandle.ExpectQuery("SELECT * FROM `audit_plans` WHERE `audit_plans`.`deleted_at` IS NULL AND ((project_status = ?) AND (id = ?))"). + WithArgs("active", 3). WillReturnRows(sqlmock.NewRows([]string{"id", "name", "type", "cron_expression"})) m.sync() diff --git a/sqle/server/auditplan/mananger_comm.go b/sqle/server/auditplan/mananger_comm.go index fb52257882..ca2765651e 100644 --- a/sqle/server/auditplan/mananger_comm.go +++ b/sqle/server/auditplan/mananger_comm.go @@ -25,11 +25,11 @@ func NewSyncFromAuditPlan(auditReport *model.AuditPlanReportV2, filterSqls []*mo type SyncFromSqlAuditRecord struct { Task *model.Task SqlFpMap map[string]string - ProjectId uint + ProjectId string SqlAuditRecordID uint } -func NewSyncFromSqlAudit(task *model.Task, fpMap map[string]string, projectID uint, sqlAuditID uint) SqlManager { +func NewSyncFromSqlAudit(task *model.Task, fpMap map[string]string, projectID string, sqlAuditID uint) SqlManager { return &SyncFromSqlAuditRecord{ Task: task, ProjectId: projectID, diff --git a/sqle/server/auditplan/meta.go b/sqle/server/auditplan/meta.go index 89d12ef98d..42b45f75df 100644 --- a/sqle/server/auditplan/meta.go +++ b/sqle/server/auditplan/meta.go @@ -19,18 +19,19 @@ type Meta struct { } const ( - TypeDefault = "default" - TypeMySQLSlowLog = "mysql_slow_log" - TypeMySQLMybatis = "mysql_mybatis" - TypeMySQLSchemaMeta = "mysql_schema_meta" - TypeMySQLProcesslist = "mysql_processlist" - TypeAliRdsMySQLSlowLog = "ali_rds_mysql_slow_log" - TypeAliRdsMySQLAuditLog = "ali_rds_mysql_audit_log" - TypeOracleTopSQL = "oracle_top_sql" - TypeTiDBAuditLog = "tidb_audit_log" - TypeAllAppExtract = "all_app_extract" - TypeBaiduRdsMySQLSlowLog = "baidu_rds_mysql_slow_log" - TypeSQLFile = "sql_file" + TypeDefault = "default" + TypeMySQLSlowLog = "mysql_slow_log" + TypeMySQLMybatis = "mysql_mybatis" + TypeMySQLSchemaMeta = "mysql_schema_meta" + TypeMySQLProcesslist = "mysql_processlist" + TypeAliRdsMySQLSlowLog = "ali_rds_mysql_slow_log" + TypeAliRdsMySQLAuditLog = "ali_rds_mysql_audit_log" + TypeHuaweiRdsMySQLSlowLog = "huawei_rds_mysql_slow_log" + TypeOracleTopSQL = "oracle_top_sql" + TypeTiDBAuditLog = "tidb_audit_log" + TypeAllAppExtract = "all_app_extract" + TypeBaiduRdsMySQLSlowLog = "baidu_rds_mysql_slow_log" + TypeSQLFile = "sql_file" ) const ( @@ -51,6 +52,8 @@ const ( paramKeyAccessKeySecret = "access_key_secret" paramKeyRdsPath = "rds_path" paramKeyFirstSqlsScrappedInLastPeriodHours = "first_sqls_scrapped_in_last_period_hours" + paramKeyProjectId = "project_id" + paramKeyRegion = "region" ) var Metas = []Meta{ @@ -272,6 +275,50 @@ var Metas = []Meta{ }, }, }, + { + Type: TypeHuaweiRdsMySQLSlowLog, + Desc: "华为云RDS MySQL慢日志", + InstanceType: InstanceTypeMySQL, + CreateTask: NewHuaweiRdsMySQLSlowLogTask, + Params: []*params.Param{ + { + Key: paramKeyProjectId, + Desc: "项目ID", + Value: "", + Type: params.ParamTypeString, + }, + { + Key: paramKeyDBInstanceId, + Desc: "实例ID", + Value: "", + Type: params.ParamTypeString, + }, + { + Key: paramKeyAccessKeyId, + Desc: "Access Key ID", + Value: "", + Type: params.ParamTypeString, + }, + { + Key: paramKeyAccessKeySecret, + Desc: "Access Key Secret", + Value: "", + Type: params.ParamTypeString, + }, + { + Key: paramKeyFirstSqlsScrappedInLastPeriodHours, + Desc: "启动任务时拉取慢日志的时间范围(单位:小时,最大30天)", + Value: "", + Type: params.ParamTypeInt, + }, + { + Key: paramKeyRegion, + Desc: "当前RDS实例所在的地区(示例:cn-east-2)", + Value: "", + Type: params.ParamTypeString, + }, + }, + }, { Type: TypeOracleTopSQL, Desc: "Oracle TOP SQL", diff --git a/sqle/server/auditplan/task.go b/sqle/server/auditplan/task.go index 0325f7a790..24ef084b7f 100644 --- a/sqle/server/auditplan/task.go +++ b/sqle/server/auditplan/task.go @@ -11,6 +11,7 @@ import ( "sync" "time" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/driver/mysql/executor" driverV2 "github.com/actiontech/sqle/sqle/driver/v2" "github.com/actiontech/sqle/sqle/errors" @@ -261,9 +262,23 @@ func NewDefaultTask(entry *logrus.Entry, ap *model.AuditPlan) Task { } func (at *DefaultTask) Audit() (*AuditResultResp, error) { - task, err := getTaskWithInstanceByAuditPlan(at.ap, at.persist) - if err != nil { - return nil, err + var task *model.Task + if at.ap.InstanceName == "" { + task = &model.Task{ + DBType: at.ap.DBType, + } + } else { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) + defer cancel() + instance, _, err := dms.GetInstanceInProjectByName(ctx, string(at.ap.ProjectId), at.ap.InstanceName) + if err != nil { + return nil, err + } + task = &model.Task{ + Instance: instance, + Schema: at.ap.InstanceDatabase, + DBType: at.ap.DBType, + } } return at.baseTask.audit(task) } @@ -358,7 +373,7 @@ func getTaskWithInstanceByAuditPlan(ap *model.AuditPlan, persist *model.Storage) DBType: ap.DBType, } } else { - instance, _, err := persist.GetInstanceByNameAndProjectID(ap.InstanceName, ap.ProjectId) + instance, _, err := dms.GetInstanceInProjectByName(context.TODO(), string(ap.ProjectId), ap.InstanceName) if err != nil { return nil, err } @@ -393,7 +408,10 @@ func (at *SchemaMetaTask) collectorDo() { at.logger.Warnf("instance schema is not configured") return } - instance, _, err := at.persist.GetInstanceByNameAndProjectID(at.ap.InstanceName, at.ap.ProjectId) + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) + defer cancel() + instance, _, err := dms.GetInstanceInProjectByName(ctx, string(at.ap.ProjectId), at.ap.InstanceName) if err != nil { return } @@ -512,7 +530,10 @@ func (at *OracleTopSQLTask) collectorDo() { return } - inst, _, err := at.persist.GetInstanceByNameAndProjectID(at.ap.InstanceName, at.ap.ProjectId) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) + defer cancel() + inst, _, err := dms.GetInstanceInProjectByName(ctx, string(at.ap.ProjectId), at.ap.InstanceName) + if err != nil { at.logger.Warnf("get instance fail, error: %v", err) return @@ -536,7 +557,7 @@ func (at *OracleTopSQLTask) collectorDo() { } defer db.Close() - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel = context.WithCancel(context.Background()) defer cancel() sqls, err := db.QueryTopSQLs(ctx, at.ap.Params.GetParam("top_n").Int(), at.ap.Params.GetParam("order_by_column").String()) @@ -645,7 +666,10 @@ func (at *TiDBAuditLogTask) Audit() (*AuditResultResp, error) { DBType: at.ap.DBType, } } else { - instance, _, err := at.persist.GetInstanceByNameAndProjectID(at.ap.InstanceName, at.ap.ProjectId) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) + defer cancel() + + instance, _, err := dms.GetInstanceInProjectByName(ctx, string(at.ap.ProjectId), at.ap.InstanceName) if err != nil { return nil, err } @@ -1230,7 +1254,11 @@ func (at *MySQLProcesslistTask) collectorDo() { at.logger.Warnf("instance is not configured") return } - instance, _, err := at.persist.GetInstanceByNameAndProjectID(at.ap.InstanceName, at.ap.ProjectId) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*20) + defer cancel() + + instance, _, err := dms.GetInstanceInProjectByName(ctx, string(at.ap.ProjectId), at.ap.InstanceName) + if err != nil { return } diff --git a/sqle/server/clean.go b/sqle/server/clean.go index 00bc66e847..c8337b65a2 100644 --- a/sqle/server/clean.go +++ b/sqle/server/clean.go @@ -50,10 +50,10 @@ func (j *CleanJob) CleanExpiredWorkflows(entry *logrus.Entry) { for _, workflow := range workflows { err := st.DeleteWorkflow(workflow) if err != nil { - entry.Errorf("clean workflow %d error: %s", workflow.ID, err) + entry.Errorf("clean workflow %s error: %s", workflow.WorkflowId, err) break } - hasDeletedWorkflowIds = append(hasDeletedWorkflowIds, strconv.FormatUint(uint64(workflow.ID), 10)) + hasDeletedWorkflowIds = append(hasDeletedWorkflowIds, workflow.WorkflowId) } if len(hasDeletedWorkflowIds) > 0 { entry.Infof("clean workflow [%s] success", strings.Join(hasDeletedWorkflowIds, ", ")) diff --git a/sqle/server/ding_talk.go b/sqle/server/ding_talk.go index 7628b5b795..aa0d1c5477 100644 --- a/sqle/server/ding_talk.go +++ b/sqle/server/ding_talk.go @@ -1,10 +1,12 @@ package server import ( + "context" "fmt" - "strconv" + "strings" "time" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/model" imPkg "github.com/actiontech/sqle/sqle/pkg/im" "github.com/actiontech/sqle/sqle/pkg/im/dingding" @@ -53,23 +55,21 @@ func (j *DingTalkJob) dingTalkRotation(entry *logrus.Entry) { switch *approval.Result { case model.ApproveStatusAgree: - workflow, exist, err := st.GetWorkflowDetailById(strconv.Itoa(int(dingTalkInstance.WorkflowId))) + workflow, err := dms.GetWorkflowDetailByWorkflowId("", dingTalkInstance.WorkflowId, st.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { entry.Errorf("get workflow detail error: %v", err) continue } - if !exist { - entry.Errorf("workflow not exist, id: %d", dingTalkInstance.WorkflowId) - continue - } + if workflow.Record.Status == model.WorkflowStatusCancel { - entry.Errorf("workflow has canceled skip, id: %d", dingTalkInstance.WorkflowId) + entry.Errorf("workflow has canceled skip, id: %s", dingTalkInstance.WorkflowId) continue } nextStep := workflow.NextStep() userId := *approval.OperationRecords[1].UserId + user, err := getUserByUserId(d, userId, workflow.CurrentStep().Assignees) if err != nil { entry.Errorf("get user by user id error: %v", err) @@ -88,21 +88,18 @@ func (j *DingTalkJob) dingTalkRotation(entry *logrus.Entry) { } if nextStep.Template.Typ != model.WorkflowStepTypeSQLExecute { - imPkg.CreateApprove(strconv.Itoa(int(workflow.ID))) + imPkg.CreateApprove(string(workflow.ProjectId), workflow.WorkflowId) } case model.ApproveStatusRefuse: - workflow, exist, err := st.GetWorkflowDetailById(strconv.Itoa(int(dingTalkInstance.WorkflowId))) + workflow, err := dms.GetWorkflowDetailByWorkflowId("", dingTalkInstance.WorkflowId, st.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { entry.Errorf("get workflow detail error: %v", err) continue } - if !exist { - entry.Errorf("workflow not exist, id: %d", dingTalkInstance.WorkflowId) - continue - } + if workflow.Record.Status == model.WorkflowStatusCancel { - entry.Errorf("workflow has canceled skip, id: %d", dingTalkInstance.WorkflowId) + entry.Errorf("workflow has canceled skip, id: %s", dingTalkInstance.WorkflowId) continue } @@ -138,15 +135,19 @@ func (j *DingTalkJob) dingTalkRotation(entry *logrus.Entry) { } } -func getUserByUserId(d *dingding.DingTalk, userId string, assignees []*model.User) (*model.User, error) { +func getUserByUserId(d *dingding.DingTalk, userId string, assigneesUsers string) (*model.User, error) { + userMaps, err := dms.GetMapUsers(context.TODO(), strings.Split(assigneesUsers, ","), dms.GetDMSServerAddress()) + if err != nil { + return nil, err + } phone, err := d.GetMobileByUserID(userId) if err != nil { return nil, fmt.Errorf("get user mobile error: %v", err) } - for _, assignee := range assignees { - if assignee.Phone == phone { - return assignee, nil + for _, assigneeUser := range userMaps { + if assigneeUser.Phone == phone { + return assigneeUser, nil } } diff --git a/sqle/server/sqled.go b/sqle/server/sqled.go index 0fec30951d..ed1567210c 100644 --- a/sqle/server/sqled.go +++ b/sqle/server/sqled.go @@ -8,6 +8,7 @@ import ( "sync" "time" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/driver" "github.com/actiontech/sqle/sqle/utils" "github.com/go-sql-driver/mysql" @@ -65,6 +66,7 @@ func (s *Sqled) addTask(taskId string, typ int) (*action, error) { var p driver.Plugin var rules []*model.Rule var customRules []*model.CustomRule + var instance *model.Instance st := model.GetStorage() // var drvMgr driver.DriverManager entry := log.NewEntry().WithField("task_id", taskId) @@ -92,6 +94,18 @@ func (s *Sqled) addTask(taskId string, typ int) (*action, error) { err = errors.New(errors.TaskNotExist, fmt.Errorf("task not exist")) goto Error } + if task.InstanceId != 0 { + instance, exist, err = dms.GetInstancesById(context.Background(), task.InstanceId) + if err != nil { + goto Error + } + if !exist { + err = errors.New(errors.DataNotExist, fmt.Errorf("instance not exist")) + goto Error + } + + task.Instance = instance + } if err = action.validation(task); err != nil { goto Error @@ -99,7 +113,7 @@ func (s *Sqled) addTask(taskId string, typ int) (*action, error) { action.task = task // plugin will be closed by drvMgr in Sqled.do(). - rules, customRules, err = st.GetAllRulesByTmpNameAndProjectIdInstanceDBType("", nil, task.Instance, task.DBType) + rules, customRules, err = st.GetAllRulesByTmpNameAndProjectIdInstanceDBType("", "", task.Instance, task.DBType) if err != nil { goto Error } diff --git a/sqle/server/sqled_test.go b/sqle/server/sqled_test.go index d5d936085a..f0ba502009 100644 --- a/sqle/server/sqled_test.go +++ b/sqle/server/sqled_test.go @@ -164,8 +164,8 @@ func Test_action_audit_UpdateTask(t *testing.T) { } act := getAction([]string{"select * from t1"}, ActionTypeAudit, &mockDriver{}) - mock.ExpectQuery(regexp.QuoteMeta("SELECT `sql_whitelist`.* FROM `sql_whitelist` LEFT JOIN instances ON sql_whitelist.project_id = instances.project_id WHERE `sql_whitelist`.`deleted_at` IS NULL AND ((instances.id = ?))")). - WithArgs(1). + mock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `sql_whitelist` WHERE `sql_whitelist`.`deleted_at` IS NULL AND ((sql_whitelist.project_id = ?))")). + WithArgs(""). WillReturnRows(sqlmock.NewRows([]string{"value", "match_type"}).AddRow(whitelist.Value, whitelist.MatchType)) mock.ExpectBegin() @@ -208,13 +208,13 @@ func Test_action_execute(t *testing.T) { return nil }) - gomonkey.ApplyMethod(reflect.TypeOf(&model.Storage{}), "GetRulesFromRuleTemplateByName", func(_ *model.Storage, _ []uint, _ string) ([]*model.Rule, []*model.CustomRule, error) { + gomonkey.ApplyMethod(reflect.TypeOf(&model.Storage{}), "GetRulesFromRuleTemplateByName", func(_ *model.Storage, _ []string, _ string) ([]*model.Rule, []*model.CustomRule, error) { return nil, nil, nil }) } newDriver := func() (driver.Plugin, error) { - rules, _, err := model.GetStorage().GetAllRulesByTmpNameAndProjectIdInstanceDBType("", nil, nil, driverV2.DriverTypeMySQL) + rules, _, err := model.GetStorage().GetAllRulesByTmpNameAndProjectIdInstanceDBType("", "", nil, driverV2.DriverTypeMySQL) if err != nil { return nil, err } diff --git a/sqle/server/workflow_schedule.go b/sqle/server/workflow_schedule.go index ebec281615..fd8bfd5d9e 100644 --- a/sqle/server/workflow_schedule.go +++ b/sqle/server/workflow_schedule.go @@ -1,13 +1,16 @@ package server import ( + "context" "fmt" "strconv" "strings" "sync" "time" + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" "github.com/actiontech/sqle/sqle/common" + "github.com/actiontech/sqle/sqle/dms" "github.com/actiontech/sqle/sqle/errors" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" @@ -37,15 +40,11 @@ func (j *WorkflowScheduleJob) WorkflowSchedule(entry *logrus.Entry) { } now := time.Now() for _, workflow := range workflows { - w, exist, err := st.GetWorkflowDetailById(strconv.Itoa(int(workflow.ID))) + w, err := dms.GetWorkflowDetailByWorkflowId(string(workflow.ProjectId), workflow.WorkflowId, st.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { entry.Errorf("get workflow from storage error: %v", err) return } - if !exist { - entry.Errorf("workflow %s not found", workflow.Subject) - return - } currentStep := w.CurrentStep() if currentStep == nil { @@ -58,7 +57,7 @@ func (j *WorkflowScheduleJob) WorkflowSchedule(entry *logrus.Entry) { } entry.Infof("start to execute scheduled workflow %s", w.Subject) - needExecuteTaskIds := map[uint]uint{} + needExecuteTaskIds := map[uint]string{} for _, ir := range w.Record.InstanceRecords { if !ir.IsSQLExecuted && ir.ScheduledAt != nil && ir.ScheduledAt.Before(now) { needExecuteTaskIds[ir.TaskId] = ir.ScheduleUserId @@ -76,7 +75,7 @@ func (j *WorkflowScheduleJob) WorkflowSchedule(entry *logrus.Entry) { } } -func ExecuteWorkflow(workflow *model.Workflow, needExecTaskIdToUserId map[uint]uint) error { +func ExecuteWorkflow(workflow *model.Workflow, needExecTaskIdToUserId map[uint]string) error { s := model.GetStorage() // get task and check connection before to execute it. @@ -89,6 +88,14 @@ func ExecuteWorkflow(workflow *model.Workflow, needExecTaskIdToUserId map[uint]u if !exist { return errors.New(errors.DataNotExist, fmt.Errorf("task is not exist. taskID=%v", taskId)) } + instance, exist, err := dms.GetInstancesById(context.Background(), task.InstanceId) + if err != nil { + return err + } + if !exist { + return errors.New(errors.DataNotExist, fmt.Errorf("instance is not exist. instanceId=%v", task.InstanceId)) + } + task.Instance = instance if task.Instance == nil { return errors.New(errors.DataNotExist, fmt.Errorf("instance is not exist")) } @@ -152,9 +159,9 @@ func ExecuteWorkflow(workflow *model.Workflow, needExecTaskIdToUserId map[uint]u } if err != nil || task.Status == model.TaskStatusExecuteFailed { - go notification.NotifyWorkflow(fmt.Sprintf("%v", workflow.ID), notification.WorkflowNotifyTypeExecuteFail) + go notification.NotifyWorkflow(string(workflow.ProjectId), workflow.WorkflowId, notification.WorkflowNotifyTypeExecuteFail) } else { - go notification.NotifyWorkflow(fmt.Sprintf("%v", workflow.ID), notification.WorkflowNotifyTypeExecuteSuccess) + go notification.NotifyWorkflow(string(workflow.ProjectId), workflow.WorkflowId, notification.WorkflowNotifyTypeExecuteSuccess) } }() @@ -225,7 +232,7 @@ func ApproveWorkflowProcess(workflow *model.Workflow, user *model.User, s *model currentStep.State = model.WorkflowStepStateApprove now := time.Now() currentStep.OperateAt = &now - currentStep.OperationUserId = user.ID + currentStep.OperationUserId = user.GetIDStr() nextStep := workflow.NextStep() workflow.Record.CurrentWorkflowStepId = nextStep.ID if nextStep.Template.Typ == model.WorkflowStepTypeSQLExecute { @@ -237,7 +244,7 @@ func ApproveWorkflowProcess(workflow *model.Workflow, user *model.User, s *model return fmt.Errorf("update workflow status failed, %v", err) } - go notification.NotifyWorkflow(strconv.Itoa(int(workflow.ID)), notification.WorkflowNotifyTypeApprove) + go notification.NotifyWorkflow(string(workflow.ProjectId), workflow.WorkflowId, notification.WorkflowNotifyTypeApprove) return nil } @@ -248,7 +255,7 @@ func RejectWorkflowProcess(workflow *model.Workflow, reason string, user *model. currentStep.Reason = reason now := time.Now() currentStep.OperateAt = &now - currentStep.OperationUserId = user.ID + currentStep.OperationUserId = user.GetIDStr() workflow.Record.Status = model.WorkflowStatusReject workflow.Record.CurrentWorkflowStepId = 0 @@ -257,26 +264,23 @@ func RejectWorkflowProcess(workflow *model.Workflow, reason string, user *model. return fmt.Errorf("update workflow status failed, %v", err) } - go notification.NotifyWorkflow(fmt.Sprintf("%v", workflow.ID), notification.WorkflowNotifyTypeReject) + go notification.NotifyWorkflow(string(workflow.ProjectId), workflow.WorkflowId, notification.WorkflowNotifyTypeReject) return nil } -func ExecuteTasksProcess(workflowId string, projectName string, user *model.User) error { +func ExecuteTasksProcess(workflowId string, projectUid string, user *model.User) error { s := model.GetStorage() - workflow, exist, err := s.GetWorkflowDetailById(workflowId) + workflow, err := dms.GetWorkflowDetailByWorkflowId(projectUid, workflowId, s.GetWorkflowDetailWithoutInstancesByWorkflowID) if err != nil { return err } - if !exist { - return err - } - if err := PrepareForWorkflowExecution(projectName, workflow, user); err != nil { + if err = PrepareForWorkflowExecution(projectUid, workflow, user); err != nil { return err } - needExecTaskIds, err := GetNeedExecTaskIds(s, workflow, user) + needExecTaskIds, err := GetNeedExecTaskIds(workflow, user) if err != nil { return err } @@ -289,8 +293,8 @@ func ExecuteTasksProcess(workflowId string, projectName string, user *model.User return nil } -func PrepareForWorkflowExecution(projectName string, workflow *model.Workflow, user *model.User) error { - err := CheckCurrentUserCanOperateWorkflowByUser(user, &model.Project{Name: projectName}, workflow, []uint{}) +func PrepareForWorkflowExecution(projectUid string, workflow *model.Workflow, user *model.User) error { + err := CheckCurrentUserCanOperateWorkflowByUser(user, projectUid, workflow, []dmsV1.OpPermissionType{}) if err != nil { return err } @@ -312,10 +316,10 @@ func PrepareForWorkflowExecution(projectName string, workflow *model.Workflow, u return nil } -func GetNeedExecTaskIds(s *model.Storage, workflow *model.Workflow, user *model.User) (taskIds map[uint] /*task id*/ uint /*user id*/, err error) { - instances, err := s.GetInstancesByWorkflowID(workflow.ID) - if err != nil { - return nil, err +func GetNeedExecTaskIds(workflow *model.Workflow, user *model.User) (taskIds map[uint] /*task id*/ string /*user id*/, err error) { + instances := make([]*model.Instance, 0, len(workflow.Record.InstanceRecords)) + for _, item := range workflow.Record.InstanceRecords { + instances = append(instances, item.Instance) } // 有不在运维时间内的instances报错 var cannotExecuteInstanceNames []string @@ -330,32 +334,32 @@ func GetNeedExecTaskIds(s *model.Storage, workflow *model.Workflow, user *model. } // 定时的instances和已上线的跳过 - needExecTaskIds := make(map[uint]uint) + needExecTaskIds := make(map[uint]string) for _, instRecord := range workflow.Record.InstanceRecords { if instRecord.ScheduledAt != nil || instRecord.IsSQLExecuted { continue } - needExecTaskIds[instRecord.TaskId] = user.ID + needExecTaskIds[instRecord.TaskId] = user.GetIDStr() } return needExecTaskIds, nil } -func CheckCurrentUserCanOperateWorkflowByUser(user *model.User, project *model.Project, workflow *model.Workflow, ops []uint) error { +func CheckCurrentUserCanOperateWorkflowByUser(user *model.User, projectUid string, workflow *model.Workflow, ops []dmsV1.OpPermissionType) error { if user.Name == model.DefaultAdminUser { return nil } s := model.GetStorage() - - isManager, err := s.IsProjectManager(user.Name, project.Name) + up, err := dms.NewUserPermission(user.GetIDStr(), projectUid) if err != nil { return err } + isManager := up.IsProjectAdmin() if isManager { return nil } - access, err := s.UserCanAccessWorkflow(user, workflow) + access, err := s.UserCanAccessWorkflow(user.GetIDStr(), workflow) if err != nil { return err } @@ -363,16 +367,10 @@ func CheckCurrentUserCanOperateWorkflowByUser(user *model.User, project *model.P return nil } if len(ops) > 0 { - instances, err := s.GetInstancesByWorkflowID(workflow.ID) - if err != nil { - return err - } - ok, err := s.CheckUserHasOpToInstances(user, instances, ops) - if err != nil { - return err - } - if ok { - return nil + for _, item := range workflow.Record.InstanceRecords { + if !up.CanOpInstanceNoAdmin(item.Instance.GetIDStr(), ops...) { + return ErrWorkflowNoAccess + } } } diff --git a/sqle/sqled.go b/sqle/sqled.go index 4502b0f81f..f9212ec3ff 100644 --- a/sqle/sqled.go +++ b/sqle/sqled.go @@ -6,55 +6,63 @@ import ( "os/signal" "syscall" + dmsCommonAes "github.com/actiontech/dms/pkg/dms-common/pkg/aes" + "github.com/actiontech/dms/pkg/dms-common/pkg/http" "github.com/actiontech/sqle/sqle/api" - "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/service" + "github.com/actiontech/sqle/sqle/dms" + + // "github.com/actiontech/sqle/sqle/api/cloudbeaver_wrapper/service" "github.com/actiontech/sqle/sqle/config" "github.com/actiontech/sqle/sqle/driver" "github.com/actiontech/sqle/sqle/log" "github.com/actiontech/sqle/sqle/model" - "github.com/actiontech/sqle/sqle/notification/webhook" "github.com/actiontech/sqle/sqle/server" "github.com/actiontech/sqle/sqle/server/cluster" - "github.com/actiontech/sqle/sqle/utils" "github.com/facebookgo/grace/gracenet" ) -func Run(config *config.Config) error { +func Run(options *config.SqleOptions) error { // init logger - sqleCnf := config.Server.SqleCnf + sqleCnf := options.Service log.InitLogger(sqleCnf.LogPath, sqleCnf.LogMaxSizeMB, sqleCnf.LogMaxBackupNumber) defer log.ExitLogger() log.Logger().Infoln("starting sqled server") defer log.Logger().Info("stop sqled server") - if sqleCnf.EnableClusterMode && sqleCnf.ServerId == "" { + if sqleCnf.EnableClusterMode && options.ID == 0 { return fmt.Errorf("server id is required on cluster mode") } - secretKey := sqleCnf.SecretKey + secretKey := options.SecretKey if secretKey != "" { - if err := utils.SetSecretKey([]byte(secretKey)); err != nil { - return fmt.Errorf("set secret key error, %v, check your secret key in config file", err) + // reset jwt singing key, default dms token + if err := http.ResetJWTSigningKeyAndDefaultToken(secretKey); err != nil { + return err + } + + // reset aes secret key + if err := dmsCommonAes.ResetAesSecretKey(secretKey); err != nil { + return err } } defer driver.GetPluginManager().Stop() - if err := driver.GetPluginManager().Start(sqleCnf.PluginPath, config.Server.PluginConfig); err != nil { + if err := driver.GetPluginManager().Start(sqleCnf.PluginPath, options.Service.PluginConfig); err != nil { return fmt.Errorf("init plugins error: %v", err) } - service.InitSQLQueryConfig(sqleCnf.SqleServerPort, sqleCnf.EnableHttps, config.Server.SQLQueryConfig) + // service.InitSQLQueryConfig(sqleCnf.SqleServerPort, sqleCnf.EnableHttps, config.Server.SQLQueryConfig) - dbConfig := config.Server.DBCnf.MysqlCnf + dbConfig := options.Service.Database dbPassword := dbConfig.Password // Support using secret mysql password in sqled config, read secret_mysql_password first, // but you can still use mysql_password to be compatible with older versions. secretPassword := dbConfig.SecretPassword if secretPassword != "" { - password, err := utils.AesDecrypt(secretPassword) + password, err := dmsCommonAes.AesDecrypt(secretPassword) if err != nil { return fmt.Errorf("read db info from config file error, %d", err) } @@ -68,25 +76,27 @@ func Run(config *config.Config) error { } model.InitStorage(s) + err = dms.RegisterAsDMSTarget(options) + if err != nil { + return fmt.Errorf("register to dms failed :%v", err) + } + if sqleCnf.AutoMigrateTable { if err := s.AutoMigrate(); err != nil { return fmt.Errorf("auto migrate table failed: %v", err) } + + err := s.CreateDefaultWorkflowTemplateIfNotExist() + if err != nil { + return fmt.Errorf("create workflow template failed: %v", err) + } if err := s.CreateRulesIfNotExist(driver.GetPluginManager().GetAllRules()); err != nil { return fmt.Errorf("create rules failed while auto migrating table: %v", err) } - if err := s.CreateDefaultTemplate(driver.GetPluginManager().GetAllRules()); err != nil { + + if err := s.CreateDefaultTemplateIfNotExist(model.ProjectIdForGlobalRuleTemplate, driver.GetPluginManager().GetAllRules()); err != nil { return fmt.Errorf("create default template failed while auto migrating table: %v", err) } - if err := s.CreateAdminUser(); err != nil { - return fmt.Errorf("create default admin user failed while auto migrating table: %v", err) - } - if err := s.CreateDefaultProject(); err != nil { - return fmt.Errorf("create default project failed while auto migrating table: %v", err) - } - if err := s.CreateDefaultRole(); err != nil { - return fmt.Errorf("create default rule failed while auto migrating table: %v", err) - } } exitChan := make(chan struct{}) server.InitSqled(exitChan) @@ -96,28 +106,18 @@ func Run(config *config.Config) error { cluster.IsClusterMode = true log.Logger().Infoln("running sqled server on cluster mode") node = cluster.DefaultNode - node.Join(sqleCnf.ServerId) + node.Join(fmt.Sprintf("%v", options.ID)) defer node.Leave() } else { node = &cluster.NoClusterNode{} } - // webhook - { - cfg, _, err := s.GetWorkflowWebHookConfig() - if err != nil { - return fmt.Errorf("get workflow webhook config failed: %v", err) - } - webhook.UpdateWorkflowConfig(cfg.Enable, - cfg.MaxRetryTimes, cfg.RetryIntervalSeconds, cfg.URL, cfg.Token) - } - jm := server.NewServerJobManger(node) jm.Start() defer jm.Stop() net := &gracenet.Net{} - go api.StartApi(net, exitChan, sqleCnf) + go api.StartApi(net, exitChan, options) killChan := make(chan os.Signal, 1) // os.Kill is like kill -9 which kills a process immediately, can't be caught diff --git a/vendor/github.com/99designs/gqlgen/LICENSE b/vendor/github.com/99designs/gqlgen/LICENSE deleted file mode 100644 index 10bb21c07e..0000000000 --- a/vendor/github.com/99designs/gqlgen/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2020 gqlgen authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/99designs/gqlgen/api/generate.go b/vendor/github.com/99designs/gqlgen/api/generate.go deleted file mode 100644 index 6619dd5cd2..0000000000 --- a/vendor/github.com/99designs/gqlgen/api/generate.go +++ /dev/null @@ -1,139 +0,0 @@ -package api - -import ( - "fmt" - "regexp" - "syscall" - - "github.com/99designs/gqlgen/codegen" - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/plugin" - "github.com/99designs/gqlgen/plugin/federation" - "github.com/99designs/gqlgen/plugin/modelgen" - "github.com/99designs/gqlgen/plugin/resolvergen" -) - -func Generate(cfg *config.Config, option ...Option) error { - _ = syscall.Unlink(cfg.Exec.Filename) - if cfg.Model.IsDefined() { - _ = syscall.Unlink(cfg.Model.Filename) - } - - plugins := []plugin.Plugin{} - if cfg.Model.IsDefined() { - plugins = append(plugins, modelgen.New()) - } - plugins = append(plugins, resolvergen.New()) - if cfg.Federation.IsDefined() { - if cfg.Federation.Version == 0 { // default to using the user's choice of version, but if unset, try to sort out which federation version to use - urlRegex := regexp.MustCompile(`(?s)@link.*\(.*url:.*?"(.*?)"[^)]+\)`) // regex to grab the url of a link directive, should it exist - - // check the sources, and if one is marked as federation v2, we mark the entirety to be generated using that format - for _, v := range cfg.Sources { - cfg.Federation.Version = 1 - urlString := urlRegex.FindStringSubmatch(v.Input) - if urlString != nil && urlString[1] == "https://specs.apollo.dev/federation/v2.0" { - cfg.Federation.Version = 2 - break - } - } - } - plugins = append([]plugin.Plugin{federation.New(cfg.Federation.Version)}, plugins...) - } - - for _, o := range option { - o(cfg, &plugins) - } - - for _, p := range plugins { - if inj, ok := p.(plugin.EarlySourceInjector); ok { - if s := inj.InjectSourceEarly(); s != nil { - cfg.Sources = append(cfg.Sources, s) - } - } - } - - if err := cfg.LoadSchema(); err != nil { - return fmt.Errorf("failed to load schema: %w", err) - } - - for _, p := range plugins { - if inj, ok := p.(plugin.LateSourceInjector); ok { - if s := inj.InjectSourceLate(cfg.Schema); s != nil { - cfg.Sources = append(cfg.Sources, s) - } - } - } - - // LoadSchema again now we have everything - if err := cfg.LoadSchema(); err != nil { - return fmt.Errorf("failed to load schema: %w", err) - } - - if err := cfg.Init(); err != nil { - return fmt.Errorf("generating core failed: %w", err) - } - - for _, p := range plugins { - if mut, ok := p.(plugin.ConfigMutator); ok { - err := mut.MutateConfig(cfg) - if err != nil { - return fmt.Errorf("%s: %w", p.Name(), err) - } - } - } - // Merge again now that the generated models have been injected into the typemap - data, err := codegen.BuildData(cfg) - if err != nil { - return fmt.Errorf("merging type systems failed: %w", err) - } - - if err = codegen.GenerateCode(data); err != nil { - return fmt.Errorf("generating core failed: %w", err) - } - - if !cfg.SkipModTidy { - if err = cfg.Packages.ModTidy(); err != nil { - return fmt.Errorf("tidy failed: %w", err) - } - } - - for _, p := range plugins { - if mut, ok := p.(plugin.CodeGenerator); ok { - err := mut.GenerateCode(data) - if err != nil { - return fmt.Errorf("%s: %w", p.Name(), err) - } - } - } - - if err = codegen.GenerateCode(data); err != nil { - return fmt.Errorf("generating core failed: %w", err) - } - - if !cfg.SkipValidation { - if err := validate(cfg); err != nil { - return fmt.Errorf("validation failed: %w", err) - } - } - - return nil -} - -func validate(cfg *config.Config) error { - roots := []string{cfg.Exec.ImportPath()} - if cfg.Model.IsDefined() { - roots = append(roots, cfg.Model.ImportPath()) - } - - if cfg.Resolver.IsDefined() { - roots = append(roots, cfg.Resolver.ImportPath()) - } - - cfg.Packages.LoadAll(roots...) - errs := cfg.Packages.Errors() - if len(errs) > 0 { - return errs - } - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/api/option.go b/vendor/github.com/99designs/gqlgen/api/option.go deleted file mode 100644 index d376193dfe..0000000000 --- a/vendor/github.com/99designs/gqlgen/api/option.go +++ /dev/null @@ -1,47 +0,0 @@ -package api - -import ( - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/plugin" -) - -type Option func(cfg *config.Config, plugins *[]plugin.Plugin) - -func NoPlugins() Option { - return func(cfg *config.Config, plugins *[]plugin.Plugin) { - *plugins = nil - } -} - -func AddPlugin(p plugin.Plugin) Option { - return func(cfg *config.Config, plugins *[]plugin.Plugin) { - *plugins = append(*plugins, p) - } -} - -// PrependPlugin prepends plugin any existing plugins -func PrependPlugin(p plugin.Plugin) Option { - return func(cfg *config.Config, plugins *[]plugin.Plugin) { - *plugins = append([]plugin.Plugin{p}, *plugins...) - } -} - -// ReplacePlugin replaces any existing plugin with a matching plugin name -func ReplacePlugin(p plugin.Plugin) Option { - return func(cfg *config.Config, plugins *[]plugin.Plugin) { - if plugins != nil { - found := false - ps := *plugins - for i, o := range ps { - if p.Name() == o.Name() { - ps[i] = p - found = true - } - } - if !found { - ps = append(ps, p) - } - *plugins = ps - } - } -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/args.go b/vendor/github.com/99designs/gqlgen/codegen/args.go deleted file mode 100644 index 0fd30fffd5..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/args.go +++ /dev/null @@ -1,122 +0,0 @@ -package codegen - -import ( - "fmt" - "go/types" - "strings" - - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/codegen/templates" - "github.com/vektah/gqlparser/v2/ast" -) - -type ArgSet struct { - Args []*FieldArgument - FuncDecl string -} - -type FieldArgument struct { - *ast.ArgumentDefinition - TypeReference *config.TypeReference - VarName string // The name of the var in go - Object *Object // A link back to the parent object - Default interface{} // The default value - Directives []*Directive - Value interface{} // value set in Data -} - -// ImplDirectives get not Builtin and location ARGUMENT_DEFINITION directive -func (f *FieldArgument) ImplDirectives() []*Directive { - d := make([]*Directive, 0) - for i := range f.Directives { - if !f.Directives[i].Builtin && f.Directives[i].IsLocation(ast.LocationArgumentDefinition) { - d = append(d, f.Directives[i]) - } - } - - return d -} - -func (f *FieldArgument) DirectiveObjName() string { - return "rawArgs" -} - -func (f *FieldArgument) Stream() bool { - return f.Object != nil && f.Object.Stream -} - -func (b *builder) buildArg(obj *Object, arg *ast.ArgumentDefinition) (*FieldArgument, error) { - tr, err := b.Binder.TypeReference(arg.Type, nil) - if err != nil { - return nil, err - } - - argDirs, err := b.getDirectives(arg.Directives) - if err != nil { - return nil, err - } - newArg := FieldArgument{ - ArgumentDefinition: arg, - TypeReference: tr, - Object: obj, - VarName: templates.ToGoPrivate(arg.Name), - Directives: argDirs, - } - - if arg.DefaultValue != nil { - newArg.Default, err = arg.DefaultValue.Value(nil) - if err != nil { - return nil, fmt.Errorf("default value is not valid: %w", err) - } - } - - return &newArg, nil -} - -func (b *builder) bindArgs(field *Field, sig *types.Signature, params *types.Tuple) ([]*FieldArgument, error) { - n := params.Len() - newArgs := make([]*FieldArgument, 0, len(field.Args)) - // Accept variadic methods (i.e. have optional parameters). - if params.Len() > len(field.Args) && sig.Variadic() { - n = len(field.Args) - } -nextArg: - for j := 0; j < n; j++ { - param := params.At(j) - for _, oldArg := range field.Args { - if strings.EqualFold(oldArg.Name, param.Name()) { - tr, err := b.Binder.TypeReference(oldArg.Type, param.Type()) - if err != nil { - return nil, err - } - oldArg.TypeReference = tr - - newArgs = append(newArgs, oldArg) - continue nextArg - } - } - - // no matching arg found, abort - return nil, fmt.Errorf("arg %s not in schema", param.Name()) - } - - return newArgs, nil -} - -func (a *Data) Args() map[string][]*FieldArgument { - ret := map[string][]*FieldArgument{} - for _, o := range a.Objects { - for _, f := range o.Fields { - if len(f.Args) > 0 { - ret[f.ArgsFunc()] = f.Args - } - } - } - - for _, d := range a.Directives() { - if len(d.Args) > 0 { - ret[d.ArgsFunc()] = d.Args - } - } - return ret -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/args.gotpl b/vendor/github.com/99designs/gqlgen/codegen/args.gotpl deleted file mode 100644 index 7b541ae1f2..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/args.gotpl +++ /dev/null @@ -1,36 +0,0 @@ -{{ range $name, $args := .Args }} -func (ec *executionContext) {{ $name }}(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - {{- range $i, $arg := . }} - var arg{{$i}} {{ $arg.TypeReference.GO | ref}} - if tmp, ok := rawArgs[{{$arg.Name|quote}}]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField({{$arg.Name|quote}})) - {{- if $arg.ImplDirectives }} - directive0 := func(ctx context.Context) (interface{}, error) { return ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, tmp) } - {{ template "implDirectives" $arg }} - tmp, err = directive{{$arg.ImplDirectives|len}}(ctx) - if err != nil { - return nil, graphql.ErrorOnPath(ctx, err) - } - if data, ok := tmp.({{ $arg.TypeReference.GO | ref }}) ; ok { - arg{{$i}} = data - {{- if $arg.TypeReference.IsNilable }} - } else if tmp == nil { - arg{{$i}} = nil - {{- end }} - } else { - return nil, graphql.ErrorOnPath(ctx, fmt.Errorf(`unexpected type %T from directive, should be {{ $arg.TypeReference.GO }}`, tmp)) - } - {{- else }} - arg{{$i}}, err = ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, tmp) - if err != nil { - return nil, err - } - {{- end }} - } - args[{{$arg.Name|quote}}] = arg{{$i}} - {{- end }} - return args, nil -} -{{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/complexity.go b/vendor/github.com/99designs/gqlgen/codegen/complexity.go deleted file mode 100644 index e9c6a20ee8..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/complexity.go +++ /dev/null @@ -1,11 +0,0 @@ -package codegen - -func (o *Object) UniqueFields() map[string][]*Field { - m := map[string][]*Field{} - - for _, f := range o.Fields { - m[f.GoFieldName] = append(m[f.GoFieldName], f) - } - - return m -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/binder.go b/vendor/github.com/99designs/gqlgen/codegen/config/binder.go deleted file mode 100644 index bedc23bc61..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/config/binder.go +++ /dev/null @@ -1,493 +0,0 @@ -package config - -import ( - "errors" - "fmt" - "go/token" - "go/types" - - "golang.org/x/tools/go/packages" - - "github.com/99designs/gqlgen/codegen/templates" - "github.com/99designs/gqlgen/internal/code" - "github.com/vektah/gqlparser/v2/ast" -) - -var ErrTypeNotFound = errors.New("unable to find type") - -// Binder connects graphql types to golang types using static analysis -type Binder struct { - pkgs *code.Packages - schema *ast.Schema - cfg *Config - References []*TypeReference - SawInvalid bool - objectCache map[string]map[string]types.Object -} - -func (c *Config) NewBinder() *Binder { - return &Binder{ - pkgs: c.Packages, - schema: c.Schema, - cfg: c, - } -} - -func (b *Binder) TypePosition(typ types.Type) token.Position { - named, isNamed := typ.(*types.Named) - if !isNamed { - return token.Position{ - Filename: "unknown", - } - } - - return b.ObjectPosition(named.Obj()) -} - -func (b *Binder) ObjectPosition(typ types.Object) token.Position { - if typ == nil { - return token.Position{ - Filename: "unknown", - } - } - pkg := b.pkgs.Load(typ.Pkg().Path()) - return pkg.Fset.Position(typ.Pos()) -} - -func (b *Binder) FindTypeFromName(name string) (types.Type, error) { - pkgName, typeName := code.PkgAndType(name) - return b.FindType(pkgName, typeName) -} - -func (b *Binder) FindType(pkgName string, typeName string) (types.Type, error) { - if pkgName == "" { - if typeName == "map[string]interface{}" { - return MapType, nil - } - - if typeName == "interface{}" { - return InterfaceType, nil - } - } - - obj, err := b.FindObject(pkgName, typeName) - if err != nil { - return nil, err - } - - if fun, isFunc := obj.(*types.Func); isFunc { - return fun.Type().(*types.Signature).Params().At(0).Type(), nil - } - return obj.Type(), nil -} - -var ( - MapType = types.NewMap(types.Typ[types.String], types.NewInterfaceType(nil, nil).Complete()) - InterfaceType = types.NewInterfaceType(nil, nil) -) - -func (b *Binder) DefaultUserObject(name string) (types.Type, error) { - models := b.cfg.Models[name].Model - if len(models) == 0 { - return nil, fmt.Errorf(name + " not found in typemap") - } - - if models[0] == "map[string]interface{}" { - return MapType, nil - } - - if models[0] == "interface{}" { - return InterfaceType, nil - } - - pkgName, typeName := code.PkgAndType(models[0]) - if pkgName == "" { - return nil, fmt.Errorf("missing package name for %s", name) - } - - obj, err := b.FindObject(pkgName, typeName) - if err != nil { - return nil, err - } - - return obj.Type(), nil -} - -func (b *Binder) FindObject(pkgName string, typeName string) (types.Object, error) { - if pkgName == "" { - return nil, fmt.Errorf("package cannot be nil") - } - - pkg := b.pkgs.LoadWithTypes(pkgName) - if pkg == nil { - err := b.pkgs.Errors() - if err != nil { - return nil, fmt.Errorf("package could not be loaded: %s.%s: %w", pkgName, typeName, err) - } - return nil, fmt.Errorf("required package was not loaded: %s.%s", pkgName, typeName) - } - - if b.objectCache == nil { - b.objectCache = make(map[string]map[string]types.Object, b.pkgs.Count()) - } - - defsIndex, ok := b.objectCache[pkgName] - if !ok { - defsIndex = indexDefs(pkg) - b.objectCache[pkgName] = defsIndex - } - - // function based marshalers take precedence - if val, ok := defsIndex["Marshal"+typeName]; ok { - return val, nil - } - - if val, ok := defsIndex[typeName]; ok { - return val, nil - } - - return nil, fmt.Errorf("%w: %s.%s", ErrTypeNotFound, pkgName, typeName) -} - -func indexDefs(pkg *packages.Package) map[string]types.Object { - res := make(map[string]types.Object) - - scope := pkg.Types.Scope() - for astNode, def := range pkg.TypesInfo.Defs { - // only look at defs in the top scope - if def == nil { - continue - } - parent := def.Parent() - if parent == nil || parent != scope { - continue - } - - if _, ok := res[astNode.Name]; !ok { - // The above check may not be really needed, it is only here to have a consistent behavior with - // previous implementation of FindObject() function which only honored the first inclusion of a def. - // If this is still needed, we can consider something like sync.Map.LoadOrStore() to avoid two lookups. - res[astNode.Name] = def - } - } - - return res -} - -func (b *Binder) PointerTo(ref *TypeReference) *TypeReference { - newRef := *ref - newRef.GO = types.NewPointer(ref.GO) - b.References = append(b.References, &newRef) - return &newRef -} - -// TypeReference is used by args and field types. The Definition can refer to both input and output types. -type TypeReference struct { - Definition *ast.Definition - GQL *ast.Type - GO types.Type // Type of the field being bound. Could be a pointer or a value type of Target. - Target types.Type // The actual type that we know how to bind to. May require pointer juggling when traversing to fields. - CastType types.Type // Before calling marshalling functions cast from/to this base type - Marshaler *types.Func // When using external marshalling functions this will point to the Marshal function - Unmarshaler *types.Func // When using external marshalling functions this will point to the Unmarshal function - IsMarshaler bool // Does the type implement graphql.Marshaler and graphql.Unmarshaler - IsContext bool // Is the Marshaler/Unmarshaller the context version; applies to either the method or interface variety. -} - -func (ref *TypeReference) Elem() *TypeReference { - if p, isPtr := ref.GO.(*types.Pointer); isPtr { - newRef := *ref - newRef.GO = p.Elem() - return &newRef - } - - if ref.IsSlice() { - newRef := *ref - newRef.GO = ref.GO.(*types.Slice).Elem() - newRef.GQL = ref.GQL.Elem - return &newRef - } - return nil -} - -func (t *TypeReference) IsPtr() bool { - _, isPtr := t.GO.(*types.Pointer) - return isPtr -} - -// fix for https://github.com/golang/go/issues/31103 may make it possible to remove this (may still be useful) -func (t *TypeReference) IsPtrToPtr() bool { - if p, isPtr := t.GO.(*types.Pointer); isPtr { - _, isPtr := p.Elem().(*types.Pointer) - return isPtr - } - return false -} - -func (t *TypeReference) IsNilable() bool { - return IsNilable(t.GO) -} - -func (t *TypeReference) IsSlice() bool { - _, isSlice := t.GO.(*types.Slice) - return t.GQL.Elem != nil && isSlice -} - -func (t *TypeReference) IsPtrToSlice() bool { - if t.IsPtr() { - _, isPointerToSlice := t.GO.(*types.Pointer).Elem().(*types.Slice) - return isPointerToSlice - } - return false -} - -func (t *TypeReference) IsNamed() bool { - _, isSlice := t.GO.(*types.Named) - return isSlice -} - -func (t *TypeReference) IsStruct() bool { - _, isStruct := t.GO.Underlying().(*types.Struct) - return isStruct -} - -func (t *TypeReference) IsScalar() bool { - return t.Definition.Kind == ast.Scalar -} - -func (t *TypeReference) UniquenessKey() string { - nullability := "O" - if t.GQL.NonNull { - nullability = "N" - } - - elemNullability := "" - if t.GQL.Elem != nil && t.GQL.Elem.NonNull { - // Fix for #896 - elemNullability = "ᚄ" - } - return nullability + t.Definition.Name + "2" + templates.TypeIdentifier(t.GO) + elemNullability -} - -func (t *TypeReference) MarshalFunc() string { - if t.Definition == nil { - panic(errors.New("Definition missing for " + t.GQL.Name())) - } - - if t.Definition.Kind == ast.InputObject { - return "" - } - - return "marshal" + t.UniquenessKey() -} - -func (t *TypeReference) UnmarshalFunc() string { - if t.Definition == nil { - panic(errors.New("Definition missing for " + t.GQL.Name())) - } - - if !t.Definition.IsInputType() { - return "" - } - - return "unmarshal" + t.UniquenessKey() -} - -func (t *TypeReference) IsTargetNilable() bool { - return IsNilable(t.Target) -} - -func (b *Binder) PushRef(ret *TypeReference) { - b.References = append(b.References, ret) -} - -func isMap(t types.Type) bool { - if t == nil { - return true - } - _, ok := t.(*types.Map) - return ok -} - -func isIntf(t types.Type) bool { - if t == nil { - return true - } - _, ok := t.(*types.Interface) - return ok -} - -func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret *TypeReference, err error) { - if !isValid(bindTarget) { - b.SawInvalid = true - return nil, fmt.Errorf("%s has an invalid type", schemaType.Name()) - } - - var pkgName, typeName string - def := b.schema.Types[schemaType.Name()] - defer func() { - if err == nil && ret != nil { - b.PushRef(ret) - } - }() - - if len(b.cfg.Models[schemaType.Name()].Model) == 0 { - return nil, fmt.Errorf("%s was not found", schemaType.Name()) - } - - for _, model := range b.cfg.Models[schemaType.Name()].Model { - if model == "map[string]interface{}" { - if !isMap(bindTarget) { - continue - } - return &TypeReference{ - Definition: def, - GQL: schemaType, - GO: MapType, - }, nil - } - - if model == "interface{}" { - if !isIntf(bindTarget) { - continue - } - return &TypeReference{ - Definition: def, - GQL: schemaType, - GO: InterfaceType, - }, nil - } - - pkgName, typeName = code.PkgAndType(model) - if pkgName == "" { - return nil, fmt.Errorf("missing package name for %s", schemaType.Name()) - } - - ref := &TypeReference{ - Definition: def, - GQL: schemaType, - } - - obj, err := b.FindObject(pkgName, typeName) - if err != nil { - return nil, err - } - - if fun, isFunc := obj.(*types.Func); isFunc { - ref.GO = fun.Type().(*types.Signature).Params().At(0).Type() - ref.IsContext = fun.Type().(*types.Signature).Results().At(0).Type().String() == "github.com/99designs/gqlgen/graphql.ContextMarshaler" - ref.Marshaler = fun - ref.Unmarshaler = types.NewFunc(0, fun.Pkg(), "Unmarshal"+typeName, nil) - } else if hasMethod(obj.Type(), "MarshalGQLContext") && hasMethod(obj.Type(), "UnmarshalGQLContext") { - ref.GO = obj.Type() - ref.IsContext = true - ref.IsMarshaler = true - } else if hasMethod(obj.Type(), "MarshalGQL") && hasMethod(obj.Type(), "UnmarshalGQL") { - ref.GO = obj.Type() - ref.IsMarshaler = true - } else if underlying := basicUnderlying(obj.Type()); def.IsLeafType() && underlying != nil && underlying.Kind() == types.String { - // TODO delete before v1. Backwards compatibility case for named types wrapping strings (see #595) - - ref.GO = obj.Type() - ref.CastType = underlying - - underlyingRef, err := b.TypeReference(&ast.Type{NamedType: "String"}, nil) - if err != nil { - return nil, err - } - - ref.Marshaler = underlyingRef.Marshaler - ref.Unmarshaler = underlyingRef.Unmarshaler - } else { - ref.GO = obj.Type() - } - - ref.Target = ref.GO - ref.GO = b.CopyModifiersFromAst(schemaType, ref.GO) - - if bindTarget != nil { - if err = code.CompatibleTypes(ref.GO, bindTarget); err != nil { - continue - } - ref.GO = bindTarget - } - - return ref, nil - } - - return nil, fmt.Errorf("%s is incompatible with %s", schemaType.Name(), bindTarget.String()) -} - -func isValid(t types.Type) bool { - basic, isBasic := t.(*types.Basic) - if !isBasic { - return true - } - return basic.Kind() != types.Invalid -} - -func (b *Binder) CopyModifiersFromAst(t *ast.Type, base types.Type) types.Type { - if t.Elem != nil { - child := b.CopyModifiersFromAst(t.Elem, base) - if _, isStruct := child.Underlying().(*types.Struct); isStruct && !b.cfg.OmitSliceElementPointers { - child = types.NewPointer(child) - } - return types.NewSlice(child) - } - - var isInterface bool - if named, ok := base.(*types.Named); ok { - _, isInterface = named.Underlying().(*types.Interface) - } - - if !isInterface && !IsNilable(base) && !t.NonNull { - return types.NewPointer(base) - } - - return base -} - -func IsNilable(t types.Type) bool { - if namedType, isNamed := t.(*types.Named); isNamed { - return IsNilable(namedType.Underlying()) - } - _, isPtr := t.(*types.Pointer) - _, isMap := t.(*types.Map) - _, isInterface := t.(*types.Interface) - _, isSlice := t.(*types.Slice) - _, isChan := t.(*types.Chan) - return isPtr || isMap || isInterface || isSlice || isChan -} - -func hasMethod(it types.Type, name string) bool { - if ptr, isPtr := it.(*types.Pointer); isPtr { - it = ptr.Elem() - } - namedType, ok := it.(*types.Named) - if !ok { - return false - } - - for i := 0; i < namedType.NumMethods(); i++ { - if namedType.Method(i).Name() == name { - return true - } - } - return false -} - -func basicUnderlying(it types.Type) *types.Basic { - if ptr, isPtr := it.(*types.Pointer); isPtr { - it = ptr.Elem() - } - namedType, ok := it.(*types.Named) - if !ok { - return nil - } - - if basic, ok := namedType.Underlying().(*types.Basic); ok { - return basic - } - - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/config.go b/vendor/github.com/99designs/gqlgen/codegen/config/config.go deleted file mode 100644 index c6de8625f0..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/config/config.go +++ /dev/null @@ -1,656 +0,0 @@ -package config - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "regexp" - "sort" - "strings" - - "github.com/99designs/gqlgen/internal/code" - "github.com/vektah/gqlparser/v2" - "github.com/vektah/gqlparser/v2/ast" - "gopkg.in/yaml.v3" -) - -type Config struct { - SchemaFilename StringList `yaml:"schema,omitempty"` - Exec ExecConfig `yaml:"exec"` - Model PackageConfig `yaml:"model,omitempty"` - Federation PackageConfig `yaml:"federation,omitempty"` - Resolver ResolverConfig `yaml:"resolver,omitempty"` - AutoBind []string `yaml:"autobind"` - Models TypeMap `yaml:"models,omitempty"` - StructTag string `yaml:"struct_tag,omitempty"` - Directives map[string]DirectiveConfig `yaml:"directives,omitempty"` - OmitSliceElementPointers bool `yaml:"omit_slice_element_pointers,omitempty"` - OmitGetters bool `yaml:"omit_getters,omitempty"` - StructFieldsAlwaysPointers bool `yaml:"struct_fields_always_pointers,omitempty"` - ResolversAlwaysReturnPointers bool `yaml:"resolvers_always_return_pointers,omitempty"` - SkipValidation bool `yaml:"skip_validation,omitempty"` - SkipModTidy bool `yaml:"skip_mod_tidy,omitempty"` - Sources []*ast.Source `yaml:"-"` - Packages *code.Packages `yaml:"-"` - Schema *ast.Schema `yaml:"-"` - - // Deprecated: use Federation instead. Will be removed next release - Federated bool `yaml:"federated,omitempty"` -} - -var cfgFilenames = []string{".gqlgen.yml", "gqlgen.yml", "gqlgen.yaml"} - -// DefaultConfig creates a copy of the default config -func DefaultConfig() *Config { - return &Config{ - SchemaFilename: StringList{"schema.graphql"}, - Model: PackageConfig{Filename: "models_gen.go"}, - Exec: ExecConfig{Filename: "generated.go"}, - Directives: map[string]DirectiveConfig{}, - Models: TypeMap{}, - StructFieldsAlwaysPointers: true, - ResolversAlwaysReturnPointers: true, - } -} - -// LoadDefaultConfig loads the default config so that it is ready to be used -func LoadDefaultConfig() (*Config, error) { - config := DefaultConfig() - - for _, filename := range config.SchemaFilename { - filename = filepath.ToSlash(filename) - var err error - var schemaRaw []byte - schemaRaw, err = os.ReadFile(filename) - if err != nil { - return nil, fmt.Errorf("unable to open schema: %w", err) - } - - config.Sources = append(config.Sources, &ast.Source{Name: filename, Input: string(schemaRaw)}) - } - - return config, nil -} - -// LoadConfigFromDefaultLocations looks for a config file in the current directory, and all parent directories -// walking up the tree. The closest config file will be returned. -func LoadConfigFromDefaultLocations() (*Config, error) { - cfgFile, err := findCfg() - if err != nil { - return nil, err - } - - err = os.Chdir(filepath.Dir(cfgFile)) - if err != nil { - return nil, fmt.Errorf("unable to enter config dir: %w", err) - } - return LoadConfig(cfgFile) -} - -var path2regex = strings.NewReplacer( - `.`, `\.`, - `*`, `.+`, - `\`, `[\\/]`, - `/`, `[\\/]`, -) - -// LoadConfig reads the gqlgen.yml config file -func LoadConfig(filename string) (*Config, error) { - config := DefaultConfig() - - b, err := os.ReadFile(filename) - if err != nil { - return nil, fmt.Errorf("unable to read config: %w", err) - } - - dec := yaml.NewDecoder(bytes.NewReader(b)) - dec.KnownFields(true) - - if err := dec.Decode(config); err != nil { - return nil, fmt.Errorf("unable to parse config: %w", err) - } - - if err := CompleteConfig(config); err != nil { - return nil, err - } - - return config, nil -} - -// CompleteConfig fills in the schema and other values to a config loaded from -// YAML. -func CompleteConfig(config *Config) error { - defaultDirectives := map[string]DirectiveConfig{ - "skip": {SkipRuntime: true}, - "include": {SkipRuntime: true}, - "deprecated": {SkipRuntime: true}, - "specifiedBy": {SkipRuntime: true}, - } - - for key, value := range defaultDirectives { - if _, defined := config.Directives[key]; !defined { - config.Directives[key] = value - } - } - - preGlobbing := config.SchemaFilename - config.SchemaFilename = StringList{} - for _, f := range preGlobbing { - var matches []string - - // for ** we want to override default globbing patterns and walk all - // subdirectories to match schema files. - if strings.Contains(f, "**") { - pathParts := strings.SplitN(f, "**", 2) - rest := strings.TrimPrefix(strings.TrimPrefix(pathParts[1], `\`), `/`) - // turn the rest of the glob into a regex, anchored only at the end because ** allows - // for any number of dirs in between and walk will let us match against the full path name - globRe := regexp.MustCompile(path2regex.Replace(rest) + `$`) - - if err := filepath.Walk(pathParts[0], func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if globRe.MatchString(strings.TrimPrefix(path, pathParts[0])) { - matches = append(matches, path) - } - - return nil - }); err != nil { - return fmt.Errorf("failed to walk schema at root %s: %w", pathParts[0], err) - } - } else { - var err error - matches, err = filepath.Glob(f) - if err != nil { - return fmt.Errorf("failed to glob schema filename %s: %w", f, err) - } - } - - for _, m := range matches { - if config.SchemaFilename.Has(m) { - continue - } - config.SchemaFilename = append(config.SchemaFilename, m) - } - } - - for _, filename := range config.SchemaFilename { - filename = filepath.ToSlash(filename) - var err error - var schemaRaw []byte - schemaRaw, err = os.ReadFile(filename) - if err != nil { - return fmt.Errorf("unable to open schema: %w", err) - } - - config.Sources = append(config.Sources, &ast.Source{Name: filename, Input: string(schemaRaw)}) - } - return nil -} - -func (c *Config) Init() error { - if c.Packages == nil { - c.Packages = &code.Packages{} - } - - if c.Schema == nil { - if err := c.LoadSchema(); err != nil { - return err - } - } - - err := c.injectTypesFromSchema() - if err != nil { - return err - } - - err = c.autobind() - if err != nil { - return err - } - - c.injectBuiltins() - // prefetch all packages in one big packages.Load call - c.Packages.LoadAll(c.packageList()...) - - // check everything is valid on the way out - err = c.check() - if err != nil { - return err - } - - return nil -} - -func (c *Config) packageList() []string { - pkgs := []string{ - "github.com/99designs/gqlgen/graphql", - "github.com/99designs/gqlgen/graphql/introspection", - } - pkgs = append(pkgs, c.Models.ReferencedPackages()...) - pkgs = append(pkgs, c.AutoBind...) - return pkgs -} - -func (c *Config) ReloadAllPackages() { - c.Packages.ReloadAll(c.packageList()...) -} - -func (c *Config) injectTypesFromSchema() error { - c.Directives["goModel"] = DirectiveConfig{ - SkipRuntime: true, - } - - c.Directives["goField"] = DirectiveConfig{ - SkipRuntime: true, - } - - c.Directives["goTag"] = DirectiveConfig{ - SkipRuntime: true, - } - - for _, schemaType := range c.Schema.Types { - if schemaType == c.Schema.Query || schemaType == c.Schema.Mutation || schemaType == c.Schema.Subscription { - continue - } - - if bd := schemaType.Directives.ForName("goModel"); bd != nil { - if ma := bd.Arguments.ForName("model"); ma != nil { - if mv, err := ma.Value.Value(nil); err == nil { - c.Models.Add(schemaType.Name, mv.(string)) - } - } - if ma := bd.Arguments.ForName("models"); ma != nil { - if mvs, err := ma.Value.Value(nil); err == nil { - for _, mv := range mvs.([]interface{}) { - c.Models.Add(schemaType.Name, mv.(string)) - } - } - } - } - - if schemaType.Kind == ast.Object || schemaType.Kind == ast.InputObject { - for _, field := range schemaType.Fields { - if fd := field.Directives.ForName("goField"); fd != nil { - forceResolver := c.Models[schemaType.Name].Fields[field.Name].Resolver - fieldName := c.Models[schemaType.Name].Fields[field.Name].FieldName - - if ra := fd.Arguments.ForName("forceResolver"); ra != nil { - if fr, err := ra.Value.Value(nil); err == nil { - forceResolver = fr.(bool) - } - } - - if na := fd.Arguments.ForName("name"); na != nil { - if fr, err := na.Value.Value(nil); err == nil { - fieldName = fr.(string) - } - } - - if c.Models[schemaType.Name].Fields == nil { - c.Models[schemaType.Name] = TypeMapEntry{ - Model: c.Models[schemaType.Name].Model, - Fields: map[string]TypeMapField{}, - } - } - - c.Models[schemaType.Name].Fields[field.Name] = TypeMapField{ - FieldName: fieldName, - Resolver: forceResolver, - } - } - } - } - } - - return nil -} - -type TypeMapEntry struct { - Model StringList `yaml:"model"` - Fields map[string]TypeMapField `yaml:"fields,omitempty"` -} - -type TypeMapField struct { - Resolver bool `yaml:"resolver"` - FieldName string `yaml:"fieldName"` - GeneratedMethod string `yaml:"-"` -} - -type StringList []string - -func (a *StringList) UnmarshalYAML(unmarshal func(interface{}) error) error { - var single string - err := unmarshal(&single) - if err == nil { - *a = []string{single} - return nil - } - - var multi []string - err = unmarshal(&multi) - if err != nil { - return err - } - - *a = multi - return nil -} - -func (a StringList) Has(file string) bool { - for _, existing := range a { - if existing == file { - return true - } - } - return false -} - -func (c *Config) check() error { - if c.Models == nil { - c.Models = TypeMap{} - } - - type FilenamePackage struct { - Filename string - Package string - Declaree string - } - - fileList := map[string][]FilenamePackage{} - - if err := c.Models.Check(); err != nil { - return fmt.Errorf("config.models: %w", err) - } - if err := c.Exec.Check(); err != nil { - return fmt.Errorf("config.exec: %w", err) - } - fileList[c.Exec.ImportPath()] = append(fileList[c.Exec.ImportPath()], FilenamePackage{ - Filename: c.Exec.Filename, - Package: c.Exec.Package, - Declaree: "exec", - }) - - if c.Model.IsDefined() { - if err := c.Model.Check(); err != nil { - return fmt.Errorf("config.model: %w", err) - } - fileList[c.Model.ImportPath()] = append(fileList[c.Model.ImportPath()], FilenamePackage{ - Filename: c.Model.Filename, - Package: c.Model.Package, - Declaree: "model", - }) - } - if c.Resolver.IsDefined() { - if err := c.Resolver.Check(); err != nil { - return fmt.Errorf("config.resolver: %w", err) - } - fileList[c.Resolver.ImportPath()] = append(fileList[c.Resolver.ImportPath()], FilenamePackage{ - Filename: c.Resolver.Filename, - Package: c.Resolver.Package, - Declaree: "resolver", - }) - } - if c.Federation.IsDefined() { - if err := c.Federation.Check(); err != nil { - return fmt.Errorf("config.federation: %w", err) - } - fileList[c.Federation.ImportPath()] = append(fileList[c.Federation.ImportPath()], FilenamePackage{ - Filename: c.Federation.Filename, - Package: c.Federation.Package, - Declaree: "federation", - }) - if c.Federation.ImportPath() != c.Exec.ImportPath() { - return fmt.Errorf("federation and exec must be in the same package") - } - } - if c.Federated { - return fmt.Errorf("federated has been removed, instead use\nfederation:\n filename: path/to/federated.go") - } - - for importPath, pkg := range fileList { - for _, file1 := range pkg { - for _, file2 := range pkg { - if file1.Package != file2.Package { - return fmt.Errorf("%s and %s define the same import path (%s) with different package names (%s vs %s)", - file1.Declaree, - file2.Declaree, - importPath, - file1.Package, - file2.Package, - ) - } - } - } - } - - return nil -} - -type TypeMap map[string]TypeMapEntry - -func (tm TypeMap) Exists(typeName string) bool { - _, ok := tm[typeName] - return ok -} - -func (tm TypeMap) UserDefined(typeName string) bool { - m, ok := tm[typeName] - return ok && len(m.Model) > 0 -} - -func (tm TypeMap) Check() error { - for typeName, entry := range tm { - for _, model := range entry.Model { - if strings.LastIndex(model, ".") < strings.LastIndex(model, "/") { - return fmt.Errorf("model %s: invalid type specifier \"%s\" - you need to specify a struct to map to", typeName, entry.Model) - } - } - } - return nil -} - -func (tm TypeMap) ReferencedPackages() []string { - var pkgs []string - - for _, typ := range tm { - for _, model := range typ.Model { - if model == "map[string]interface{}" || model == "interface{}" { - continue - } - pkg, _ := code.PkgAndType(model) - if pkg == "" || inStrSlice(pkgs, pkg) { - continue - } - pkgs = append(pkgs, code.QualifyPackagePath(pkg)) - } - } - - sort.Slice(pkgs, func(i, j int) bool { - return pkgs[i] > pkgs[j] - }) - return pkgs -} - -func (tm TypeMap) Add(name string, goType string) { - modelCfg := tm[name] - modelCfg.Model = append(modelCfg.Model, goType) - tm[name] = modelCfg -} - -type DirectiveConfig struct { - SkipRuntime bool `yaml:"skip_runtime"` -} - -func inStrSlice(haystack []string, needle string) bool { - for _, v := range haystack { - if needle == v { - return true - } - } - - return false -} - -// findCfg searches for the config file in this directory and all parents up the tree -// looking for the closest match -func findCfg() (string, error) { - dir, err := os.Getwd() - if err != nil { - return "", fmt.Errorf("unable to get working dir to findCfg: %w", err) - } - - cfg := findCfgInDir(dir) - - for cfg == "" && dir != filepath.Dir(dir) { - dir = filepath.Dir(dir) - cfg = findCfgInDir(dir) - } - - if cfg == "" { - return "", os.ErrNotExist - } - - return cfg, nil -} - -func findCfgInDir(dir string) string { - for _, cfgName := range cfgFilenames { - path := filepath.Join(dir, cfgName) - if _, err := os.Stat(path); err == nil { - return path - } - } - return "" -} - -func (c *Config) autobind() error { - if len(c.AutoBind) == 0 { - return nil - } - - ps := c.Packages.LoadAll(c.AutoBind...) - - for _, t := range c.Schema.Types { - if c.Models.UserDefined(t.Name) { - continue - } - - for i, p := range ps { - if p == nil || p.Module == nil { - return fmt.Errorf("unable to load %s - make sure you're using an import path to a package that exists", c.AutoBind[i]) - } - if t := p.Types.Scope().Lookup(t.Name); t != nil { - c.Models.Add(t.Name(), t.Pkg().Path()+"."+t.Name()) - break - } - } - } - - for i, t := range c.Models { - for j, m := range t.Model { - pkg, typename := code.PkgAndType(m) - - // skip anything that looks like an import path - if strings.Contains(pkg, "/") { - continue - } - - for _, p := range ps { - if p.Name != pkg { - continue - } - if t := p.Types.Scope().Lookup(typename); t != nil { - c.Models[i].Model[j] = t.Pkg().Path() + "." + t.Name() - break - } - } - } - } - - return nil -} - -func (c *Config) injectBuiltins() { - builtins := TypeMap{ - "__Directive": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Directive"}}, - "__DirectiveLocation": {Model: StringList{"github.com/99designs/gqlgen/graphql.String"}}, - "__Type": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Type"}}, - "__TypeKind": {Model: StringList{"github.com/99designs/gqlgen/graphql.String"}}, - "__Field": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Field"}}, - "__EnumValue": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.EnumValue"}}, - "__InputValue": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.InputValue"}}, - "__Schema": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Schema"}}, - "Float": {Model: StringList{"github.com/99designs/gqlgen/graphql.FloatContext"}}, - "String": {Model: StringList{"github.com/99designs/gqlgen/graphql.String"}}, - "Boolean": {Model: StringList{"github.com/99designs/gqlgen/graphql.Boolean"}}, - "Int": {Model: StringList{ - "github.com/99designs/gqlgen/graphql.Int", - "github.com/99designs/gqlgen/graphql.Int32", - "github.com/99designs/gqlgen/graphql.Int64", - }}, - "ID": { - Model: StringList{ - "github.com/99designs/gqlgen/graphql.ID", - "github.com/99designs/gqlgen/graphql.IntID", - }, - }, - } - - for typeName, entry := range builtins { - if !c.Models.Exists(typeName) { - c.Models[typeName] = entry - } - } - - // These are additional types that are injected if defined in the schema as scalars. - extraBuiltins := TypeMap{ - "Time": {Model: StringList{"github.com/99designs/gqlgen/graphql.Time"}}, - "Map": {Model: StringList{"github.com/99designs/gqlgen/graphql.Map"}}, - "Upload": {Model: StringList{"github.com/99designs/gqlgen/graphql.Upload"}}, - "Any": {Model: StringList{"github.com/99designs/gqlgen/graphql.Any"}}, - } - - for typeName, entry := range extraBuiltins { - if t, ok := c.Schema.Types[typeName]; !c.Models.Exists(typeName) && ok && t.Kind == ast.Scalar { - c.Models[typeName] = entry - } - } -} - -func (c *Config) LoadSchema() error { - if c.Packages != nil { - c.Packages = &code.Packages{} - } - - if err := c.check(); err != nil { - return err - } - - schema, err := gqlparser.LoadSchema(c.Sources...) - if err != nil { - return err - } - - if schema.Query == nil { - schema.Query = &ast.Definition{ - Kind: ast.Object, - Name: "Query", - } - schema.Types["Query"] = schema.Query - } - - c.Schema = schema - return nil -} - -func abs(path string) string { - absPath, err := filepath.Abs(path) - if err != nil { - panic(err) - } - return filepath.ToSlash(absPath) -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/exec.go b/vendor/github.com/99designs/gqlgen/codegen/config/exec.go deleted file mode 100644 index fe1dccd21d..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/config/exec.go +++ /dev/null @@ -1,97 +0,0 @@ -package config - -import ( - "fmt" - "go/types" - "path/filepath" - "strings" - - "github.com/99designs/gqlgen/internal/code" -) - -type ExecConfig struct { - Package string `yaml:"package,omitempty"` - Layout ExecLayout `yaml:"layout,omitempty"` // Default: single-file - - // Only for single-file layout: - Filename string `yaml:"filename,omitempty"` - - // Only for follow-schema layout: - FilenameTemplate string `yaml:"filename_template,omitempty"` // String template with {name} as placeholder for base name. - DirName string `yaml:"dir"` -} - -type ExecLayout string - -var ( - // Write all generated code to a single file. - ExecLayoutSingleFile ExecLayout = "single-file" - // Write generated code to a directory, generating one Go source file for each GraphQL schema file. - ExecLayoutFollowSchema ExecLayout = "follow-schema" -) - -func (r *ExecConfig) Check() error { - if r.Layout == "" { - r.Layout = ExecLayoutSingleFile - } - - switch r.Layout { - case ExecLayoutSingleFile: - if r.Filename == "" { - return fmt.Errorf("filename must be specified when using single-file layout") - } - if !strings.HasSuffix(r.Filename, ".go") { - return fmt.Errorf("filename should be path to a go source file when using single-file layout") - } - r.Filename = abs(r.Filename) - case ExecLayoutFollowSchema: - if r.DirName == "" { - return fmt.Errorf("dir must be specified when using follow-schema layout") - } - r.DirName = abs(r.DirName) - default: - return fmt.Errorf("invalid layout %s", r.Layout) - } - - if strings.ContainsAny(r.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") - } - - if r.Package == "" && r.Dir() != "" { - r.Package = code.NameForDir(r.Dir()) - } - - return nil -} - -func (r *ExecConfig) ImportPath() string { - if r.Dir() == "" { - return "" - } - return code.ImportPathForDir(r.Dir()) -} - -func (r *ExecConfig) Dir() string { - switch r.Layout { - case ExecLayoutSingleFile: - if r.Filename == "" { - return "" - } - return filepath.Dir(r.Filename) - case ExecLayoutFollowSchema: - return abs(r.DirName) - default: - panic("invalid layout " + r.Layout) - } -} - -func (r *ExecConfig) Pkg() *types.Package { - if r.Dir() == "" { - return nil - } - return types.NewPackage(r.ImportPath(), r.Package) -} - -func (r *ExecConfig) IsDefined() bool { - return r.Filename != "" || r.DirName != "" -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/package.go b/vendor/github.com/99designs/gqlgen/codegen/config/package.go deleted file mode 100644 index faacd1496f..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/config/package.go +++ /dev/null @@ -1,63 +0,0 @@ -package config - -import ( - "fmt" - "go/types" - "path/filepath" - "strings" - - "github.com/99designs/gqlgen/internal/code" -) - -type PackageConfig struct { - Filename string `yaml:"filename,omitempty"` - Package string `yaml:"package,omitempty"` - Version int `yaml:"version,omitempty"` -} - -func (c *PackageConfig) ImportPath() string { - if !c.IsDefined() { - return "" - } - return code.ImportPathForDir(c.Dir()) -} - -func (c *PackageConfig) Dir() string { - if !c.IsDefined() { - return "" - } - return filepath.Dir(c.Filename) -} - -func (c *PackageConfig) Pkg() *types.Package { - if !c.IsDefined() { - return nil - } - return types.NewPackage(c.ImportPath(), c.Package) -} - -func (c *PackageConfig) IsDefined() bool { - return c.Filename != "" -} - -func (c *PackageConfig) Check() error { - if strings.ContainsAny(c.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") - } - if c.Filename == "" { - return fmt.Errorf("filename must be specified") - } - if !strings.HasSuffix(c.Filename, ".go") { - return fmt.Errorf("filename should be path to a go source file") - } - - c.Filename = abs(c.Filename) - - // If Package is not set, first attempt to load the package at the output dir. If that fails - // fallback to just the base dir name of the output filename. - if c.Package == "" { - c.Package = code.NameForDir(c.Dir()) - } - - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/resolver.go b/vendor/github.com/99designs/gqlgen/codegen/config/resolver.go deleted file mode 100644 index cd03f18872..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/config/resolver.go +++ /dev/null @@ -1,100 +0,0 @@ -package config - -import ( - "fmt" - "go/types" - "path/filepath" - "strings" - - "github.com/99designs/gqlgen/internal/code" -) - -type ResolverConfig struct { - Filename string `yaml:"filename,omitempty"` - FilenameTemplate string `yaml:"filename_template,omitempty"` - Package string `yaml:"package,omitempty"` - Type string `yaml:"type,omitempty"` - Layout ResolverLayout `yaml:"layout,omitempty"` - DirName string `yaml:"dir"` -} - -type ResolverLayout string - -var ( - LayoutSingleFile ResolverLayout = "single-file" - LayoutFollowSchema ResolverLayout = "follow-schema" -) - -func (r *ResolverConfig) Check() error { - if r.Layout == "" { - r.Layout = LayoutSingleFile - } - if r.Type == "" { - r.Type = "Resolver" - } - - switch r.Layout { - case LayoutSingleFile: - if r.Filename == "" { - return fmt.Errorf("filename must be specified with layout=%s", r.Layout) - } - if !strings.HasSuffix(r.Filename, ".go") { - return fmt.Errorf("filename should be path to a go source file with layout=%s", r.Layout) - } - r.Filename = abs(r.Filename) - case LayoutFollowSchema: - if r.DirName == "" { - return fmt.Errorf("dirname must be specified with layout=%s", r.Layout) - } - r.DirName = abs(r.DirName) - if r.Filename == "" { - r.Filename = filepath.Join(r.DirName, "resolver.go") - } else { - r.Filename = abs(r.Filename) - } - default: - return fmt.Errorf("invalid layout %s. must be %s or %s", r.Layout, LayoutSingleFile, LayoutFollowSchema) - } - - if strings.ContainsAny(r.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") - } - - if r.Package == "" && r.Dir() != "" { - r.Package = code.NameForDir(r.Dir()) - } - - return nil -} - -func (r *ResolverConfig) ImportPath() string { - if r.Dir() == "" { - return "" - } - return code.ImportPathForDir(r.Dir()) -} - -func (r *ResolverConfig) Dir() string { - switch r.Layout { - case LayoutSingleFile: - if r.Filename == "" { - return "" - } - return filepath.Dir(r.Filename) - case LayoutFollowSchema: - return r.DirName - default: - panic("invalid layout " + r.Layout) - } -} - -func (r *ResolverConfig) Pkg() *types.Package { - if r.Dir() == "" { - return nil - } - return types.NewPackage(r.ImportPath(), r.Package) -} - -func (r *ResolverConfig) IsDefined() bool { - return r.Filename != "" || r.DirName != "" -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/data.go b/vendor/github.com/99designs/gqlgen/codegen/data.go deleted file mode 100644 index 592140ae6c..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/data.go +++ /dev/null @@ -1,233 +0,0 @@ -package codegen - -import ( - "fmt" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/vektah/gqlparser/v2/ast" - - "github.com/99designs/gqlgen/codegen/config" -) - -// Data is a unified model of the code to be generated. Plugins may modify this structure to do things like implement -// resolvers or directives automatically (eg grpc, validation) -type Data struct { - Config *config.Config - Schema *ast.Schema - // If a schema is broken up into multiple Data instance, each representing part of the schema, - // AllDirectives should contain the directives for the entire schema. Directives() can - // then be used to get the directives that were defined in this Data instance's sources. - // If a single Data instance is used for the entire schema, AllDirectives and Directives() - // will be identical. - // AllDirectives should rarely be used directly. - AllDirectives DirectiveList - Objects Objects - Inputs Objects - Interfaces map[string]*Interface - ReferencedTypes map[string]*config.TypeReference - ComplexityRoots map[string]*Object - - QueryRoot *Object - MutationRoot *Object - SubscriptionRoot *Object - AugmentedSources []AugmentedSource -} - -func (d *Data) HasEmbeddableSources() bool { - hasEmbeddableSources := false - for _, s := range d.AugmentedSources { - if s.Embeddable { - hasEmbeddableSources = true - } - } - return hasEmbeddableSources -} - -// AugmentedSource contains extra information about graphql schema files which is not known directly from the Config.Sources data -type AugmentedSource struct { - // path relative to Config.Exec.Filename - RelativePath string - Embeddable bool - BuiltIn bool - Source string -} - -type builder struct { - Config *config.Config - Schema *ast.Schema - Binder *config.Binder - Directives map[string]*Directive -} - -// Get only the directives which are defined in the config's sources. -func (d *Data) Directives() DirectiveList { - res := DirectiveList{} - for k, directive := range d.AllDirectives { - for _, s := range d.Config.Sources { - if directive.Position.Src.Name == s.Name { - res[k] = directive - break - } - } - } - return res -} - -func BuildData(cfg *config.Config) (*Data, error) { - // We reload all packages to allow packages to be compared correctly. - cfg.ReloadAllPackages() - - b := builder{ - Config: cfg, - Schema: cfg.Schema, - } - - b.Binder = b.Config.NewBinder() - - var err error - b.Directives, err = b.buildDirectives() - if err != nil { - return nil, err - } - - dataDirectives := make(map[string]*Directive) - for name, d := range b.Directives { - if !d.Builtin { - dataDirectives[name] = d - } - } - - s := Data{ - Config: cfg, - AllDirectives: dataDirectives, - Schema: b.Schema, - Interfaces: map[string]*Interface{}, - } - - for _, schemaType := range b.Schema.Types { - switch schemaType.Kind { - case ast.Object: - obj, err := b.buildObject(schemaType) - if err != nil { - return nil, fmt.Errorf("unable to build object definition: %w", err) - } - - s.Objects = append(s.Objects, obj) - case ast.InputObject: - input, err := b.buildObject(schemaType) - if err != nil { - return nil, fmt.Errorf("unable to build input definition: %w", err) - } - - s.Inputs = append(s.Inputs, input) - - case ast.Union, ast.Interface: - s.Interfaces[schemaType.Name], err = b.buildInterface(schemaType) - if err != nil { - return nil, fmt.Errorf("unable to bind to interface: %w", err) - } - } - } - - if s.Schema.Query != nil { - s.QueryRoot = s.Objects.ByName(s.Schema.Query.Name) - } else { - return nil, fmt.Errorf("query entry point missing") - } - - if s.Schema.Mutation != nil { - s.MutationRoot = s.Objects.ByName(s.Schema.Mutation.Name) - } - - if s.Schema.Subscription != nil { - s.SubscriptionRoot = s.Objects.ByName(s.Schema.Subscription.Name) - } - - if err := b.injectIntrospectionRoots(&s); err != nil { - return nil, err - } - - s.ReferencedTypes = b.buildTypes() - - sort.Slice(s.Objects, func(i, j int) bool { - return s.Objects[i].Definition.Name < s.Objects[j].Definition.Name - }) - - sort.Slice(s.Inputs, func(i, j int) bool { - return s.Inputs[i].Definition.Name < s.Inputs[j].Definition.Name - }) - - if b.Binder.SawInvalid { - // if we have a syntax error, show it - err := cfg.Packages.Errors() - if len(err) > 0 { - return nil, err - } - - // otherwise show a generic error message - return nil, fmt.Errorf("invalid types were encountered while traversing the go source code, this probably means the invalid code generated isnt correct. add try adding -v to debug") - } - aSources := []AugmentedSource{} - for _, s := range cfg.Sources { - wd, err := os.Getwd() - if err != nil { - return nil, fmt.Errorf("failed to get working directory: %w", err) - } - outputDir := cfg.Exec.Dir() - sourcePath := filepath.Join(wd, s.Name) - relative, err := filepath.Rel(outputDir, sourcePath) - if err != nil { - return nil, fmt.Errorf("failed to compute path of %s relative to %s: %w", sourcePath, outputDir, err) - } - relative = filepath.ToSlash(relative) - embeddable := true - if strings.HasPrefix(relative, "..") || s.BuiltIn { - embeddable = false - } - aSources = append(aSources, AugmentedSource{ - RelativePath: relative, - Embeddable: embeddable, - BuiltIn: s.BuiltIn, - Source: s.Input, - }) - } - s.AugmentedSources = aSources - - return &s, nil -} - -func (b *builder) injectIntrospectionRoots(s *Data) error { - obj := s.Objects.ByName(b.Schema.Query.Name) - if obj == nil { - return fmt.Errorf("root query type must be defined") - } - - __type, err := b.buildField(obj, &ast.FieldDefinition{ - Name: "__type", - Type: ast.NamedType("__Type", nil), - Arguments: []*ast.ArgumentDefinition{ - { - Name: "name", - Type: ast.NonNullNamedType("String", nil), - }, - }, - }) - if err != nil { - return err - } - - __schema, err := b.buildField(obj, &ast.FieldDefinition{ - Name: "__schema", - Type: ast.NamedType("__Schema", nil), - }) - if err != nil { - return err - } - - obj.Fields = append(obj.Fields, __type, __schema) - - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/directive.go b/vendor/github.com/99designs/gqlgen/codegen/directive.go deleted file mode 100644 index 973061129a..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/directive.go +++ /dev/null @@ -1,174 +0,0 @@ -package codegen - -import ( - "fmt" - "strconv" - "strings" - - "github.com/99designs/gqlgen/codegen/templates" - "github.com/vektah/gqlparser/v2/ast" -) - -type DirectiveList map[string]*Directive - -// LocationDirectives filter directives by location -func (dl DirectiveList) LocationDirectives(location string) DirectiveList { - return locationDirectives(dl, ast.DirectiveLocation(location)) -} - -type Directive struct { - *ast.DirectiveDefinition - Name string - Args []*FieldArgument - Builtin bool -} - -// IsLocation check location directive -func (d *Directive) IsLocation(location ...ast.DirectiveLocation) bool { - for _, l := range d.Locations { - for _, a := range location { - if l == a { - return true - } - } - } - - return false -} - -func locationDirectives(directives DirectiveList, location ...ast.DirectiveLocation) map[string]*Directive { - mDirectives := make(map[string]*Directive) - for name, d := range directives { - if d.IsLocation(location...) { - mDirectives[name] = d - } - } - return mDirectives -} - -func (b *builder) buildDirectives() (map[string]*Directive, error) { - directives := make(map[string]*Directive, len(b.Schema.Directives)) - - for name, dir := range b.Schema.Directives { - if _, ok := directives[name]; ok { - return nil, fmt.Errorf("directive with name %s already exists", name) - } - - var args []*FieldArgument - for _, arg := range dir.Arguments { - tr, err := b.Binder.TypeReference(arg.Type, nil) - if err != nil { - return nil, err - } - - newArg := &FieldArgument{ - ArgumentDefinition: arg, - TypeReference: tr, - VarName: templates.ToGoPrivate(arg.Name), - } - - if arg.DefaultValue != nil { - var err error - newArg.Default, err = arg.DefaultValue.Value(nil) - if err != nil { - return nil, fmt.Errorf("default value for directive argument %s(%s) is not valid: %w", dir.Name, arg.Name, err) - } - } - args = append(args, newArg) - } - - directives[name] = &Directive{ - DirectiveDefinition: dir, - Name: name, - Args: args, - Builtin: b.Config.Directives[name].SkipRuntime, - } - } - - return directives, nil -} - -func (b *builder) getDirectives(list ast.DirectiveList) ([]*Directive, error) { - dirs := make([]*Directive, len(list)) - for i, d := range list { - argValues := make(map[string]interface{}, len(d.Arguments)) - for _, da := range d.Arguments { - val, err := da.Value.Value(nil) - if err != nil { - return nil, err - } - argValues[da.Name] = val - } - def, ok := b.Directives[d.Name] - if !ok { - return nil, fmt.Errorf("directive %s not found", d.Name) - } - - var args []*FieldArgument - for _, a := range def.Args { - value := a.Default - if argValue, ok := argValues[a.Name]; ok { - value = argValue - } - args = append(args, &FieldArgument{ - ArgumentDefinition: a.ArgumentDefinition, - Value: value, - VarName: a.VarName, - TypeReference: a.TypeReference, - }) - } - dirs[i] = &Directive{ - Name: d.Name, - Args: args, - DirectiveDefinition: list[i].Definition, - Builtin: b.Config.Directives[d.Name].SkipRuntime, - } - - } - - return dirs, nil -} - -func (d *Directive) ArgsFunc() string { - if len(d.Args) == 0 { - return "" - } - - return "dir_" + d.Name + "_args" -} - -func (d *Directive) CallArgs() string { - args := []string{"ctx", "obj", "n"} - - for _, arg := range d.Args { - args = append(args, "args["+strconv.Quote(arg.Name)+"].("+templates.CurrentImports.LookupType(arg.TypeReference.GO)+")") - } - - return strings.Join(args, ", ") -} - -func (d *Directive) ResolveArgs(obj string, next int) string { - args := []string{"ctx", obj, fmt.Sprintf("directive%d", next)} - - for _, arg := range d.Args { - dArg := arg.VarName - if arg.Value == nil && arg.Default == nil { - dArg = "nil" - } - - args = append(args, dArg) - } - - return strings.Join(args, ", ") -} - -func (d *Directive) Declaration() string { - res := ucFirst(d.Name) + " func(ctx context.Context, obj interface{}, next graphql.Resolver" - - for _, arg := range d.Args { - res += fmt.Sprintf(", %s %s", templates.ToGoPrivate(arg.Name), templates.CurrentImports.LookupType(arg.TypeReference.GO)) - } - - res += ") (res interface{}, err error)" - return res -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/directives.gotpl b/vendor/github.com/99designs/gqlgen/codegen/directives.gotpl deleted file mode 100644 index 23bcf0f879..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/directives.gotpl +++ /dev/null @@ -1,149 +0,0 @@ -{{ define "implDirectives" }}{{ $in := .DirectiveObjName }} - {{- range $i, $directive := .ImplDirectives -}} - directive{{add $i 1}} := func(ctx context.Context) (interface{}, error) { - {{- range $arg := $directive.Args }} - {{- if notNil "Value" $arg }} - {{ $arg.VarName }}, err := ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, {{ $arg.Value | dump }}) - if err != nil{ - return nil, err - } - {{- else if notNil "Default" $arg }} - {{ $arg.VarName }}, err := ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, {{ $arg.Default | dump }}) - if err != nil{ - return nil, err - } - {{- end }} - {{- end }} - if ec.directives.{{$directive.Name|ucFirst}} == nil { - return nil, errors.New("directive {{$directive.Name}} is not implemented") - } - return ec.directives.{{$directive.Name|ucFirst}}({{$directive.ResolveArgs $in $i }}) - } - {{ end -}} -{{ end }} - -{{define "queryDirectives"}} - for _, d := range obj.Directives { - switch d.Name { - {{- range $directive := . }} - case "{{$directive.Name}}": - {{- if $directive.Args }} - rawArgs := d.ArgumentMap(ec.Variables) - args, err := ec.{{ $directive.ArgsFunc }}(ctx,rawArgs) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - {{- end }} - n := next - next = func(ctx context.Context) (interface{}, error) { - if ec.directives.{{$directive.Name|ucFirst}} == nil { - return nil, errors.New("directive {{$directive.Name}} is not implemented") - } - return ec.directives.{{$directive.Name|ucFirst}}({{$directive.CallArgs}}) - } - {{- end }} - } - } - tmp, err := next(ctx) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if data, ok := tmp.(graphql.Marshaler); ok { - return data - } - ec.Errorf(ctx, `unexpected type %T from directive, should be graphql.Marshaler`, tmp) - return graphql.Null -{{end}} - -{{ if .Directives.LocationDirectives "QUERY" }} -func (ec *executionContext) _queryMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (interface{}, error)) graphql.Marshaler { - {{ template "queryDirectives" .Directives.LocationDirectives "QUERY" }} -} -{{ end }} - -{{ if .Directives.LocationDirectives "MUTATION" }} -func (ec *executionContext) _mutationMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (interface{}, error)) graphql.Marshaler { - {{ template "queryDirectives" .Directives.LocationDirectives "MUTATION" }} -} -{{ end }} - -{{ if .Directives.LocationDirectives "SUBSCRIPTION" }} -func (ec *executionContext) _subscriptionMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (interface{}, error)) func(ctx context.Context) graphql.Marshaler { - for _, d := range obj.Directives { - switch d.Name { - {{- range $directive := .Directives.LocationDirectives "SUBSCRIPTION" }} - case "{{$directive.Name}}": - {{- if $directive.Args }} - rawArgs := d.ArgumentMap(ec.Variables) - args, err := ec.{{ $directive.ArgsFunc }}(ctx,rawArgs) - if err != nil { - ec.Error(ctx, err) - return func(ctx context.Context) graphql.Marshaler { - return graphql.Null - } - } - {{- end }} - n := next - next = func(ctx context.Context) (interface{}, error) { - if ec.directives.{{$directive.Name|ucFirst}} == nil { - return nil, errors.New("directive {{$directive.Name}} is not implemented") - } - return ec.directives.{{$directive.Name|ucFirst}}({{$directive.CallArgs}}) - } - {{- end }} - } - } - tmp, err := next(ctx) - if err != nil { - ec.Error(ctx, err) - return func(ctx context.Context) graphql.Marshaler { - return graphql.Null - } - } - if data, ok := tmp.(func(ctx context.Context) graphql.Marshaler); ok { - return data - } - ec.Errorf(ctx, `unexpected type %T from directive, should be graphql.Marshaler`, tmp) - return func(ctx context.Context) graphql.Marshaler { - return graphql.Null - } -} -{{ end }} - -{{ if .Directives.LocationDirectives "FIELD" }} - func (ec *executionContext) _fieldMiddleware(ctx context.Context, obj interface{}, next graphql.Resolver) interface{} { - {{- if .Directives.LocationDirectives "FIELD" }} - fc := graphql.GetFieldContext(ctx) - for _, d := range fc.Field.Directives { - switch d.Name { - {{- range $directive := .Directives.LocationDirectives "FIELD" }} - case "{{$directive.Name}}": - {{- if $directive.Args }} - rawArgs := d.ArgumentMap(ec.Variables) - args, err := ec.{{ $directive.ArgsFunc }}(ctx,rawArgs) - if err != nil { - ec.Error(ctx, err) - return nil - } - {{- end }} - n := next - next = func(ctx context.Context) (interface{}, error) { - if ec.directives.{{$directive.Name|ucFirst}} == nil { - return nil, errors.New("directive {{$directive.Name}} is not implemented") - } - return ec.directives.{{$directive.Name|ucFirst}}({{$directive.CallArgs}}) - } - {{- end }} - } - } - {{- end }} - res, err := ec.ResolverMiddleware(ctx, next) - if err != nil { - ec.Error(ctx, err) - return nil - } - return res - } -{{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/field.go b/vendor/github.com/99designs/gqlgen/codegen/field.go deleted file mode 100644 index a33cc18e5a..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/field.go +++ /dev/null @@ -1,580 +0,0 @@ -package codegen - -import ( - "errors" - "fmt" - "go/types" - "log" - "reflect" - "strconv" - "strings" - - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/codegen/templates" - "github.com/vektah/gqlparser/v2/ast" - "golang.org/x/text/cases" - "golang.org/x/text/language" -) - -type Field struct { - *ast.FieldDefinition - - TypeReference *config.TypeReference - GoFieldType GoFieldType // The field type in go, if any - GoReceiverName string // The name of method & var receiver in go, if any - GoFieldName string // The name of the method or var in go, if any - IsResolver bool // Does this field need a resolver - Args []*FieldArgument // A list of arguments to be passed to this field - MethodHasContext bool // If this is bound to a go method, does the method also take a context - NoErr bool // If this is bound to a go method, does that method have an error as the second argument - VOkFunc bool // If this is bound to a go method, is it of shape (interface{}, bool) - Object *Object // A link back to the parent object - Default interface{} // The default value - Stream bool // does this field return a channel? - Directives []*Directive -} - -func (b *builder) buildField(obj *Object, field *ast.FieldDefinition) (*Field, error) { - dirs, err := b.getDirectives(field.Directives) - if err != nil { - return nil, err - } - - f := Field{ - FieldDefinition: field, - Object: obj, - Directives: dirs, - GoFieldName: templates.ToGo(field.Name), - GoFieldType: GoFieldVariable, - GoReceiverName: "obj", - } - - if field.DefaultValue != nil { - var err error - f.Default, err = field.DefaultValue.Value(nil) - if err != nil { - return nil, fmt.Errorf("default value %s is not valid: %w", field.Name, err) - } - } - - for _, arg := range field.Arguments { - newArg, err := b.buildArg(obj, arg) - if err != nil { - return nil, err - } - f.Args = append(f.Args, newArg) - } - - if err = b.bindField(obj, &f); err != nil { - f.IsResolver = true - if errors.Is(err, config.ErrTypeNotFound) { - return nil, err - } - log.Println(err.Error()) - } - - if f.IsResolver && b.Config.ResolversAlwaysReturnPointers && !f.TypeReference.IsPtr() && f.TypeReference.IsStruct() { - f.TypeReference = b.Binder.PointerTo(f.TypeReference) - } - - return &f, nil -} - -func (b *builder) bindField(obj *Object, f *Field) (errret error) { - defer func() { - if f.TypeReference == nil { - tr, err := b.Binder.TypeReference(f.Type, nil) - if err != nil { - errret = err - } - f.TypeReference = tr - } - if f.TypeReference != nil { - dirs, err := b.getDirectives(f.TypeReference.Definition.Directives) - if err != nil { - errret = err - } - for _, dir := range obj.Directives { - if dir.IsLocation(ast.LocationInputObject) { - dirs = append(dirs, dir) - } - } - f.Directives = append(dirs, f.Directives...) - } - }() - - f.Stream = obj.Stream - - switch { - case f.Name == "__schema": - f.GoFieldType = GoFieldMethod - f.GoReceiverName = "ec" - f.GoFieldName = "introspectSchema" - return nil - case f.Name == "__type": - f.GoFieldType = GoFieldMethod - f.GoReceiverName = "ec" - f.GoFieldName = "introspectType" - return nil - case f.Name == "_entities": - f.GoFieldType = GoFieldMethod - f.GoReceiverName = "ec" - f.GoFieldName = "__resolve_entities" - f.MethodHasContext = true - f.NoErr = true - return nil - case f.Name == "_service": - f.GoFieldType = GoFieldMethod - f.GoReceiverName = "ec" - f.GoFieldName = "__resolve__service" - f.MethodHasContext = true - return nil - case obj.Root: - f.IsResolver = true - return nil - case b.Config.Models[obj.Name].Fields[f.Name].Resolver: - f.IsResolver = true - return nil - case obj.Type == config.MapType: - f.GoFieldType = GoFieldMap - return nil - case b.Config.Models[obj.Name].Fields[f.Name].FieldName != "": - f.GoFieldName = b.Config.Models[obj.Name].Fields[f.Name].FieldName - } - - target, err := b.findBindTarget(obj.Type.(*types.Named), f.GoFieldName) - if err != nil { - return err - } - - pos := b.Binder.ObjectPosition(target) - - switch target := target.(type) { - case nil: - objPos := b.Binder.TypePosition(obj.Type) - return fmt.Errorf( - "%s:%d adding resolver method for %s.%s, nothing matched", - objPos.Filename, - objPos.Line, - obj.Name, - f.Name, - ) - - case *types.Func: - sig := target.Type().(*types.Signature) - if sig.Results().Len() == 1 { - f.NoErr = true - } else if s := sig.Results(); s.Len() == 2 && s.At(1).Type().String() == "bool" { - f.VOkFunc = true - } else if sig.Results().Len() != 2 { - return fmt.Errorf("method has wrong number of args") - } - params := sig.Params() - // If the first argument is the context, remove it from the comparison and set - // the MethodHasContext flag so that the context will be passed to this model's method - if params.Len() > 0 && params.At(0).Type().String() == "context.Context" { - f.MethodHasContext = true - vars := make([]*types.Var, params.Len()-1) - for i := 1; i < params.Len(); i++ { - vars[i-1] = params.At(i) - } - params = types.NewTuple(vars...) - } - - // Try to match target function's arguments with GraphQL field arguments. - newArgs, err := b.bindArgs(f, sig, params) - if err != nil { - return fmt.Errorf("%s:%d: %w", pos.Filename, pos.Line, err) - } - - // Try to match target function's return types with GraphQL field return type - result := sig.Results().At(0) - tr, err := b.Binder.TypeReference(f.Type, result.Type()) - if err != nil { - return err - } - - // success, args and return type match. Bind to method - f.GoFieldType = GoFieldMethod - f.GoReceiverName = "obj" - f.GoFieldName = target.Name() - f.Args = newArgs - f.TypeReference = tr - - return nil - - case *types.Var: - tr, err := b.Binder.TypeReference(f.Type, target.Type()) - if err != nil { - return err - } - - // success, bind to var - f.GoFieldType = GoFieldVariable - f.GoReceiverName = "obj" - f.GoFieldName = target.Name() - f.TypeReference = tr - - return nil - default: - panic(fmt.Errorf("unknown bind target %T for %s", target, f.Name)) - } -} - -// findBindTarget attempts to match the name to a field or method on a Type -// with the following priorites: -// 1. Any Fields with a struct tag (see config.StructTag). Errors if more than one match is found -// 2. Any method or field with a matching name. Errors if more than one match is found -// 3. Same logic again for embedded fields -func (b *builder) findBindTarget(t types.Type, name string) (types.Object, error) { - // NOTE: a struct tag will override both methods and fields - // Bind to struct tag - found, err := b.findBindStructTagTarget(t, name) - if found != nil || err != nil { - return found, err - } - - // Search for a method to bind to - foundMethod, err := b.findBindMethodTarget(t, name) - if err != nil { - return nil, err - } - - // Search for a field to bind to - foundField, err := b.findBindFieldTarget(t, name) - if err != nil { - return nil, err - } - - switch { - case foundField == nil && foundMethod != nil: - // Bind to method - return foundMethod, nil - case foundField != nil && foundMethod == nil: - // Bind to field - return foundField, nil - case foundField != nil && foundMethod != nil: - // Error - return nil, fmt.Errorf("found more than one way to bind for %s", name) - } - - // Search embeds - return b.findBindEmbedsTarget(t, name) -} - -func (b *builder) findBindStructTagTarget(in types.Type, name string) (types.Object, error) { - if b.Config.StructTag == "" { - return nil, nil - } - - switch t := in.(type) { - case *types.Named: - return b.findBindStructTagTarget(t.Underlying(), name) - case *types.Struct: - var found types.Object - for i := 0; i < t.NumFields(); i++ { - field := t.Field(i) - if !field.Exported() || field.Embedded() { - continue - } - tags := reflect.StructTag(t.Tag(i)) - if val, ok := tags.Lookup(b.Config.StructTag); ok && equalFieldName(val, name) { - if found != nil { - return nil, fmt.Errorf("tag %s is ambigious; multiple fields have the same tag value of %s", b.Config.StructTag, val) - } - - found = field - } - } - - return found, nil - } - - return nil, nil -} - -func (b *builder) findBindMethodTarget(in types.Type, name string) (types.Object, error) { - switch t := in.(type) { - case *types.Named: - if _, ok := t.Underlying().(*types.Interface); ok { - return b.findBindMethodTarget(t.Underlying(), name) - } - - return b.findBindMethoderTarget(t.Method, t.NumMethods(), name) - case *types.Interface: - // FIX-ME: Should use ExplicitMethod here? What's the difference? - return b.findBindMethoderTarget(t.Method, t.NumMethods(), name) - } - - return nil, nil -} - -func (b *builder) findBindMethoderTarget(methodFunc func(i int) *types.Func, methodCount int, name string) (types.Object, error) { - var found types.Object - for i := 0; i < methodCount; i++ { - method := methodFunc(i) - if !method.Exported() || !strings.EqualFold(method.Name(), name) { - continue - } - - if found != nil { - return nil, fmt.Errorf("found more than one matching method to bind for %s", name) - } - - found = method - } - - return found, nil -} - -func (b *builder) findBindFieldTarget(in types.Type, name string) (types.Object, error) { - switch t := in.(type) { - case *types.Named: - return b.findBindFieldTarget(t.Underlying(), name) - case *types.Struct: - var found types.Object - for i := 0; i < t.NumFields(); i++ { - field := t.Field(i) - if !field.Exported() || !equalFieldName(field.Name(), name) { - continue - } - - if found != nil { - return nil, fmt.Errorf("found more than one matching field to bind for %s", name) - } - - found = field - } - - return found, nil - } - - return nil, nil -} - -func (b *builder) findBindEmbedsTarget(in types.Type, name string) (types.Object, error) { - switch t := in.(type) { - case *types.Named: - return b.findBindEmbedsTarget(t.Underlying(), name) - case *types.Struct: - return b.findBindStructEmbedsTarget(t, name) - case *types.Interface: - return b.findBindInterfaceEmbedsTarget(t, name) - } - - return nil, nil -} - -func (b *builder) findBindStructEmbedsTarget(strukt *types.Struct, name string) (types.Object, error) { - var found types.Object - for i := 0; i < strukt.NumFields(); i++ { - field := strukt.Field(i) - if !field.Embedded() { - continue - } - - fieldType := field.Type() - if ptr, ok := fieldType.(*types.Pointer); ok { - fieldType = ptr.Elem() - } - - f, err := b.findBindTarget(fieldType, name) - if err != nil { - return nil, err - } - - if f != nil && found != nil { - return nil, fmt.Errorf("found more than one way to bind for %s", name) - } - - if f != nil { - found = f - } - } - - return found, nil -} - -func (b *builder) findBindInterfaceEmbedsTarget(iface *types.Interface, name string) (types.Object, error) { - var found types.Object - for i := 0; i < iface.NumEmbeddeds(); i++ { - embeddedType := iface.EmbeddedType(i) - - f, err := b.findBindTarget(embeddedType, name) - if err != nil { - return nil, err - } - - if f != nil && found != nil { - return nil, fmt.Errorf("found more than one way to bind for %s", name) - } - - if f != nil { - found = f - } - } - - return found, nil -} - -func (f *Field) HasDirectives() bool { - return len(f.ImplDirectives()) > 0 -} - -func (f *Field) DirectiveObjName() string { - if f.Object.Root { - return "nil" - } - return f.GoReceiverName -} - -func (f *Field) ImplDirectives() []*Directive { - var d []*Directive - loc := ast.LocationFieldDefinition - if f.Object.IsInputType() { - loc = ast.LocationInputFieldDefinition - } - for i := range f.Directives { - if !f.Directives[i].Builtin && - (f.Directives[i].IsLocation(loc, ast.LocationObject) || f.Directives[i].IsLocation(loc, ast.LocationInputObject)) { - d = append(d, f.Directives[i]) - } - } - return d -} - -func (f *Field) IsReserved() bool { - return strings.HasPrefix(f.Name, "__") -} - -func (f *Field) IsMethod() bool { - return f.GoFieldType == GoFieldMethod -} - -func (f *Field) IsVariable() bool { - return f.GoFieldType == GoFieldVariable -} - -func (f *Field) IsMap() bool { - return f.GoFieldType == GoFieldMap -} - -func (f *Field) IsConcurrent() bool { - if f.Object.DisableConcurrency { - return false - } - return f.MethodHasContext || f.IsResolver -} - -func (f *Field) GoNameUnexported() string { - return templates.ToGoPrivate(f.Name) -} - -func (f *Field) ShortInvocation() string { - caser := cases.Title(language.English, cases.NoLower) - if f.Object.Kind == ast.InputObject { - return fmt.Sprintf("%s().%s(ctx, &it, data)", caser.String(f.Object.Definition.Name), f.GoFieldName) - } - return fmt.Sprintf("%s().%s(%s)", caser.String(f.Object.Definition.Name), f.GoFieldName, f.CallArgs()) -} - -func (f *Field) ArgsFunc() string { - if len(f.Args) == 0 { - return "" - } - - return "field_" + f.Object.Definition.Name + "_" + f.Name + "_args" -} - -func (f *Field) FieldContextFunc() string { - return "fieldContext_" + f.Object.Definition.Name + "_" + f.Name -} - -func (f *Field) ChildFieldContextFunc(name string) string { - return "fieldContext_" + f.TypeReference.Definition.Name + "_" + name -} - -func (f *Field) ResolverType() string { - if !f.IsResolver { - return "" - } - - return fmt.Sprintf("%s().%s(%s)", f.Object.Definition.Name, f.GoFieldName, f.CallArgs()) -} - -func (f *Field) ShortResolverDeclaration() string { - if f.Object.Kind == ast.InputObject { - return fmt.Sprintf("(ctx context.Context, obj %s, data %s) error", - templates.CurrentImports.LookupType(f.Object.Reference()), - templates.CurrentImports.LookupType(f.TypeReference.GO), - ) - } - - res := "(ctx context.Context" - - if !f.Object.Root { - res += fmt.Sprintf(", obj %s", templates.CurrentImports.LookupType(f.Object.Reference())) - } - for _, arg := range f.Args { - res += fmt.Sprintf(", %s %s", arg.VarName, templates.CurrentImports.LookupType(arg.TypeReference.GO)) - } - - result := templates.CurrentImports.LookupType(f.TypeReference.GO) - if f.Object.Stream { - result = "<-chan " + result - } - - res += fmt.Sprintf(") (%s, error)", result) - return res -} - -func (f *Field) ComplexitySignature() string { - res := "func(childComplexity int" - for _, arg := range f.Args { - res += fmt.Sprintf(", %s %s", arg.VarName, templates.CurrentImports.LookupType(arg.TypeReference.GO)) - } - res += ") int" - return res -} - -func (f *Field) ComplexityArgs() string { - args := make([]string, len(f.Args)) - for i, arg := range f.Args { - args[i] = "args[" + strconv.Quote(arg.Name) + "].(" + templates.CurrentImports.LookupType(arg.TypeReference.GO) + ")" - } - - return strings.Join(args, ", ") -} - -func (f *Field) CallArgs() string { - args := make([]string, 0, len(f.Args)+2) - - if f.IsResolver { - args = append(args, "rctx") - - if !f.Object.Root { - args = append(args, "obj") - } - } else if f.MethodHasContext { - args = append(args, "ctx") - } - - for _, arg := range f.Args { - tmp := "fc.Args[" + strconv.Quote(arg.Name) + "].(" + templates.CurrentImports.LookupType(arg.TypeReference.GO) + ")" - - if iface, ok := arg.TypeReference.GO.(*types.Interface); ok && iface.Empty() { - tmp = fmt.Sprintf(` - func () interface{} { - if fc.Args["%s"] == nil { - return nil - } - return fc.Args["%s"].(interface{}) - }()`, arg.Name, arg.Name, - ) - } - - args = append(args, tmp) - } - - return strings.Join(args, ", ") -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/field.gotpl b/vendor/github.com/99designs/gqlgen/codegen/field.gotpl deleted file mode 100644 index e47b958dda..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/field.gotpl +++ /dev/null @@ -1,158 +0,0 @@ -{{- range $object := .Objects }}{{- range $field := $object.Fields }} - -func (ec *executionContext) _{{$object.Name}}_{{$field.Name}}(ctx context.Context, field graphql.CollectedField{{ if not $object.Root }}, obj {{$object.Reference | ref}}{{end}}) (ret {{ if $object.Stream }}func(ctx context.Context){{ end }}graphql.Marshaler) { - {{- $null := "graphql.Null" }} - {{- if $object.Stream }} - {{- $null = "nil" }} - {{- end }} - fc, err := ec.{{ $field.FieldContextFunc }}(ctx, field) - if err != nil { - return {{ $null }} - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func () { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = {{ $null }} - } - }() - {{- if $.AllDirectives.LocationDirectives "FIELD" }} - resTmp := ec._fieldMiddleware(ctx, {{if $object.Root}}nil{{else}}obj{{end}}, func(rctx context.Context) (interface{}, error) { - {{ template "field" $field }} - }) - {{ else }} - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - {{ template "field" $field }} - }) - if err != nil { - ec.Error(ctx, err) - return {{ $null }} - } - {{- end }} - if resTmp == nil { - {{- if $field.TypeReference.GQL.NonNull }} - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - {{- end }} - return {{ $null }} - } - {{- if $object.Stream }} - return func(ctx context.Context) graphql.Marshaler { - select { - case res, ok := <-resTmp.(<-chan {{$field.TypeReference.GO | ref}}): - if !ok { - return nil - } - return graphql.WriterFunc(func(w io.Writer) { - w.Write([]byte{'{'}) - graphql.MarshalString(field.Alias).MarshalGQL(w) - w.Write([]byte{':'}) - ec.{{ $field.TypeReference.MarshalFunc }}(ctx, field.Selections, res).MarshalGQL(w) - w.Write([]byte{'}'}) - }) - case <-ctx.Done(): - return nil - } - } - {{- else }} - res := resTmp.({{$field.TypeReference.GO | ref}}) - fc.Result = res - return ec.{{ $field.TypeReference.MarshalFunc }}(ctx, field.Selections, res) - {{- end }} -} - -func (ec *executionContext) {{ $field.FieldContextFunc }}(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: {{quote $field.Object.Name}}, - Field: field, - IsMethod: {{or $field.IsMethod $field.IsResolver}}, - IsResolver: {{ $field.IsResolver }}, - Child: func (ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - {{- if not $field.TypeReference.Definition.Fields }} - return nil, errors.New("field of type {{ $field.TypeReference.Definition.Name }} does not have child fields") - {{- else if ne $field.TypeReference.Definition.Kind "OBJECT" }} - return nil, errors.New("FieldContext.Child cannot be called on type {{ $field.TypeReference.Definition.Kind }}") - {{- else }} - switch field.Name { - {{- range $f := $field.TypeReference.Definition.Fields }} - case "{{ $f.Name }}": - return ec.{{ $field.ChildFieldContextFunc $f.Name }}(ctx, field) - {{- end }} - } - return nil, fmt.Errorf("no field named %q was found under type {{ $field.TypeReference.Definition.Name }}", field.Name) - {{- end }} - }, - } - {{- if $field.Args }} - defer func () { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.{{ $field.ArgsFunc }}(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - {{- end }} - return fc, nil -} - -{{- end }}{{- end}} - -{{ define "field" }} - {{- if .HasDirectives -}} - directive0 := func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - {{ template "fieldDefinition" . }} - } - {{ template "implDirectives" . }} - tmp, err := directive{{.ImplDirectives|len}}(rctx) - if err != nil { - return nil, graphql.ErrorOnPath(ctx, err) - } - if tmp == nil { - return nil, nil - } - if data, ok := tmp.({{if .Stream}}<-chan {{end}}{{ .TypeReference.GO | ref }}) ; ok { - return data, nil - } - return nil, fmt.Errorf(`unexpected type %T from directive, should be {{if .Stream}}<-chan {{end}}{{ .TypeReference.GO }}`, tmp) - {{- else -}} - ctx = rctx // use context from middleware stack in children - {{ template "fieldDefinition" . }} - {{- end -}} -{{ end }} - -{{ define "fieldDefinition" }} - {{- if .IsResolver -}} - return ec.resolvers.{{ .ShortInvocation }} - {{- else if .IsMap -}} - switch v := {{.GoReceiverName}}[{{.Name|quote}}].(type) { - case {{if .Stream}}<-chan {{end}}{{.TypeReference.GO | ref}}: - return v, nil - case {{if .Stream}}<-chan {{end}}{{.TypeReference.Elem.GO | ref}}: - return &v, nil - case nil: - return ({{.TypeReference.GO | ref}})(nil), nil - default: - return nil, fmt.Errorf("unexpected type %T for field %s", v, {{ .Name | quote}}) - } - {{- else if .IsMethod -}} - {{- if .VOkFunc -}} - v, ok := {{.GoReceiverName}}.{{.GoFieldName}}({{ .CallArgs }}) - if !ok { - return nil, nil - } - return v, nil - {{- else if .NoErr -}} - return {{.GoReceiverName}}.{{.GoFieldName}}({{ .CallArgs }}), nil - {{- else -}} - return {{.GoReceiverName}}.{{.GoFieldName}}({{ .CallArgs }}) - {{- end -}} - {{- else if .IsVariable -}} - return {{.GoReceiverName}}.{{.GoFieldName}}, nil - {{- end }} -{{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/generate.go b/vendor/github.com/99designs/gqlgen/codegen/generate.go deleted file mode 100644 index 1ce8c329dc..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/generate.go +++ /dev/null @@ -1,220 +0,0 @@ -package codegen - -import ( - "embed" - "errors" - "fmt" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/codegen/templates" - "github.com/vektah/gqlparser/v2/ast" -) - -//go:embed *.gotpl -var codegenTemplates embed.FS - -func GenerateCode(data *Data) error { - if !data.Config.Exec.IsDefined() { - return fmt.Errorf("missing exec config") - } - - switch data.Config.Exec.Layout { - case config.ExecLayoutSingleFile: - return generateSingleFile(data) - case config.ExecLayoutFollowSchema: - return generatePerSchema(data) - } - - return fmt.Errorf("unrecognized exec layout %s", data.Config.Exec.Layout) -} - -func generateSingleFile(data *Data) error { - return templates.Render(templates.Options{ - PackageName: data.Config.Exec.Package, - Filename: data.Config.Exec.Filename, - Data: data, - RegionTags: true, - GeneratedHeader: true, - Packages: data.Config.Packages, - TemplateFS: codegenTemplates, - }) -} - -func generatePerSchema(data *Data) error { - err := generateRootFile(data) - if err != nil { - return err - } - - builds := map[string]*Data{} - - err = addObjects(data, &builds) - if err != nil { - return err - } - - err = addInputs(data, &builds) - if err != nil { - return err - } - - err = addInterfaces(data, &builds) - if err != nil { - return err - } - - err = addReferencedTypes(data, &builds) - if err != nil { - return err - } - - for filename, build := range builds { - if filename == "" { - continue - } - - dir := data.Config.Exec.DirName - path := filepath.Join(dir, filename) - - err = templates.Render(templates.Options{ - PackageName: data.Config.Exec.Package, - Filename: path, - Data: build, - RegionTags: true, - GeneratedHeader: true, - Packages: data.Config.Packages, - TemplateFS: codegenTemplates, - }) - if err != nil { - return err - } - } - - return nil -} - -func filename(p *ast.Position, config *config.Config) string { - name := "common!" - if p != nil && p.Src != nil { - gqlname := filepath.Base(p.Src.Name) - ext := filepath.Ext(p.Src.Name) - name = strings.TrimSuffix(gqlname, ext) - } - - filenameTempl := config.Exec.FilenameTemplate - if filenameTempl == "" { - filenameTempl = "{name}.generated.go" - } - - return strings.ReplaceAll(filenameTempl, "{name}", name) -} - -func addBuild(filename string, p *ast.Position, data *Data, builds *map[string]*Data) { - buildConfig := *data.Config - if p != nil { - buildConfig.Sources = []*ast.Source{p.Src} - } - - (*builds)[filename] = &Data{ - Config: &buildConfig, - QueryRoot: data.QueryRoot, - MutationRoot: data.MutationRoot, - SubscriptionRoot: data.SubscriptionRoot, - AllDirectives: data.AllDirectives, - } -} - -// Root file contains top-level definitions that should not be duplicated across the generated -// files for each schema file. -func generateRootFile(data *Data) error { - dir := data.Config.Exec.DirName - path := filepath.Join(dir, "root_.generated.go") - - _, thisFile, _, _ := runtime.Caller(0) - rootDir := filepath.Dir(thisFile) - templatePath := filepath.Join(rootDir, "root_.gotpl") - templateBytes, err := os.ReadFile(templatePath) - if err != nil { - return err - } - template := string(templateBytes) - - return templates.Render(templates.Options{ - PackageName: data.Config.Exec.Package, - Template: template, - Filename: path, - Data: data, - RegionTags: false, - GeneratedHeader: true, - Packages: data.Config.Packages, - TemplateFS: codegenTemplates, - }) -} - -func addObjects(data *Data, builds *map[string]*Data) error { - for _, o := range data.Objects { - filename := filename(o.Position, data.Config) - if (*builds)[filename] == nil { - addBuild(filename, o.Position, data, builds) - } - - (*builds)[filename].Objects = append((*builds)[filename].Objects, o) - } - return nil -} - -func addInputs(data *Data, builds *map[string]*Data) error { - for _, in := range data.Inputs { - filename := filename(in.Position, data.Config) - if (*builds)[filename] == nil { - addBuild(filename, in.Position, data, builds) - } - - (*builds)[filename].Inputs = append((*builds)[filename].Inputs, in) - } - return nil -} - -func addInterfaces(data *Data, builds *map[string]*Data) error { - for k, inf := range data.Interfaces { - filename := filename(inf.Position, data.Config) - if (*builds)[filename] == nil { - addBuild(filename, inf.Position, data, builds) - } - build := (*builds)[filename] - - if build.Interfaces == nil { - build.Interfaces = map[string]*Interface{} - } - if build.Interfaces[k] != nil { - return errors.New("conflicting interface keys") - } - - build.Interfaces[k] = inf - } - return nil -} - -func addReferencedTypes(data *Data, builds *map[string]*Data) error { - for k, rt := range data.ReferencedTypes { - filename := filename(rt.Definition.Position, data.Config) - if (*builds)[filename] == nil { - addBuild(filename, rt.Definition.Position, data, builds) - } - build := (*builds)[filename] - - if build.ReferencedTypes == nil { - build.ReferencedTypes = map[string]*config.TypeReference{} - } - if build.ReferencedTypes[k] != nil { - return errors.New("conflicting referenced type keys") - } - - build.ReferencedTypes[k] = rt - } - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/generated!.gotpl b/vendor/github.com/99designs/gqlgen/codegen/generated!.gotpl deleted file mode 100644 index 0998c77502..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/generated!.gotpl +++ /dev/null @@ -1,258 +0,0 @@ -{{ reserveImport "context" }} -{{ reserveImport "fmt" }} -{{ reserveImport "io" }} -{{ reserveImport "strconv" }} -{{ reserveImport "time" }} -{{ reserveImport "sync" }} -{{ reserveImport "sync/atomic" }} -{{ reserveImport "errors" }} -{{ reserveImport "bytes" }} -{{ reserveImport "embed" }} - -{{ reserveImport "github.com/vektah/gqlparser/v2" "gqlparser" }} -{{ reserveImport "github.com/vektah/gqlparser/v2/ast" }} -{{ reserveImport "github.com/99designs/gqlgen/graphql" }} -{{ reserveImport "github.com/99designs/gqlgen/graphql/introspection" }} - - -{{ if eq .Config.Exec.Layout "single-file" }} - // NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. - func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { - return &executableSchema{ - resolvers: cfg.Resolvers, - directives: cfg.Directives, - complexity: cfg.Complexity, - } - } - - type Config struct { - Resolvers ResolverRoot - Directives DirectiveRoot - Complexity ComplexityRoot - } - - type ResolverRoot interface { - {{- range $object := .Objects -}} - {{ if $object.HasResolvers -}} - {{ucFirst $object.Name}}() {{ucFirst $object.Name}}Resolver - {{ end }} - {{- end }} - {{- range $object := .Inputs -}} - {{ if $object.HasResolvers -}} - {{ucFirst $object.Name}}() {{ucFirst $object.Name}}Resolver - {{ end }} -{{- end }} -} - - type DirectiveRoot struct { - {{ range $directive := .Directives }} - {{- $directive.Declaration }} - {{ end }} - } - - type ComplexityRoot struct { - {{ range $object := .Objects }} - {{ if not $object.IsReserved -}} - {{ ucFirst $object.Name }} struct { - {{ range $_, $fields := $object.UniqueFields }} - {{- $field := index $fields 0 -}} - {{ if not $field.IsReserved -}} - {{ $field.GoFieldName }} {{ $field.ComplexitySignature }} - {{ end }} - {{- end }} - } - {{- end }} - {{ end }} - } -{{ end }} - -{{ range $object := .Objects -}} - {{ if $object.HasResolvers }} - type {{ucFirst $object.Name}}Resolver interface { - {{ range $field := $object.Fields -}} - {{- if $field.IsResolver }} - {{- $field.GoFieldName}}{{ $field.ShortResolverDeclaration }} - {{- end }} - {{ end }} - } - {{- end }} -{{- end }} - -{{ range $object := .Inputs -}} - {{ if $object.HasResolvers }} - type {{$object.Name}}Resolver interface { - {{ range $field := $object.Fields -}} - {{- if $field.IsResolver }} - {{- $field.GoFieldName}}{{ $field.ShortResolverDeclaration }} - {{- end }} - {{ end }} - } - {{- end }} -{{- end }} - -{{ if eq .Config.Exec.Layout "single-file" }} - type executableSchema struct { - resolvers ResolverRoot - directives DirectiveRoot - complexity ComplexityRoot - } - - func (e *executableSchema) Schema() *ast.Schema { - return parsedSchema - } - - func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { - ec := executionContext{nil, e} - _ = ec - switch typeName + "." + field { - {{ range $object := .Objects }} - {{ if not $object.IsReserved }} - {{ range $_, $fields := $object.UniqueFields }} - {{- $len := len $fields }} - {{- range $i, $field := $fields }} - {{- $last := eq (add $i 1) $len }} - {{- if not $field.IsReserved }} - {{- if eq $i 0 }}case {{ end }}"{{$object.Name}}.{{$field.Name}}"{{ if not $last }},{{ else }}: - if e.complexity.{{ucFirst $object.Name}}.{{$field.GoFieldName}} == nil { - break - } - {{ if $field.Args }} - args, err := ec.{{ $field.ArgsFunc }}(context.TODO(),rawArgs) - if err != nil { - return 0, false - } - {{ end }} - return e.complexity.{{ucFirst $object.Name}}.{{$field.GoFieldName}}(childComplexity{{if $field.Args}}, {{$field.ComplexityArgs}} {{ end }}), true - {{ end }} - {{- end }} - {{- end }} - {{ end }} - {{ end }} - {{ end }} - } - return 0, false - } - - func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { - rc := graphql.GetOperationContext(ctx) - ec := executionContext{rc, e} - inputUnmarshalMap := graphql.BuildUnmarshalerMap( - {{- range $input := .Inputs -}} - {{ if not $input.HasUnmarshal }} - ec.unmarshalInput{{ $input.Name }}, - {{- end }} - {{- end }} - ) - first := true - - switch rc.Operation.Operation { - {{- if .QueryRoot }} case ast.Query: - return func(ctx context.Context) *graphql.Response { - if !first { return nil } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - {{ if .Directives.LocationDirectives "QUERY" -}} - data := ec._queryMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.QueryRoot.Name}}(ctx, rc.Operation.SelectionSet), nil - }) - {{- else -}} - data := ec._{{.QueryRoot.Name}}(ctx, rc.Operation.SelectionSet) - {{- end }} - var buf bytes.Buffer - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - {{ end }} - - {{- if .MutationRoot }} case ast.Mutation: - return func(ctx context.Context) *graphql.Response { - if !first { return nil } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - {{ if .Directives.LocationDirectives "MUTATION" -}} - data := ec._mutationMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.MutationRoot.Name}}(ctx, rc.Operation.SelectionSet), nil - }) - {{- else -}} - data := ec._{{.MutationRoot.Name}}(ctx, rc.Operation.SelectionSet) - {{- end }} - var buf bytes.Buffer - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - {{ end }} - - {{- if .SubscriptionRoot }} case ast.Subscription: - {{ if .Directives.LocationDirectives "SUBSCRIPTION" -}} - next := ec._subscriptionMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.SubscriptionRoot.Name}}(ctx, rc.Operation.SelectionSet),nil - }) - {{- else -}} - next := ec._{{.SubscriptionRoot.Name}}(ctx, rc.Operation.SelectionSet) - {{- end }} - - var buf bytes.Buffer - return func(ctx context.Context) *graphql.Response { - buf.Reset() - data := next(ctx) - - if data == nil { - return nil - } - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - {{ end }} - default: - return graphql.OneShot(graphql.ErrorResponse(ctx, "unsupported GraphQL operation")) - } - } - - type executionContext struct { - *graphql.OperationContext - *executableSchema - } - - func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { - if ec.DisableIntrospection { - return nil, errors.New("introspection disabled") - } - return introspection.WrapSchema(parsedSchema), nil - } - - func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { - if ec.DisableIntrospection { - return nil, errors.New("introspection disabled") - } - return introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name]), nil - } - - {{if .HasEmbeddableSources }} - //go:embed{{- range $source := .AugmentedSources }}{{if $source.Embeddable}} {{$source.RelativePath|quote}}{{end}}{{- end }} - var sourcesFS embed.FS - - func sourceData(filename string) string { - data, err := sourcesFS.ReadFile(filename) - if err != nil { - panic(fmt.Sprintf("codegen problem: %s not available", filename)) - } - return string(data) - } - {{- end }} - - var sources = []*ast.Source{ - {{- range $source := .AugmentedSources }} - {Name: {{$source.RelativePath|quote}}, Input: {{if (not $source.Embeddable)}}{{$source.Source|rawQuote}}{{else}}sourceData({{$source.RelativePath|quote}}){{end}}, BuiltIn: {{$source.BuiltIn}}}, - {{- end }} - } - var parsedSchema = gqlparser.MustLoadSchema(sources...) -{{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/input.gotpl b/vendor/github.com/99designs/gqlgen/codegen/input.gotpl deleted file mode 100644 index 116fe9ce76..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/input.gotpl +++ /dev/null @@ -1,77 +0,0 @@ -{{- range $input := .Inputs }} - {{- if not .HasUnmarshal }} - func (ec *executionContext) unmarshalInput{{ .Name }}(ctx context.Context, obj interface{}) ({{.Type | ref}}, error) { - var it {{.Type | ref}} - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { - asMap[k] = v - } - {{ range $field := .Fields}} - {{- if notNil "Default" $field }} - if _, present := asMap[{{$field.Name|quote}}] ; !present { - asMap[{{$field.Name|quote}}] = {{ $field.Default | dump }} - } - {{- end}} - {{- end }} - - fieldsInOrder := [...]string{ {{ range .Fields }}{{ quote .Name }},{{ end }} } - for _, k := range fieldsInOrder { - v, ok := asMap[k] - if !ok { - continue - } - switch k { - {{- range $field := .Fields }} - case {{$field.Name|quote}}: - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField({{$field.Name|quote}})) - {{- if $field.ImplDirectives }} - directive0 := func(ctx context.Context) (interface{}, error) { return ec.{{ $field.TypeReference.UnmarshalFunc }}(ctx, v) } - {{ template "implDirectives" $field }} - tmp, err := directive{{$field.ImplDirectives|len}}(ctx) - if err != nil { - return it, graphql.ErrorOnPath(ctx, err) - } - if data, ok := tmp.({{ $field.TypeReference.GO | ref }}) ; ok { - {{- if $field.IsResolver }} - if err = ec.resolvers.{{ $field.ShortInvocation }}; err != nil { - return it, err - } - {{- else }} - it.{{$field.GoFieldName}} = data - {{- end }} - {{- if $field.TypeReference.IsNilable }} - {{- if not $field.IsResolver }} - } else if tmp == nil { - it.{{$field.GoFieldName}} = nil - {{- end }} - {{- end }} - } else { - err := fmt.Errorf(`unexpected type %T from directive, should be {{ $field.TypeReference.GO }}`, tmp) - return it, graphql.ErrorOnPath(ctx, err) - } - {{- else }} - {{- if $field.IsResolver }} - data, err := ec.{{ $field.TypeReference.UnmarshalFunc }}(ctx, v) - if err != nil { - return it, err - } - if err = ec.resolvers.{{ $field.ShortInvocation }}; err != nil { - return it, err - } - {{- else }} - it.{{$field.GoFieldName}}, err = ec.{{ $field.TypeReference.UnmarshalFunc }}(ctx, v) - if err != nil { - return it, err - } - {{- end }} - {{- end }} - {{- end }} - } - } - - return it, nil - } - {{- end }} -{{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/interface.go b/vendor/github.com/99designs/gqlgen/codegen/interface.go deleted file mode 100644 index cdc4d4d32e..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/interface.go +++ /dev/null @@ -1,87 +0,0 @@ -package codegen - -import ( - "fmt" - "go/types" - - "github.com/vektah/gqlparser/v2/ast" - - "github.com/99designs/gqlgen/codegen/config" -) - -type Interface struct { - *ast.Definition - Type types.Type - Implementors []InterfaceImplementor - InTypemap bool -} - -type InterfaceImplementor struct { - *ast.Definition - - Type types.Type - TakeRef bool -} - -func (b *builder) buildInterface(typ *ast.Definition) (*Interface, error) { - obj, err := b.Binder.DefaultUserObject(typ.Name) - if err != nil { - panic(err) - } - - i := &Interface{ - Definition: typ, - Type: obj, - InTypemap: b.Config.Models.UserDefined(typ.Name), - } - - interfaceType, err := findGoInterface(i.Type) - if interfaceType == nil || err != nil { - return nil, fmt.Errorf("%s is not an interface", i.Type) - } - - for _, implementor := range b.Schema.GetPossibleTypes(typ) { - obj, err := b.Binder.DefaultUserObject(implementor.Name) - if err != nil { - return nil, fmt.Errorf("%s has no backing go type", implementor.Name) - } - - implementorType, err := findGoNamedType(obj) - if err != nil { - return nil, fmt.Errorf("can not find backing go type %s: %w", obj.String(), err) - } else if implementorType == nil { - return nil, fmt.Errorf("can not find backing go type %s", obj.String()) - } - - anyValid := false - - // first check if the value receiver can be nil, eg can we type switch on case Thing: - if types.Implements(implementorType, interfaceType) { - i.Implementors = append(i.Implementors, InterfaceImplementor{ - Definition: implementor, - Type: obj, - TakeRef: !types.IsInterface(obj), - }) - anyValid = true - } - - // then check if the pointer receiver can be nil, eg can we type switch on case *Thing: - if types.Implements(types.NewPointer(implementorType), interfaceType) { - i.Implementors = append(i.Implementors, InterfaceImplementor{ - Definition: implementor, - Type: types.NewPointer(obj), - }) - anyValid = true - } - - if !anyValid { - return nil, fmt.Errorf("%s does not satisfy the interface %s", implementorType.String(), i.Type.String()) - } - } - - return i, nil -} - -func (i *InterfaceImplementor) CanBeNil() bool { - return config.IsNilable(i.Type) -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/interface.gotpl b/vendor/github.com/99designs/gqlgen/codegen/interface.gotpl deleted file mode 100644 index e9d560c8f6..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/interface.gotpl +++ /dev/null @@ -1,21 +0,0 @@ -{{- range $interface := .Interfaces }} - -func (ec *executionContext) _{{$interface.Name}}(ctx context.Context, sel ast.SelectionSet, obj {{$interface.Type | ref}}) graphql.Marshaler { - switch obj := (obj).(type) { - case nil: - return graphql.Null - {{- range $implementor := $interface.Implementors }} - case {{$implementor.Type | ref}}: - {{- if $implementor.CanBeNil }} - if obj == nil { - return graphql.Null - } - {{- end }} - return ec._{{$implementor.Name}}(ctx, sel, {{ if $implementor.TakeRef }}&{{ end }}obj) - {{- end }} - default: - panic(fmt.Errorf("unexpected type %T", obj)) - } -} - -{{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/object.go b/vendor/github.com/99designs/gqlgen/codegen/object.go deleted file mode 100644 index a9cb34061b..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/object.go +++ /dev/null @@ -1,171 +0,0 @@ -package codegen - -import ( - "fmt" - "go/types" - "strconv" - "strings" - "unicode" - - "github.com/99designs/gqlgen/codegen/config" - "github.com/vektah/gqlparser/v2/ast" - "golang.org/x/text/cases" - "golang.org/x/text/language" -) - -type GoFieldType int - -const ( - GoFieldUndefined GoFieldType = iota - GoFieldMethod - GoFieldVariable - GoFieldMap -) - -type Object struct { - *ast.Definition - - Type types.Type - ResolverInterface types.Type - Root bool - Fields []*Field - Implements []*ast.Definition - DisableConcurrency bool - Stream bool - Directives []*Directive -} - -func (b *builder) buildObject(typ *ast.Definition) (*Object, error) { - dirs, err := b.getDirectives(typ.Directives) - if err != nil { - return nil, fmt.Errorf("%s: %w", typ.Name, err) - } - caser := cases.Title(language.English, cases.NoLower) - obj := &Object{ - Definition: typ, - Root: b.Schema.Query == typ || b.Schema.Mutation == typ || b.Schema.Subscription == typ, - DisableConcurrency: typ == b.Schema.Mutation, - Stream: typ == b.Schema.Subscription, - Directives: dirs, - ResolverInterface: types.NewNamed( - types.NewTypeName(0, b.Config.Exec.Pkg(), caser.String(typ.Name)+"Resolver", nil), - nil, - nil, - ), - } - - if !obj.Root { - goObject, err := b.Binder.DefaultUserObject(typ.Name) - if err != nil { - return nil, err - } - obj.Type = goObject - } - - for _, intf := range b.Schema.GetImplements(typ) { - obj.Implements = append(obj.Implements, b.Schema.Types[intf.Name]) - } - - for _, field := range typ.Fields { - if strings.HasPrefix(field.Name, "__") { - continue - } - - var f *Field - f, err = b.buildField(obj, field) - if err != nil { - return nil, err - } - - obj.Fields = append(obj.Fields, f) - } - - return obj, nil -} - -func (o *Object) Reference() types.Type { - if config.IsNilable(o.Type) { - return o.Type - } - return types.NewPointer(o.Type) -} - -type Objects []*Object - -func (o *Object) Implementors() string { - satisfiedBy := strconv.Quote(o.Name) - for _, s := range o.Implements { - satisfiedBy += ", " + strconv.Quote(s.Name) - } - return "[]string{" + satisfiedBy + "}" -} - -func (o *Object) HasResolvers() bool { - for _, f := range o.Fields { - if f.IsResolver { - return true - } - } - return false -} - -func (o *Object) HasUnmarshal() bool { - if o.Type == config.MapType { - return true - } - for i := 0; i < o.Type.(*types.Named).NumMethods(); i++ { - if o.Type.(*types.Named).Method(i).Name() == "UnmarshalGQL" { - return true - } - } - return false -} - -func (o *Object) HasDirectives() bool { - if len(o.Directives) > 0 { - return true - } - for _, f := range o.Fields { - if f.HasDirectives() { - return true - } - } - - return false -} - -func (o *Object) IsConcurrent() bool { - for _, f := range o.Fields { - if f.IsConcurrent() { - return true - } - } - return false -} - -func (o *Object) IsReserved() bool { - return strings.HasPrefix(o.Definition.Name, "__") -} - -func (o *Object) Description() string { - return o.Definition.Description -} - -func (os Objects) ByName(name string) *Object { - for i, o := range os { - if strings.EqualFold(o.Definition.Name, name) { - return os[i] - } - } - return nil -} - -func ucFirst(s string) string { - if s == "" { - return "" - } - - r := []rune(s) - r[0] = unicode.ToUpper(r[0]) - return string(r) -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/object.gotpl b/vendor/github.com/99designs/gqlgen/codegen/object.gotpl deleted file mode 100644 index 1fbdfacec1..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/object.gotpl +++ /dev/null @@ -1,112 +0,0 @@ -{{- range $object := .Objects }} - -var {{ $object.Name|lcFirst}}Implementors = {{$object.Implementors}} - -{{- if .Stream }} -func (ec *executionContext) _{{$object.Name}}(ctx context.Context, sel ast.SelectionSet) func(ctx context.Context) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, {{$object.Name|lcFirst}}Implementors) - ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ - Object: {{$object.Name|quote}}, - }) - if len(fields) != 1 { - ec.Errorf(ctx, "must subscribe to exactly one stream") - return nil - } - - switch fields[0].Name { - {{- range $field := $object.Fields }} - case "{{$field.Name}}": - return ec._{{$object.Name}}_{{$field.Name}}(ctx, fields[0]) - {{- end }} - default: - panic("unknown field " + strconv.Quote(fields[0].Name)) - } -} -{{- else }} -func (ec *executionContext) _{{$object.Name}}(ctx context.Context, sel ast.SelectionSet{{ if not $object.Root }},obj {{$object.Reference | ref }}{{ end }}) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, {{$object.Name|lcFirst}}Implementors) - {{- if $object.Root }} - ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ - Object: {{$object.Name|quote}}, - }) - {{end}} - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - {{- if $object.Root }} - innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ - Object: field.Name, - Field: field, - }) - {{end}} - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString({{$object.Name|quote}}) - {{- range $field := $object.Fields }} - case "{{$field.Name}}": - {{- if $field.IsConcurrent }} - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._{{$object.Name}}_{{$field.Name}}(ctx, field{{if not $object.Root}}, obj{{end}}) - {{- if $field.TypeReference.GQL.NonNull }} - if res == graphql.Null { - {{- if $object.IsConcurrent }} - atomic.AddUint32(&invalids, 1) - {{- else }} - invalids++ - {{- end }} - } - {{- end }} - return res - } - - {{if $object.Root}} - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - {{end}} - - out.Concurrently(i, func() graphql.Marshaler { - {{- if $object.Root -}} - return rrm(innerCtx) - {{- else -}} - return innerFunc(ctx) - {{end}} - }) - {{- else }} - {{if $object.Root}} - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._{{$object.Name}}_{{$field.Name}}(ctx, field) - }) - {{else}} - out.Values[i] = ec._{{$object.Name}}_{{$field.Name}}(ctx, field, obj) - {{end}} - - {{- if $field.TypeReference.GQL.NonNull }} - if out.Values[i] == graphql.Null { - {{- if $object.IsConcurrent }} - atomic.AddUint32(&invalids, 1) - {{- else }} - invalids++ - {{- end }} - } - {{- end }} - {{- end }} - {{- end }} - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { return graphql.Null } - return out -} -{{- end }} - -{{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/root_.gotpl b/vendor/github.com/99designs/gqlgen/codegen/root_.gotpl deleted file mode 100644 index 2f2a98262e..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/root_.gotpl +++ /dev/null @@ -1,230 +0,0 @@ -{{ reserveImport "context" }} -{{ reserveImport "fmt" }} -{{ reserveImport "io" }} -{{ reserveImport "strconv" }} -{{ reserveImport "time" }} -{{ reserveImport "sync" }} -{{ reserveImport "sync/atomic" }} -{{ reserveImport "errors" }} -{{ reserveImport "bytes" }} -{{ reserveImport "embed" }} - -{{ reserveImport "github.com/vektah/gqlparser/v2" "gqlparser" }} -{{ reserveImport "github.com/vektah/gqlparser/v2/ast" }} -{{ reserveImport "github.com/99designs/gqlgen/graphql" }} -{{ reserveImport "github.com/99designs/gqlgen/graphql/introspection" }} - -// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. -func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { - return &executableSchema{ - resolvers: cfg.Resolvers, - directives: cfg.Directives, - complexity: cfg.Complexity, - } -} - -type Config struct { - Resolvers ResolverRoot - Directives DirectiveRoot - Complexity ComplexityRoot -} - -type ResolverRoot interface { -{{- range $object := .Objects -}} - {{ if $object.HasResolvers -}} - {{ucFirst $object.Name}}() {{ucFirst $object.Name}}Resolver - {{ end }} -{{- end }} -{{- range $object := .Inputs -}} - {{ if $object.HasResolvers -}} - {{ucFirst $object.Name}}() {{ucFirst $object.Name}}Resolver - {{ end }} -{{- end }} -} - -type DirectiveRoot struct { -{{ range $directive := .Directives }} - {{- $directive.Declaration }} -{{ end }} -} - -type ComplexityRoot struct { -{{ range $object := .Objects }} - {{ if not $object.IsReserved -}} - {{ ucFirst $object.Name }} struct { - {{ range $_, $fields := $object.UniqueFields }} - {{- $field := index $fields 0 -}} - {{ if not $field.IsReserved -}} - {{ $field.GoFieldName }} {{ $field.ComplexitySignature }} - {{ end }} - {{- end }} - } - {{- end }} -{{ end }} -} - -type executableSchema struct { - resolvers ResolverRoot - directives DirectiveRoot - complexity ComplexityRoot -} - -func (e *executableSchema) Schema() *ast.Schema { - return parsedSchema -} - -func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { - ec := executionContext{nil, e} - _ = ec - switch typeName + "." + field { - {{ range $object := .Objects }} - {{ if not $object.IsReserved }} - {{ range $_, $fields := $object.UniqueFields }} - {{- $len := len $fields }} - {{- range $i, $field := $fields }} - {{- $last := eq (add $i 1) $len }} - {{- if not $field.IsReserved }} - {{- if eq $i 0 }}case {{ end }}"{{$object.Name}}.{{$field.Name}}"{{ if not $last }},{{ else }}: - if e.complexity.{{ucFirst $object.Name }}.{{$field.GoFieldName}} == nil { - break - } - {{ if $field.Args }} - args, err := ec.{{ $field.ArgsFunc }}(context.TODO(),rawArgs) - if err != nil { - return 0, false - } - {{ end }} - return e.complexity.{{ucFirst $object.Name}}.{{$field.GoFieldName}}(childComplexity{{if $field.Args}}, {{$field.ComplexityArgs}} {{ end }}), true - {{ end }} - {{- end }} - {{- end }} - {{ end }} - {{ end }} - {{ end }} - } - return 0, false -} - -func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { - rc := graphql.GetOperationContext(ctx) - ec := executionContext{rc, e} - inputUnmarshalMap := graphql.BuildUnmarshalerMap( - {{- range $input := .Inputs -}} - {{ if not $input.HasUnmarshal }} - ec.unmarshalInput{{ $input.Name }}, - {{- end }} - {{- end }} - ) - first := true - - switch rc.Operation.Operation { - {{- if .QueryRoot }} case ast.Query: - return func(ctx context.Context) *graphql.Response { - if !first { return nil } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - {{ if .Directives.LocationDirectives "QUERY" -}} - data := ec._queryMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.QueryRoot.Name}}(ctx, rc.Operation.SelectionSet), nil - }) - {{- else -}} - data := ec._{{.QueryRoot.Name}}(ctx, rc.Operation.SelectionSet) - {{- end }} - var buf bytes.Buffer - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - {{ end }} - - {{- if .MutationRoot }} case ast.Mutation: - return func(ctx context.Context) *graphql.Response { - if !first { return nil } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - {{ if .Directives.LocationDirectives "MUTATION" -}} - data := ec._mutationMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.MutationRoot.Name}}(ctx, rc.Operation.SelectionSet), nil - }) - {{- else -}} - data := ec._{{.MutationRoot.Name}}(ctx, rc.Operation.SelectionSet) - {{- end }} - var buf bytes.Buffer - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - {{ end }} - - {{- if .SubscriptionRoot }} case ast.Subscription: - {{ if .Directives.LocationDirectives "SUBSCRIPTION" -}} - next := ec._subscriptionMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.SubscriptionRoot.Name}}(ctx, rc.Operation.SelectionSet),nil - }) - {{- else -}} - next := ec._{{.SubscriptionRoot.Name}}(ctx, rc.Operation.SelectionSet) - {{- end }} - - var buf bytes.Buffer - return func(ctx context.Context) *graphql.Response { - buf.Reset() - data := next(ctx) - - if data == nil { - return nil - } - data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), - } - } - {{ end }} - default: - return graphql.OneShot(graphql.ErrorResponse(ctx, "unsupported GraphQL operation")) - } -} - -type executionContext struct { - *graphql.OperationContext - *executableSchema -} - -func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { - if ec.DisableIntrospection { - return nil, errors.New("introspection disabled") - } - return introspection.WrapSchema(parsedSchema), nil -} - -func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { - if ec.DisableIntrospection { - return nil, errors.New("introspection disabled") - } - return introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name]), nil -} - - -{{if .HasEmbeddableSources }} -//go:embed{{- range $source := .AugmentedSources }}{{if $source.Embeddable}} {{$source.RelativePath|quote}}{{end}}{{- end }} -var sourcesFS embed.FS - -func sourceData(filename string) string { - data, err := sourcesFS.ReadFile(filename) - if err != nil { - panic(fmt.Sprintf("codegen problem: %s not available", filename)) - } - return string(data) -} -{{- end}} - -var sources = []*ast.Source{ -{{- range $source := .AugmentedSources }} - {Name: {{$source.RelativePath|quote}}, Input: {{if (not $source.Embeddable)}}{{$source.Source|rawQuote}}{{else}}sourceData({{$source.RelativePath|quote}}){{end}}, BuiltIn: {{$source.BuiltIn}}}, -{{- end }} -} -var parsedSchema = gqlparser.MustLoadSchema(sources...) diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/import.go b/vendor/github.com/99designs/gqlgen/codegen/templates/import.go deleted file mode 100644 index 00a82ea5ef..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/templates/import.go +++ /dev/null @@ -1,139 +0,0 @@ -package templates - -import ( - "fmt" - "go/types" - "strconv" - "strings" - - "github.com/99designs/gqlgen/internal/code" -) - -type Import struct { - Name string - Path string - Alias string -} - -type Imports struct { - imports []*Import - destDir string - packages *code.Packages -} - -func (i *Import) String() string { - if strings.HasSuffix(i.Path, i.Alias) { - return strconv.Quote(i.Path) - } - - return i.Alias + " " + strconv.Quote(i.Path) -} - -func (s *Imports) String() string { - res := "" - for i, imp := range s.imports { - if i != 0 { - res += "\n" - } - res += imp.String() - } - return res -} - -func (s *Imports) Reserve(path string, aliases ...string) (string, error) { - if path == "" { - panic("empty ambient import") - } - - // if we are referencing our own package we dont need an import - if code.ImportPathForDir(s.destDir) == path { - return "", nil - } - - name := s.packages.NameForPackage(path) - var alias string - if len(aliases) != 1 { - alias = name - } else { - alias = aliases[0] - } - - if existing := s.findByPath(path); existing != nil { - if existing.Alias == alias { - return "", nil - } - return "", fmt.Errorf("ambient import already exists") - } - - if alias := s.findByAlias(alias); alias != nil { - return "", fmt.Errorf("ambient import collides on an alias") - } - - s.imports = append(s.imports, &Import{ - Name: name, - Path: path, - Alias: alias, - }) - - return "", nil -} - -func (s *Imports) Lookup(path string) string { - if path == "" { - return "" - } - - path = code.NormalizeVendor(path) - - // if we are referencing our own package we dont need an import - if code.ImportPathForDir(s.destDir) == path { - return "" - } - - if existing := s.findByPath(path); existing != nil { - return existing.Alias - } - - imp := &Import{ - Name: s.packages.NameForPackage(path), - Path: path, - } - s.imports = append(s.imports, imp) - - alias := imp.Name - i := 1 - for s.findByAlias(alias) != nil { - alias = imp.Name + strconv.Itoa(i) - i++ - if i > 1000 { - panic(fmt.Errorf("too many collisions, last attempt was %s", alias)) - } - } - imp.Alias = alias - - return imp.Alias -} - -func (s *Imports) LookupType(t types.Type) string { - return types.TypeString(t, func(i *types.Package) string { - return s.Lookup(i.Path()) - }) -} - -func (s Imports) findByPath(importPath string) *Import { - for _, imp := range s.imports { - if imp.Path == importPath { - return imp - } - } - return nil -} - -func (s Imports) findByAlias(alias string) *Import { - for _, imp := range s.imports { - if imp.Alias == alias { - return imp - } - } - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go b/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go deleted file mode 100644 index 159df77c9c..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go +++ /dev/null @@ -1,740 +0,0 @@ -package templates - -import ( - "bytes" - "fmt" - "go/types" - "io/fs" - "os" - "path/filepath" - "reflect" - "regexp" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "text/template" - "unicode" - - "github.com/99designs/gqlgen/internal/code" - - "github.com/99designs/gqlgen/internal/imports" -) - -// CurrentImports keeps track of all the import declarations that are needed during the execution of a plugin. -// this is done with a global because subtemplates currently get called in functions. Lets aim to remove this eventually. -var CurrentImports *Imports - -// Options specify various parameters to rendering a template. -type Options struct { - // PackageName is a helper that specifies the package header declaration. - // In other words, when you write the template you don't need to specify `package X` - // at the top of the file. By providing PackageName in the Options, the Render - // function will do that for you. - PackageName string - // Template is a string of the entire template that - // will be parsed and rendered. If it's empty, - // the plugin processor will look for .gotpl files - // in the same directory of where you wrote the plugin. - Template string - - // Use the go:embed API to collect all the template files you want to pass into Render - // this is an alternative to passing the Template option - TemplateFS fs.FS - - // Filename is the name of the file that will be - // written to the system disk once the template is rendered. - Filename string - RegionTags bool - GeneratedHeader bool - // PackageDoc is documentation written above the package line - PackageDoc string - // FileNotice is notice written below the package line - FileNotice string - // Data will be passed to the template execution. - Data interface{} - Funcs template.FuncMap - - // Packages cache, you can find me on config.Config - Packages *code.Packages -} - -var ( - modelNamesMu sync.Mutex - modelNames = make(map[string]string, 0) - goNameRe = regexp.MustCompile("[^a-zA-Z0-9_]") -) - -// Render renders a gql plugin template from the given Options. Render is an -// abstraction of the text/template package that makes it easier to write gqlgen -// plugins. If Options.Template is empty, the Render function will look for `.gotpl` -// files inside the directory where you wrote the plugin. -func Render(cfg Options) error { - if CurrentImports != nil { - panic(fmt.Errorf("recursive or concurrent call to RenderToFile detected")) - } - CurrentImports = &Imports{packages: cfg.Packages, destDir: filepath.Dir(cfg.Filename)} - - funcs := Funcs() - for n, f := range cfg.Funcs { - funcs[n] = f - } - - t := template.New("").Funcs(funcs) - t, err := parseTemplates(cfg, t) - if err != nil { - return err - } - - roots := make([]string, 0, len(t.Templates())) - for _, template := range t.Templates() { - // templates that end with _.gotpl are special files we don't want to include - if strings.HasSuffix(template.Name(), "_.gotpl") || - // filter out templates added with {{ template xxx }} syntax inside the template file - !strings.HasSuffix(template.Name(), ".gotpl") { - continue - } - - roots = append(roots, template.Name()) - } - - // then execute all the important looking ones in order, adding them to the same file - sort.Slice(roots, func(i, j int) bool { - // important files go first - if strings.HasSuffix(roots[i], "!.gotpl") { - return true - } - if strings.HasSuffix(roots[j], "!.gotpl") { - return false - } - return roots[i] < roots[j] - }) - - var buf bytes.Buffer - for _, root := range roots { - if cfg.RegionTags { - buf.WriteString("\n// region " + center(70, "*", " "+root+" ") + "\n") - } - err := t.Lookup(root).Execute(&buf, cfg.Data) - if err != nil { - return fmt.Errorf("%s: %w", root, err) - } - if cfg.RegionTags { - buf.WriteString("\n// endregion " + center(70, "*", " "+root+" ") + "\n") - } - } - - var result bytes.Buffer - if cfg.GeneratedHeader { - result.WriteString("// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.\n\n") - } - if cfg.PackageDoc != "" { - result.WriteString(cfg.PackageDoc + "\n") - } - result.WriteString("package ") - result.WriteString(cfg.PackageName) - result.WriteString("\n\n") - if cfg.FileNotice != "" { - result.WriteString(cfg.FileNotice) - result.WriteString("\n\n") - } - result.WriteString("import (\n") - result.WriteString(CurrentImports.String()) - result.WriteString(")\n") - _, err = buf.WriteTo(&result) - if err != nil { - return err - } - CurrentImports = nil - - err = write(cfg.Filename, result.Bytes(), cfg.Packages) - if err != nil { - return err - } - - cfg.Packages.Evict(code.ImportPathForDir(filepath.Dir(cfg.Filename))) - return nil -} - -func parseTemplates(cfg Options, t *template.Template) (*template.Template, error) { - if cfg.Template != "" { - var err error - t, err = t.New("template.gotpl").Parse(cfg.Template) - if err != nil { - return nil, fmt.Errorf("error with provided template: %w", err) - } - return t, nil - } - - var fileSystem fs.FS - if cfg.TemplateFS != nil { - fileSystem = cfg.TemplateFS - } else { - // load path relative to calling source file - _, callerFile, _, _ := runtime.Caller(1) - rootDir := filepath.Dir(callerFile) - fileSystem = os.DirFS(rootDir) - } - - t, err := t.ParseFS(fileSystem, "*.gotpl") - if err != nil { - return nil, fmt.Errorf("locating templates: %w", err) - } - - return t, nil -} - -func center(width int, pad string, s string) string { - if len(s)+2 > width { - return s - } - lpad := (width - len(s)) / 2 - rpad := width - (lpad + len(s)) - return strings.Repeat(pad, lpad) + s + strings.Repeat(pad, rpad) -} - -func Funcs() template.FuncMap { - return template.FuncMap{ - "ucFirst": UcFirst, - "lcFirst": LcFirst, - "quote": strconv.Quote, - "rawQuote": rawQuote, - "dump": Dump, - "ref": ref, - "ts": TypeIdentifier, - "call": Call, - "prefixLines": prefixLines, - "notNil": notNil, - "reserveImport": CurrentImports.Reserve, - "lookupImport": CurrentImports.Lookup, - "go": ToGo, - "goPrivate": ToGoPrivate, - "goModelName": ToGoModelName, - "goPrivateModelName": ToGoPrivateModelName, - "add": func(a, b int) int { - return a + b - }, - "render": func(filename string, tpldata interface{}) (*bytes.Buffer, error) { - return render(resolveName(filename, 0), tpldata) - }, - } -} - -func UcFirst(s string) string { - if s == "" { - return "" - } - r := []rune(s) - r[0] = unicode.ToUpper(r[0]) - return string(r) -} - -func LcFirst(s string) string { - if s == "" { - return "" - } - - r := []rune(s) - r[0] = unicode.ToLower(r[0]) - return string(r) -} - -func isDelimiter(c rune) bool { - return c == '-' || c == '_' || unicode.IsSpace(c) -} - -func ref(p types.Type) string { - return CurrentImports.LookupType(p) -} - -var pkgReplacer = strings.NewReplacer( - "/", "ᚋ", - ".", "ᚗ", - "-", "ᚑ", - "~", "א", -) - -func TypeIdentifier(t types.Type) string { - res := "" - for { - switch it := t.(type) { - case *types.Pointer: - t.Underlying() - res += "ᚖ" - t = it.Elem() - case *types.Slice: - res += "ᚕ" - t = it.Elem() - case *types.Named: - res += pkgReplacer.Replace(it.Obj().Pkg().Path()) - res += "ᚐ" - res += it.Obj().Name() - return res - case *types.Basic: - res += it.Name() - return res - case *types.Map: - res += "map" - return res - case *types.Interface: - res += "interface" - return res - default: - panic(fmt.Errorf("unexpected type %T", it)) - } - } -} - -func Call(p *types.Func) string { - pkg := CurrentImports.Lookup(p.Pkg().Path()) - - if pkg != "" { - pkg += "." - } - - if p.Type() != nil { - // make sure the returned type is listed in our imports. - ref(p.Type().(*types.Signature).Results().At(0).Type()) - } - - return pkg + p.Name() -} - -func resetModelNames() { - modelNamesMu.Lock() - defer modelNamesMu.Unlock() - modelNames = make(map[string]string, 0) -} - -func buildGoModelNameKey(parts []string) string { - const sep = ":" - return strings.Join(parts, sep) -} - -func goModelName(primaryToGoFunc func(string) string, parts []string) string { - modelNamesMu.Lock() - defer modelNamesMu.Unlock() - - var ( - goNameKey string - partLen int - - nameExists = func(n string) bool { - for _, v := range modelNames { - if n == v { - return true - } - } - return false - } - - applyToGoFunc = func(parts []string) string { - var out string - switch len(parts) { - case 0: - return "" - case 1: - return primaryToGoFunc(parts[0]) - default: - out = primaryToGoFunc(parts[0]) - } - for _, p := range parts[1:] { - out = fmt.Sprintf("%s%s", out, ToGo(p)) - } - return out - } - - applyValidGoName = func(parts []string) string { - var out string - for _, p := range parts { - out = fmt.Sprintf("%s%s", out, replaceInvalidCharacters(p)) - } - return out - } - ) - - // build key for this entity - goNameKey = buildGoModelNameKey(parts) - - // determine if we've seen this entity before, and reuse if so - if goName, ok := modelNames[goNameKey]; ok { - return goName - } - - // attempt first pass - if goName := applyToGoFunc(parts); !nameExists(goName) { - modelNames[goNameKey] = goName - return goName - } - - // determine number of parts - partLen = len(parts) - - // if there is only 1 part, append incrementing number until no conflict - if partLen == 1 { - base := applyToGoFunc(parts) - for i := 0; ; i++ { - tmp := fmt.Sprintf("%s%d", base, i) - if !nameExists(tmp) { - modelNames[goNameKey] = tmp - return tmp - } - } - } - - // best effort "pretty" name - for i := partLen - 1; i >= 1; i-- { - tmp := fmt.Sprintf("%s%s", applyToGoFunc(parts[0:i]), applyValidGoName(parts[i:])) - if !nameExists(tmp) { - modelNames[goNameKey] = tmp - return tmp - } - } - - // finally, fallback to just adding an incrementing number - base := applyToGoFunc(parts) - for i := 0; ; i++ { - tmp := fmt.Sprintf("%s%d", base, i) - if !nameExists(tmp) { - modelNames[goNameKey] = tmp - return tmp - } - } -} - -func ToGoModelName(parts ...string) string { - return goModelName(ToGo, parts) -} - -func ToGoPrivateModelName(parts ...string) string { - return goModelName(ToGoPrivate, parts) -} - -func replaceInvalidCharacters(in string) string { - return goNameRe.ReplaceAllLiteralString(in, "_") -} - -func wordWalkerFunc(private bool, nameRunes *[]rune) func(*wordInfo) { - return func(info *wordInfo) { - word := info.Word - - switch { - case private && info.WordOffset == 0: - if strings.ToUpper(word) == word || strings.ToLower(word) == word { - // ID → id, CAMEL → camel - word = strings.ToLower(info.Word) - } else { - // ITicket → iTicket - word = LcFirst(info.Word) - } - - case info.MatchCommonInitial: - word = strings.ToUpper(word) - - case !info.HasCommonInitial && (strings.ToUpper(word) == word || strings.ToLower(word) == word): - // FOO or foo → Foo - // FOo → FOo - word = UcFirst(strings.ToLower(word)) - } - - *nameRunes = append(*nameRunes, []rune(word)...) - } -} - -func ToGo(name string) string { - if name == "_" { - return "_" - } - runes := make([]rune, 0, len(name)) - - wordWalker(name, wordWalkerFunc(false, &runes)) - - return string(runes) -} - -func ToGoPrivate(name string) string { - if name == "_" { - return "_" - } - runes := make([]rune, 0, len(name)) - - wordWalker(name, wordWalkerFunc(true, &runes)) - - return sanitizeKeywords(string(runes)) -} - -type wordInfo struct { - WordOffset int - Word string - MatchCommonInitial bool - HasCommonInitial bool -} - -// This function is based on the following code. -// https://github.com/golang/lint/blob/06c8688daad7faa9da5a0c2f163a3d14aac986ca/lint.go#L679 -func wordWalker(str string, f func(*wordInfo)) { - runes := []rune(strings.TrimFunc(str, isDelimiter)) - w, i, wo := 0, 0, 0 // index of start of word, scan, word offset - hasCommonInitial := false - for i+1 <= len(runes) { - eow := false // whether we hit the end of a word - switch { - case i+1 == len(runes): - eow = true - case isDelimiter(runes[i+1]): - // underscore; shift the remainder forward over any run of underscores - eow = true - n := 1 - for i+n+1 < len(runes) && isDelimiter(runes[i+n+1]) { - n++ - } - - // Leave at most one underscore if the underscore is between two digits - if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) { - n-- - } - - copy(runes[i+1:], runes[i+n+1:]) - runes = runes[:len(runes)-n] - case unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]): - // lower->non-lower - eow = true - } - i++ - - // [w,i) is a word. - word := string(runes[w:i]) - if !eow && commonInitialisms[word] && !unicode.IsLower(runes[i]) { - // through - // split IDFoo → ID, Foo - // but URLs → URLs - } else if !eow { - if commonInitialisms[word] { - hasCommonInitial = true - } - continue - } - - matchCommonInitial := false - if commonInitialisms[strings.ToUpper(word)] { - hasCommonInitial = true - matchCommonInitial = true - } - - f(&wordInfo{ - WordOffset: wo, - Word: word, - MatchCommonInitial: matchCommonInitial, - HasCommonInitial: hasCommonInitial, - }) - hasCommonInitial = false - w = i - wo++ - } -} - -var keywords = []string{ - "break", - "default", - "func", - "interface", - "select", - "case", - "defer", - "go", - "map", - "struct", - "chan", - "else", - "goto", - "package", - "switch", - "const", - "fallthrough", - "if", - "range", - "type", - "continue", - "for", - "import", - "return", - "var", - "_", -} - -// sanitizeKeywords prevents collisions with go keywords for arguments to resolver functions -func sanitizeKeywords(name string) string { - for _, k := range keywords { - if name == k { - return name + "Arg" - } - } - return name -} - -// commonInitialisms is a set of common initialisms. -// Only add entries that are highly unlikely to be non-initialisms. -// For instance, "ID" is fine (Freudian code is rare), but "AND" is not. -var commonInitialisms = map[string]bool{ - "ACL": true, - "API": true, - "ASCII": true, - "CPU": true, - "CSS": true, - "CSV": true, - "DNS": true, - "EOF": true, - "GUID": true, - "HTML": true, - "HTTP": true, - "HTTPS": true, - "ICMP": true, - "ID": true, - "IP": true, - "JSON": true, - "KVK": true, - "LHS": true, - "PDF": true, - "PGP": true, - "QPS": true, - "QR": true, - "RAM": true, - "RHS": true, - "RPC": true, - "SLA": true, - "SMTP": true, - "SQL": true, - "SSH": true, - "SVG": true, - "TCP": true, - "TLS": true, - "TTL": true, - "UDP": true, - "UI": true, - "UID": true, - "URI": true, - "URL": true, - "UTF8": true, - "UUID": true, - "VM": true, - "XML": true, - "XMPP": true, - "XSRF": true, - "XSS": true, -} - -func rawQuote(s string) string { - return "`" + strings.ReplaceAll(s, "`", "`+\"`\"+`") + "`" -} - -func notNil(field string, data interface{}) bool { - v := reflect.ValueOf(data) - - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - if v.Kind() != reflect.Struct { - return false - } - val := v.FieldByName(field) - - return val.IsValid() && !val.IsNil() -} - -func Dump(val interface{}) string { - switch val := val.(type) { - case int: - return strconv.Itoa(val) - case int64: - return fmt.Sprintf("%d", val) - case float64: - return fmt.Sprintf("%f", val) - case string: - return strconv.Quote(val) - case bool: - return strconv.FormatBool(val) - case nil: - return "nil" - case []interface{}: - var parts []string - for _, part := range val { - parts = append(parts, Dump(part)) - } - return "[]interface{}{" + strings.Join(parts, ",") + "}" - case map[string]interface{}: - buf := bytes.Buffer{} - buf.WriteString("map[string]interface{}{") - var keys []string - for key := range val { - keys = append(keys, key) - } - sort.Strings(keys) - - for _, key := range keys { - data := val[key] - - buf.WriteString(strconv.Quote(key)) - buf.WriteString(":") - buf.WriteString(Dump(data)) - buf.WriteString(",") - } - buf.WriteString("}") - return buf.String() - default: - panic(fmt.Errorf("unsupported type %T", val)) - } -} - -func prefixLines(prefix, s string) string { - return prefix + strings.ReplaceAll(s, "\n", "\n"+prefix) -} - -func resolveName(name string, skip int) string { - if name[0] == '.' { - // load path relative to calling source file - _, callerFile, _, _ := runtime.Caller(skip + 1) - return filepath.Join(filepath.Dir(callerFile), name[1:]) - } - - // load path relative to this directory - _, callerFile, _, _ := runtime.Caller(0) - return filepath.Join(filepath.Dir(callerFile), name) -} - -func render(filename string, tpldata interface{}) (*bytes.Buffer, error) { - t := template.New("").Funcs(Funcs()) - - b, err := os.ReadFile(filename) - if err != nil { - return nil, err - } - - t, err = t.New(filepath.Base(filename)).Parse(string(b)) - if err != nil { - panic(err) - } - - buf := &bytes.Buffer{} - return buf, t.Execute(buf, tpldata) -} - -func write(filename string, b []byte, packages *code.Packages) error { - err := os.MkdirAll(filepath.Dir(filename), 0o755) - if err != nil { - return fmt.Errorf("failed to create directory: %w", err) - } - - formatted, err := imports.Prune(filename, b, packages) - if err != nil { - fmt.Fprintf(os.Stderr, "gofmt failed on %s: %s\n", filepath.Base(filename), err.Error()) - formatted = b - } - - err = os.WriteFile(filename, formatted, 0o644) - if err != nil { - return fmt.Errorf("failed to write %s: %w", filename, err) - } - - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/test.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/test.gotpl deleted file mode 100644 index 07b8462a6a..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/templates/test.gotpl +++ /dev/null @@ -1 +0,0 @@ -this is my test package diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/test_.gotpl b/vendor/github.com/99designs/gqlgen/codegen/templates/test_.gotpl deleted file mode 100644 index c74258f3e1..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/templates/test_.gotpl +++ /dev/null @@ -1 +0,0 @@ -this will not be included diff --git a/vendor/github.com/99designs/gqlgen/codegen/type.go b/vendor/github.com/99designs/gqlgen/codegen/type.go deleted file mode 100644 index 20b09dc975..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/type.go +++ /dev/null @@ -1,32 +0,0 @@ -package codegen - -import ( - "fmt" - - "github.com/99designs/gqlgen/codegen/config" -) - -func (b *builder) buildTypes() map[string]*config.TypeReference { - ret := map[string]*config.TypeReference{} - for _, ref := range b.Binder.References { - processType(ret, ref) - } - return ret -} - -func processType(ret map[string]*config.TypeReference, ref *config.TypeReference) { - key := ref.UniquenessKey() - if existing, found := ret[key]; found { - // Simplistic check of content which is obviously different. - existingGQL := fmt.Sprintf("%v", existing.GQL) - newGQL := fmt.Sprintf("%v", ref.GQL) - if existingGQL != newGQL { - panic(fmt.Sprintf("non-unique key \"%s\", trying to replace %s with %s", key, existingGQL, newGQL)) - } - } - ret[key] = ref - - if ref.IsSlice() || ref.IsPtrToSlice() || ref.IsPtrToPtr() { - processType(ret, ref.Elem()) - } -} diff --git a/vendor/github.com/99designs/gqlgen/codegen/type.gotpl b/vendor/github.com/99designs/gqlgen/codegen/type.gotpl deleted file mode 100644 index d5c3919588..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/type.gotpl +++ /dev/null @@ -1,192 +0,0 @@ -{{- range $type := .ReferencedTypes }} - {{ with $type.UnmarshalFunc }} - func (ec *executionContext) {{ . }}(ctx context.Context, v interface{}) ({{ $type.GO | ref }}, error) { - {{- if and $type.IsNilable (not $type.GQL.NonNull) (not $type.IsPtrToPtr) }} - if v == nil { return nil, nil } - {{- end }} - {{- if $type.IsPtrToSlice }} - res, err := ec.{{ $type.Elem.UnmarshalFunc }}(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) - {{- else if $type.IsSlice }} - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]{{$type.GO.Elem | ref}}, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.{{ $type.Elem.UnmarshalFunc }}(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil - {{- else if and $type.IsPtrToPtr (not $type.Unmarshaler) (not $type.IsMarshaler) }} - var pres {{ $type.Elem.GO | ref }} - if v != nil { - res, err := ec.{{ $type.Elem.UnmarshalFunc }}(ctx, v) - if err != nil { - return nil, graphql.ErrorOnPath(ctx, err) - } - pres = res - } - return &pres, nil - {{- else }} - {{- if $type.Unmarshaler }} - {{- if $type.CastType }} - {{- if $type.IsContext }} - tmp, err := {{ $type.Unmarshaler | call }}(ctx, v) - {{- else }} - tmp, err := {{ $type.Unmarshaler | call }}(v) - {{- end }} - {{- if and $type.IsNilable $type.Elem }} - res := {{ $type.Elem.GO | ref }}(tmp) - {{- else}} - res := {{ $type.GO | ref }}(tmp) - {{- end }} - {{- else}} - {{- if $type.IsContext }} - res, err := {{ $type.Unmarshaler | call }}(ctx, v) - {{- else }} - res, err := {{ $type.Unmarshaler | call }}(v) - {{- end }} - {{- end }} - {{- if and $type.IsTargetNilable (not $type.IsNilable) }} - return *res, graphql.ErrorOnPath(ctx, err) - {{- else if and (not $type.IsTargetNilable) $type.IsNilable }} - return &res, graphql.ErrorOnPath(ctx, err) - {{- else}} - return res, graphql.ErrorOnPath(ctx, err) - {{- end }} - {{- else if eq ($type.GO | ref) "map[string]interface{}" }} - return v.(map[string]interface{}), nil - {{- else if $type.IsMarshaler }} - {{- if and $type.IsNilable $type.Elem }} - var res = new({{ $type.Elem.GO | ref }}) - {{- else}} - var res {{ $type.GO | ref }} - {{- end }} - {{- if $type.IsContext }} - err := res.UnmarshalGQLContext(ctx, v) - {{- else }} - err := res.UnmarshalGQL(v) - {{- end }} - return res, graphql.ErrorOnPath(ctx, err) - {{- else }} - res, err := ec.unmarshalInput{{ $type.GQL.Name }}(ctx, v) - {{- if $type.IsNilable }} - return &res, graphql.ErrorOnPath(ctx, err) - {{- else}} - return res, graphql.ErrorOnPath(ctx, err) - {{- end }} - {{- end }} - {{- end }} - } - {{- end }} - - {{ with $type.MarshalFunc }} - func (ec *executionContext) {{ . }}(ctx context.Context, sel ast.SelectionSet, v {{ $type.GO | ref }}) graphql.Marshaler { - {{- if $type.IsPtrToSlice }} - return ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, *v) - {{- else if $type.IsSlice }} - {{- if not $type.GQL.NonNull }} - if v == nil { - return graphql.Null - } - {{- end }} - ret := make(graphql.Array, len(v)) - {{- if not $type.IsScalar }} - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - {{- end }} - for i := range v { - {{- if not $type.IsScalar }} - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - {{ else }} - ret[i] = ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, v[i]) - {{- end }} - } - {{ if not $type.IsScalar }} wg.Wait() {{ end }} - {{ if $type.Elem.GQL.NonNull }} - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - {{ end }} - return ret - {{- else if and $type.IsPtrToPtr (not $type.Unmarshaler) (not $type.IsMarshaler) }} - if v == nil { - return graphql.Null - } - return ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, *v) - {{- else }} - {{- if $type.IsNilable }} - if v == nil { - {{- if $type.GQL.NonNull }} - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - {{- end }} - return graphql.Null - } - {{- end }} - {{- if $type.IsMarshaler }} - {{- if $type.IsContext }} - return graphql.WrapContextMarshaler(ctx, v) - {{- else }} - return v - {{- end }} - {{- else if $type.Marshaler }} - {{- $v := "v" }} - {{- if and $type.IsTargetNilable (not $type.IsNilable) }} - {{- $v = "&v" }} - {{- else if and (not $type.IsTargetNilable) $type.IsNilable }} - {{- $v = "*v" }} - {{- end }} - res := {{ $type.Marshaler | call }}({{- if $type.CastType }}{{ $type.CastType | ref }}({{ $v }}){{else}}{{ $v }}{{- end }}) - {{- if $type.GQL.NonNull }} - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - {{- end }} - {{- if $type.IsContext }} - return graphql.WrapContextMarshaler(ctx, res) - {{- else }} - return res - {{- end }} - {{- else }} - return ec._{{$type.Definition.Name}}(ctx, sel, {{ if not $type.IsNilable}}&{{end}} v) - {{- end }} - {{- end }} - } - {{- end }} -{{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/util.go b/vendor/github.com/99designs/gqlgen/codegen/util.go deleted file mode 100644 index fa2ceed3df..0000000000 --- a/vendor/github.com/99designs/gqlgen/codegen/util.go +++ /dev/null @@ -1,46 +0,0 @@ -package codegen - -import ( - "fmt" - "go/types" - "strings" -) - -func findGoNamedType(def types.Type) (*types.Named, error) { - if def == nil { - return nil, nil - } - - namedType, ok := def.(*types.Named) - if !ok { - return nil, fmt.Errorf("expected %s to be a named type, instead found %T\n", def.String(), def) - } - - return namedType, nil -} - -func findGoInterface(def types.Type) (*types.Interface, error) { - if def == nil { - return nil, nil - } - namedType, err := findGoNamedType(def) - if err != nil { - return nil, err - } - if namedType == nil { - return nil, nil - } - - underlying, ok := namedType.Underlying().(*types.Interface) - if !ok { - return nil, fmt.Errorf("expected %s to be a named interface, instead found %s", def.String(), namedType.String()) - } - - return underlying, nil -} - -func equalFieldName(source, target string) bool { - source = strings.ReplaceAll(source, "_", "") - target = strings.ReplaceAll(target, "_", "") - return strings.EqualFold(source, target) -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/any.go b/vendor/github.com/99designs/gqlgen/graphql/any.go deleted file mode 100644 index 6ea8bf2eae..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/any.go +++ /dev/null @@ -1,19 +0,0 @@ -package graphql - -import ( - "encoding/json" - "io" -) - -func MarshalAny(v interface{}) Marshaler { - return WriterFunc(func(w io.Writer) { - err := json.NewEncoder(w).Encode(v) - if err != nil { - panic(err) - } - }) -} - -func UnmarshalAny(v interface{}) (interface{}, error) { - return v, nil -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/bool.go b/vendor/github.com/99designs/gqlgen/graphql/bool.go deleted file mode 100644 index f435e0c098..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/bool.go +++ /dev/null @@ -1,27 +0,0 @@ -package graphql - -import ( - "fmt" - "io" - "strings" -) - -func MarshalBoolean(b bool) Marshaler { - if b { - return WriterFunc(func(w io.Writer) { w.Write(trueLit) }) - } - return WriterFunc(func(w io.Writer) { w.Write(falseLit) }) -} - -func UnmarshalBoolean(v interface{}) (bool, error) { - switch v := v.(type) { - case string: - return strings.ToLower(v) == "true", nil - case int: - return v != 0, nil - case bool: - return v, nil - default: - return false, fmt.Errorf("%T is not a bool", v) - } -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/cache.go b/vendor/github.com/99designs/gqlgen/graphql/cache.go deleted file mode 100644 index fe86ca3502..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/cache.go +++ /dev/null @@ -1,29 +0,0 @@ -package graphql - -import "context" - -// Cache is a shared store for APQ and query AST caching -type Cache interface { - // Get looks up a key's value from the cache. - Get(ctx context.Context, key string) (value interface{}, ok bool) - - // Add adds a value to the cache. - Add(ctx context.Context, key string, value interface{}) -} - -// MapCache is the simplest implementation of a cache, because it can not evict it should only be used in tests -type MapCache map[string]interface{} - -// Get looks up a key's value from the cache. -func (m MapCache) Get(ctx context.Context, key string) (value interface{}, ok bool) { - v, ok := m[key] - return v, ok -} - -// Add adds a value to the cache. -func (m MapCache) Add(ctx context.Context, key string, value interface{}) { m[key] = value } - -type NoCache struct{} - -func (n NoCache) Get(ctx context.Context, key string) (value interface{}, ok bool) { return nil, false } -func (n NoCache) Add(ctx context.Context, key string, value interface{}) {} diff --git a/vendor/github.com/99designs/gqlgen/graphql/coercion.go b/vendor/github.com/99designs/gqlgen/graphql/coercion.go deleted file mode 100644 index d3d3c18b2b..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/coercion.go +++ /dev/null @@ -1,56 +0,0 @@ -package graphql - -import ( - "encoding/json" -) - -// CoerceList applies coercion from a single value to a list. -func CoerceList(v interface{}) []interface{} { - var vSlice []interface{} - if v != nil { - switch v := v.(type) { - case []interface{}: - // already a slice no coercion required - vSlice = v - case []string: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []json.Number: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []bool: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []map[string]interface{}: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []float64: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []float32: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []int: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []int32: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []int64: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - default: - vSlice = []interface{}{v} - } - } - return vSlice -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_field.go b/vendor/github.com/99designs/gqlgen/graphql/context_field.go deleted file mode 100644 index 1f9a6e88db..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/context_field.go +++ /dev/null @@ -1,113 +0,0 @@ -package graphql - -import ( - "context" - "time" - - "github.com/vektah/gqlparser/v2/ast" -) - -type key string - -const resolverCtx key = "resolver_context" - -// Deprecated: Use FieldContext instead -type ResolverContext = FieldContext - -type FieldContext struct { - Parent *FieldContext - // The name of the type this field belongs to - Object string - // These are the args after processing, they can be mutated in middleware to change what the resolver will get. - Args map[string]interface{} - // The raw field - Field CollectedField - // The index of array in path. - Index *int - // The result object of resolver - Result interface{} - // IsMethod indicates if the resolver is a method - IsMethod bool - // IsResolver indicates if the field has a user-specified resolver - IsResolver bool - // Child allows getting a child FieldContext by its field collection description. - // Note that, the returned child FieldContext represents the context as it was - // before the execution of the field resolver. For example: - // - // srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (interface{}, error) { - // fc := graphql.GetFieldContext(ctx) - // op := graphql.GetOperationContext(ctx) - // collected := graphql.CollectFields(opCtx, fc.Field.Selections, []string{"User"}) - // - // child, err := fc.Child(ctx, collected[0]) - // if err != nil { - // return nil, err - // } - // fmt.Println("child context %q with args: %v", child.Field.Name, child.Args) - // - // return next(ctx) - // }) - // - Child func(context.Context, CollectedField) (*FieldContext, error) -} - -type FieldStats struct { - // When field execution started - Started time.Time - - // When argument marshaling finished - ArgumentsCompleted time.Time - - // When the field completed running all middleware. Not available inside field middleware! - Completed time.Time -} - -func (r *FieldContext) Path() ast.Path { - var path ast.Path - for it := r; it != nil; it = it.Parent { - if it.Index != nil { - path = append(path, ast.PathIndex(*it.Index)) - } else if it.Field.Field != nil { - path = append(path, ast.PathName(it.Field.Alias)) - } - } - - // because we are walking up the chain, all the elements are backwards, do an inplace flip. - for i := len(path)/2 - 1; i >= 0; i-- { - opp := len(path) - 1 - i - path[i], path[opp] = path[opp], path[i] - } - - return path -} - -// Deprecated: Use GetFieldContext instead -func GetResolverContext(ctx context.Context) *ResolverContext { - return GetFieldContext(ctx) -} - -func GetFieldContext(ctx context.Context) *FieldContext { - if val, ok := ctx.Value(resolverCtx).(*FieldContext); ok { - return val - } - return nil -} - -func WithFieldContext(ctx context.Context, rc *FieldContext) context.Context { - rc.Parent = GetFieldContext(ctx) - return context.WithValue(ctx, resolverCtx, rc) -} - -func equalPath(a ast.Path, b ast.Path) bool { - if len(a) != len(b) { - return false - } - - for i := 0; i < len(a); i++ { - if a[i] != b[i] { - return false - } - } - - return true -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_operation.go b/vendor/github.com/99designs/gqlgen/graphql/context_operation.go deleted file mode 100644 index 0518ecc6ba..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/context_operation.go +++ /dev/null @@ -1,117 +0,0 @@ -package graphql - -import ( - "context" - "errors" - "net/http" - - "github.com/vektah/gqlparser/v2/ast" -) - -// Deprecated: Please update all references to OperationContext instead -type RequestContext = OperationContext - -type OperationContext struct { - RawQuery string - Variables map[string]interface{} - OperationName string - Doc *ast.QueryDocument - Headers http.Header - - Operation *ast.OperationDefinition - DisableIntrospection bool - RecoverFunc RecoverFunc - ResolverMiddleware FieldMiddleware - RootResolverMiddleware RootFieldMiddleware - - Stats Stats -} - -func (c *OperationContext) Validate(ctx context.Context) error { - if c.Doc == nil { - return errors.New("field 'Doc'is required") - } - if c.RawQuery == "" { - return errors.New("field 'RawQuery' is required") - } - if c.Variables == nil { - c.Variables = make(map[string]interface{}) - } - if c.ResolverMiddleware == nil { - return errors.New("field 'ResolverMiddleware' is required") - } - if c.RootResolverMiddleware == nil { - return errors.New("field 'RootResolverMiddleware' is required") - } - if c.RecoverFunc == nil { - c.RecoverFunc = DefaultRecover - } - - return nil -} - -const operationCtx key = "operation_context" - -// Deprecated: Please update all references to GetOperationContext instead -func GetRequestContext(ctx context.Context) *RequestContext { - return GetOperationContext(ctx) -} - -func GetOperationContext(ctx context.Context) *OperationContext { - if val, ok := ctx.Value(operationCtx).(*OperationContext); ok && val != nil { - return val - } - panic("missing operation context") -} - -func WithOperationContext(ctx context.Context, rc *OperationContext) context.Context { - return context.WithValue(ctx, operationCtx, rc) -} - -// HasOperationContext checks if the given context is part of an ongoing operation -// -// Some errors can happen outside of an operation, eg json unmarshal errors. -func HasOperationContext(ctx context.Context) bool { - _, ok := ctx.Value(operationCtx).(*OperationContext) - return ok -} - -// This is just a convenient wrapper method for CollectFields -func CollectFieldsCtx(ctx context.Context, satisfies []string) []CollectedField { - resctx := GetFieldContext(ctx) - return CollectFields(GetOperationContext(ctx), resctx.Field.Selections, satisfies) -} - -// CollectAllFields returns a slice of all GraphQL field names that were selected for the current resolver context. -// The slice will contain the unique set of all field names requested regardless of fragment type conditions. -func CollectAllFields(ctx context.Context) []string { - resctx := GetFieldContext(ctx) - collected := CollectFields(GetOperationContext(ctx), resctx.Field.Selections, nil) - uniq := make([]string, 0, len(collected)) -Next: - for _, f := range collected { - for _, name := range uniq { - if name == f.Name { - continue Next - } - } - uniq = append(uniq, f.Name) - } - return uniq -} - -// Errorf sends an error string to the client, passing it through the formatter. -// Deprecated: use graphql.AddErrorf(ctx, err) instead -func (c *OperationContext) Errorf(ctx context.Context, format string, args ...interface{}) { - AddErrorf(ctx, format, args...) -} - -// Error sends an error to the client, passing it through the formatter. -// Deprecated: use graphql.AddError(ctx, err) instead -func (c *OperationContext) Error(ctx context.Context, err error) { - AddError(ctx, err) -} - -func (c *OperationContext) Recover(ctx context.Context, err interface{}) error { - return ErrorOnPath(ctx, c.RecoverFunc(ctx, err)) -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_path.go b/vendor/github.com/99designs/gqlgen/graphql/context_path.go deleted file mode 100644 index a46ed83ddc..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/context_path.go +++ /dev/null @@ -1,77 +0,0 @@ -package graphql - -import ( - "context" - - "github.com/vektah/gqlparser/v2/ast" -) - -const fieldInputCtx key = "path_context" - -type PathContext struct { - ParentField *FieldContext - Parent *PathContext - Field *string - Index *int -} - -func (fic *PathContext) Path() ast.Path { - var path ast.Path - for it := fic; it != nil; it = it.Parent { - if it.Index != nil { - path = append(path, ast.PathIndex(*it.Index)) - } else if it.Field != nil { - path = append(path, ast.PathName(*it.Field)) - } - } - - // because we are walking up the chain, all the elements are backwards, do an inplace flip. - for i := len(path)/2 - 1; i >= 0; i-- { - opp := len(path) - 1 - i - path[i], path[opp] = path[opp], path[i] - } - - if fic.ParentField != nil { - fieldPath := fic.ParentField.Path() - return append(fieldPath, path...) - - } - - return path -} - -func NewPathWithField(field string) *PathContext { - return &PathContext{Field: &field} -} - -func NewPathWithIndex(index int) *PathContext { - return &PathContext{Index: &index} -} - -func WithPathContext(ctx context.Context, fic *PathContext) context.Context { - if fieldContext := GetFieldContext(ctx); fieldContext != nil { - fic.ParentField = fieldContext - } - if fieldInputContext := GetPathContext(ctx); fieldInputContext != nil { - fic.Parent = fieldInputContext - } - - return context.WithValue(ctx, fieldInputCtx, fic) -} - -func GetPathContext(ctx context.Context) *PathContext { - if val, ok := ctx.Value(fieldInputCtx).(*PathContext); ok { - return val - } - return nil -} - -func GetPath(ctx context.Context) ast.Path { - if pc := GetPathContext(ctx); pc != nil { - return pc.Path() - } - if fc := GetFieldContext(ctx); fc != nil { - return fc.Path() - } - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_response.go b/vendor/github.com/99designs/gqlgen/graphql/context_response.go deleted file mode 100644 index c128fdb49c..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/context_response.go +++ /dev/null @@ -1,153 +0,0 @@ -package graphql - -import ( - "context" - "fmt" - "sync" - - "github.com/vektah/gqlparser/v2/gqlerror" -) - -type responseContext struct { - errorPresenter ErrorPresenterFunc - recover RecoverFunc - - errors gqlerror.List - errorsMu sync.Mutex - - extensions map[string]interface{} - extensionsMu sync.Mutex -} - -const resultCtx key = "result_context" - -func getResponseContext(ctx context.Context) *responseContext { - val, ok := ctx.Value(resultCtx).(*responseContext) - if !ok { - panic("missing response context") - } - return val -} - -func WithResponseContext(ctx context.Context, presenterFunc ErrorPresenterFunc, recoverFunc RecoverFunc) context.Context { - return context.WithValue(ctx, resultCtx, &responseContext{ - errorPresenter: presenterFunc, - recover: recoverFunc, - }) -} - -// AddErrorf writes a formatted error to the client, first passing it through the error presenter. -func AddErrorf(ctx context.Context, format string, args ...interface{}) { - AddError(ctx, fmt.Errorf(format, args...)) -} - -// AddError sends an error to the client, first passing it through the error presenter. -func AddError(ctx context.Context, err error) { - c := getResponseContext(ctx) - - presentedError := c.errorPresenter(ctx, ErrorOnPath(ctx, err)) - - c.errorsMu.Lock() - defer c.errorsMu.Unlock() - c.errors = append(c.errors, presentedError) -} - -func Recover(ctx context.Context, err interface{}) (userMessage error) { - c := getResponseContext(ctx) - return ErrorOnPath(ctx, c.recover(ctx, err)) -} - -// HasFieldError returns true if the given field has already errored -func HasFieldError(ctx context.Context, rctx *FieldContext) bool { - c := getResponseContext(ctx) - - c.errorsMu.Lock() - defer c.errorsMu.Unlock() - - if len(c.errors) == 0 { - return false - } - - path := rctx.Path() - for _, err := range c.errors { - if equalPath(err.Path, path) { - return true - } - } - return false -} - -// GetFieldErrors returns a list of errors that occurred in the given field -func GetFieldErrors(ctx context.Context, rctx *FieldContext) gqlerror.List { - c := getResponseContext(ctx) - - c.errorsMu.Lock() - defer c.errorsMu.Unlock() - - if len(c.errors) == 0 { - return nil - } - - path := rctx.Path() - var errs gqlerror.List - for _, err := range c.errors { - if equalPath(err.Path, path) { - errs = append(errs, err) - } - } - return errs -} - -func GetErrors(ctx context.Context) gqlerror.List { - resCtx := getResponseContext(ctx) - resCtx.errorsMu.Lock() - defer resCtx.errorsMu.Unlock() - - if len(resCtx.errors) == 0 { - return nil - } - - errs := resCtx.errors - cpy := make(gqlerror.List, len(errs)) - for i := range errs { - errCpy := *errs[i] - cpy[i] = &errCpy - } - return cpy -} - -// RegisterExtension allows you to add a new extension into the graphql response -func RegisterExtension(ctx context.Context, key string, value interface{}) { - c := getResponseContext(ctx) - c.extensionsMu.Lock() - defer c.extensionsMu.Unlock() - - if c.extensions == nil { - c.extensions = make(map[string]interface{}) - } - - if _, ok := c.extensions[key]; ok { - panic(fmt.Errorf("extension already registered for key %s", key)) - } - - c.extensions[key] = value -} - -// GetExtensions returns any extensions registered in the current result context -func GetExtensions(ctx context.Context) map[string]interface{} { - ext := getResponseContext(ctx).extensions - if ext == nil { - return map[string]interface{}{} - } - - return ext -} - -func GetExtension(ctx context.Context, name string) interface{} { - ext := getResponseContext(ctx).extensions - if ext == nil { - return nil - } - - return ext[name] -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_root_field.go b/vendor/github.com/99designs/gqlgen/graphql/context_root_field.go deleted file mode 100644 index 1bf4d13b84..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/context_root_field.go +++ /dev/null @@ -1,25 +0,0 @@ -package graphql - -import ( - "context" -) - -const rootResolverCtx key = "root_resolver_context" - -type RootFieldContext struct { - // The name of the type this field belongs to - Object string - // The raw field - Field CollectedField -} - -func GetRootFieldContext(ctx context.Context) *RootFieldContext { - if val, ok := ctx.Value(rootResolverCtx).(*RootFieldContext); ok { - return val - } - return nil -} - -func WithRootFieldContext(ctx context.Context, rc *RootFieldContext) context.Context { - return context.WithValue(ctx, rootResolverCtx, rc) -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/errcode/codes.go b/vendor/github.com/99designs/gqlgen/graphql/errcode/codes.go deleted file mode 100644 index 854b206f4e..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/errcode/codes.go +++ /dev/null @@ -1,60 +0,0 @@ -package errcode - -import ( - "github.com/vektah/gqlparser/v2/gqlerror" -) - -const ( - ValidationFailed = "GRAPHQL_VALIDATION_FAILED" - ParseFailed = "GRAPHQL_PARSE_FAILED" -) - -type ErrorKind int - -const ( - // issues with graphql (validation, parsing). 422s in http, GQL_ERROR in websocket - KindProtocol ErrorKind = iota - // user errors, 200s in http, GQL_DATA in websocket - KindUser -) - -var codeType = map[string]ErrorKind{ - ValidationFailed: KindProtocol, - ParseFailed: KindProtocol, -} - -// RegisterErrorType should be called by extensions that want to customize the http status codes for -// errors they return -func RegisterErrorType(code string, kind ErrorKind) { - codeType[code] = kind -} - -// Set the error code on a given graphql error extension -func Set(err error, value string) { - if err == nil { - return - } - gqlErr, ok := err.(*gqlerror.Error) - if !ok { - return - } - - if gqlErr.Extensions == nil { - gqlErr.Extensions = map[string]interface{}{} - } - - gqlErr.Extensions["code"] = value -} - -// get the kind of the first non User error, defaults to User if no errors have a custom extension -func GetErrorKind(errs gqlerror.List) ErrorKind { - for _, err := range errs { - if code, ok := err.Extensions["code"].(string); ok { - if kind, ok := codeType[code]; ok && kind != KindUser { - return kind - } - } - } - - return KindUser -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/error.go b/vendor/github.com/99designs/gqlgen/graphql/error.go deleted file mode 100644 index f816bef6b8..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/error.go +++ /dev/null @@ -1,33 +0,0 @@ -package graphql - -import ( - "context" - "errors" - - "github.com/vektah/gqlparser/v2/gqlerror" -) - -type ErrorPresenterFunc func(ctx context.Context, err error) *gqlerror.Error - -func DefaultErrorPresenter(ctx context.Context, err error) *gqlerror.Error { - var gqlErr *gqlerror.Error - if errors.As(err, &gqlErr) { - return gqlErr - } - return gqlerror.WrapPath(GetPath(ctx), err) -} - -func ErrorOnPath(ctx context.Context, err error) error { - if err == nil { - return nil - } - var gqlErr *gqlerror.Error - if errors.As(err, &gqlErr) { - if gqlErr.Path == nil { - gqlErr.Path = GetPath(ctx) - } - // Return the original error to avoid losing any attached annotation - return err - } - return gqlerror.WrapPath(GetPath(ctx), err) -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/executable_schema.go b/vendor/github.com/99designs/gqlgen/graphql/executable_schema.go deleted file mode 100644 index 6189162288..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/executable_schema.go +++ /dev/null @@ -1,167 +0,0 @@ -//go:generate go run github.com/matryer/moq -out executable_schema_mock.go . ExecutableSchema - -package graphql - -import ( - "context" - "fmt" - - "github.com/vektah/gqlparser/v2/ast" -) - -type ExecutableSchema interface { - Schema() *ast.Schema - - Complexity(typeName, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) - Exec(ctx context.Context) ResponseHandler -} - -// CollectFields returns the set of fields from an ast.SelectionSet where all collected fields satisfy at least one of the GraphQL types -// passed through satisfies. Providing an empty or nil slice for satisfies will return collect all fields regardless of fragment -// type conditions. -func CollectFields(reqCtx *OperationContext, selSet ast.SelectionSet, satisfies []string) []CollectedField { - return collectFields(reqCtx, selSet, satisfies, map[string]bool{}) -} - -func collectFields(reqCtx *OperationContext, selSet ast.SelectionSet, satisfies []string, visited map[string]bool) []CollectedField { - groupedFields := make([]CollectedField, 0, len(selSet)) - - for _, sel := range selSet { - switch sel := sel.(type) { - case *ast.Field: - if !shouldIncludeNode(sel.Directives, reqCtx.Variables) { - continue - } - f := getOrCreateAndAppendField(&groupedFields, sel.Name, sel.Alias, sel.ObjectDefinition, func() CollectedField { - return CollectedField{Field: sel} - }) - - f.Selections = append(f.Selections, sel.SelectionSet...) - - case *ast.InlineFragment: - if !shouldIncludeNode(sel.Directives, reqCtx.Variables) { - continue - } - if len(satisfies) > 0 && !instanceOf(sel.TypeCondition, satisfies) { - continue - } - for _, childField := range collectFields(reqCtx, sel.SelectionSet, satisfies, visited) { - f := getOrCreateAndAppendField(&groupedFields, childField.Name, childField.Alias, childField.ObjectDefinition, func() CollectedField { return childField }) - f.Selections = append(f.Selections, childField.Selections...) - } - - case *ast.FragmentSpread: - if !shouldIncludeNode(sel.Directives, reqCtx.Variables) { - continue - } - fragmentName := sel.Name - if _, seen := visited[fragmentName]; seen { - continue - } - visited[fragmentName] = true - - fragment := reqCtx.Doc.Fragments.ForName(fragmentName) - if fragment == nil { - // should never happen, validator has already run - panic(fmt.Errorf("missing fragment %s", fragmentName)) - } - - if len(satisfies) > 0 && !instanceOf(fragment.TypeCondition, satisfies) { - continue - } - - for _, childField := range collectFields(reqCtx, fragment.SelectionSet, satisfies, visited) { - f := getOrCreateAndAppendField(&groupedFields, childField.Name, childField.Alias, childField.ObjectDefinition, func() CollectedField { return childField }) - f.Selections = append(f.Selections, childField.Selections...) - } - - default: - panic(fmt.Errorf("unsupported %T", sel)) - } - } - - return groupedFields -} - -type CollectedField struct { - *ast.Field - - Selections ast.SelectionSet -} - -func instanceOf(val string, satisfies []string) bool { - for _, s := range satisfies { - if val == s { - return true - } - } - return false -} - -func getOrCreateAndAppendField(c *[]CollectedField, name string, alias string, objectDefinition *ast.Definition, creator func() CollectedField) *CollectedField { - for i, cf := range *c { - if cf.Name == name && cf.Alias == alias { - if cf.ObjectDefinition == objectDefinition { - return &(*c)[i] - } - - if cf.ObjectDefinition == nil || objectDefinition == nil { - continue - } - - if cf.ObjectDefinition.Name == objectDefinition.Name { - return &(*c)[i] - } - - for _, ifc := range objectDefinition.Interfaces { - if ifc == cf.ObjectDefinition.Name { - return &(*c)[i] - } - } - for _, ifc := range cf.ObjectDefinition.Interfaces { - if ifc == objectDefinition.Name { - return &(*c)[i] - } - } - } - } - - f := creator() - - *c = append(*c, f) - return &(*c)[len(*c)-1] -} - -func shouldIncludeNode(directives ast.DirectiveList, variables map[string]interface{}) bool { - if len(directives) == 0 { - return true - } - - skip, include := false, true - - if d := directives.ForName("skip"); d != nil { - skip = resolveIfArgument(d, variables) - } - - if d := directives.ForName("include"); d != nil { - include = resolveIfArgument(d, variables) - } - - return !skip && include -} - -func resolveIfArgument(d *ast.Directive, variables map[string]interface{}) bool { - arg := d.Arguments.ForName("if") - if arg == nil { - panic(fmt.Sprintf("%s: argument 'if' not defined", d.Name)) - } - value, err := arg.Value.Value(variables) - if err != nil { - panic(err) - } - ret, ok := value.(bool) - if !ok { - panic(fmt.Sprintf("%s: argument 'if' is not a boolean", d.Name)) - } - return ret -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/executable_schema_mock.go b/vendor/github.com/99designs/gqlgen/graphql/executable_schema_mock.go deleted file mode 100644 index 5d7433162f..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/executable_schema_mock.go +++ /dev/null @@ -1,172 +0,0 @@ -// Code generated by moq; DO NOT EDIT. -// github.com/matryer/moq - -package graphql - -import ( - "context" - "github.com/vektah/gqlparser/v2/ast" - "sync" -) - -// Ensure, that ExecutableSchemaMock does implement ExecutableSchema. -// If this is not the case, regenerate this file with moq. -var _ ExecutableSchema = &ExecutableSchemaMock{} - -// ExecutableSchemaMock is a mock implementation of ExecutableSchema. -// -// func TestSomethingThatUsesExecutableSchema(t *testing.T) { -// -// // make and configure a mocked ExecutableSchema -// mockedExecutableSchema := &ExecutableSchemaMock{ -// ComplexityFunc: func(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) { -// panic("mock out the Complexity method") -// }, -// ExecFunc: func(ctx context.Context) ResponseHandler { -// panic("mock out the Exec method") -// }, -// SchemaFunc: func() *ast.Schema { -// panic("mock out the Schema method") -// }, -// } -// -// // use mockedExecutableSchema in code that requires ExecutableSchema -// // and then make assertions. -// -// } -type ExecutableSchemaMock struct { - // ComplexityFunc mocks the Complexity method. - ComplexityFunc func(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) - - // ExecFunc mocks the Exec method. - ExecFunc func(ctx context.Context) ResponseHandler - - // SchemaFunc mocks the Schema method. - SchemaFunc func() *ast.Schema - - // calls tracks calls to the methods. - calls struct { - // Complexity holds details about calls to the Complexity method. - Complexity []struct { - // TypeName is the typeName argument value. - TypeName string - // FieldName is the fieldName argument value. - FieldName string - // ChildComplexity is the childComplexity argument value. - ChildComplexity int - // Args is the args argument value. - Args map[string]interface{} - } - // Exec holds details about calls to the Exec method. - Exec []struct { - // Ctx is the ctx argument value. - Ctx context.Context - } - // Schema holds details about calls to the Schema method. - Schema []struct { - } - } - lockComplexity sync.RWMutex - lockExec sync.RWMutex - lockSchema sync.RWMutex -} - -// Complexity calls ComplexityFunc. -func (mock *ExecutableSchemaMock) Complexity(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) { - if mock.ComplexityFunc == nil { - panic("ExecutableSchemaMock.ComplexityFunc: method is nil but ExecutableSchema.Complexity was just called") - } - callInfo := struct { - TypeName string - FieldName string - ChildComplexity int - Args map[string]interface{} - }{ - TypeName: typeName, - FieldName: fieldName, - ChildComplexity: childComplexity, - Args: args, - } - mock.lockComplexity.Lock() - mock.calls.Complexity = append(mock.calls.Complexity, callInfo) - mock.lockComplexity.Unlock() - return mock.ComplexityFunc(typeName, fieldName, childComplexity, args) -} - -// ComplexityCalls gets all the calls that were made to Complexity. -// Check the length with: -// len(mockedExecutableSchema.ComplexityCalls()) -func (mock *ExecutableSchemaMock) ComplexityCalls() []struct { - TypeName string - FieldName string - ChildComplexity int - Args map[string]interface{} -} { - var calls []struct { - TypeName string - FieldName string - ChildComplexity int - Args map[string]interface{} - } - mock.lockComplexity.RLock() - calls = mock.calls.Complexity - mock.lockComplexity.RUnlock() - return calls -} - -// Exec calls ExecFunc. -func (mock *ExecutableSchemaMock) Exec(ctx context.Context) ResponseHandler { - if mock.ExecFunc == nil { - panic("ExecutableSchemaMock.ExecFunc: method is nil but ExecutableSchema.Exec was just called") - } - callInfo := struct { - Ctx context.Context - }{ - Ctx: ctx, - } - mock.lockExec.Lock() - mock.calls.Exec = append(mock.calls.Exec, callInfo) - mock.lockExec.Unlock() - return mock.ExecFunc(ctx) -} - -// ExecCalls gets all the calls that were made to Exec. -// Check the length with: -// len(mockedExecutableSchema.ExecCalls()) -func (mock *ExecutableSchemaMock) ExecCalls() []struct { - Ctx context.Context -} { - var calls []struct { - Ctx context.Context - } - mock.lockExec.RLock() - calls = mock.calls.Exec - mock.lockExec.RUnlock() - return calls -} - -// Schema calls SchemaFunc. -func (mock *ExecutableSchemaMock) Schema() *ast.Schema { - if mock.SchemaFunc == nil { - panic("ExecutableSchemaMock.SchemaFunc: method is nil but ExecutableSchema.Schema was just called") - } - callInfo := struct { - }{} - mock.lockSchema.Lock() - mock.calls.Schema = append(mock.calls.Schema, callInfo) - mock.lockSchema.Unlock() - return mock.SchemaFunc() -} - -// SchemaCalls gets all the calls that were made to Schema. -// Check the length with: -// len(mockedExecutableSchema.SchemaCalls()) -func (mock *ExecutableSchemaMock) SchemaCalls() []struct { -} { - var calls []struct { - } - mock.lockSchema.RLock() - calls = mock.calls.Schema - mock.lockSchema.RUnlock() - return calls -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/executor/executor.go b/vendor/github.com/99designs/gqlgen/graphql/executor/executor.go deleted file mode 100644 index c46a007b99..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/executor/executor.go +++ /dev/null @@ -1,221 +0,0 @@ -package executor - -import ( - "context" - - "github.com/99designs/gqlgen/graphql" - "github.com/99designs/gqlgen/graphql/errcode" - "github.com/vektah/gqlparser/v2/ast" - "github.com/vektah/gqlparser/v2/gqlerror" - "github.com/vektah/gqlparser/v2/parser" - "github.com/vektah/gqlparser/v2/validator" -) - -// Executor executes graphql queries against a schema. -type Executor struct { - es graphql.ExecutableSchema - extensions []graphql.HandlerExtension - ext extensions - - errorPresenter graphql.ErrorPresenterFunc - recoverFunc graphql.RecoverFunc - queryCache graphql.Cache -} - -var _ graphql.GraphExecutor = &Executor{} - -// New creates a new Executor with the given schema, and a default error and -// recovery callbacks, and no query cache or extensions. -func New(es graphql.ExecutableSchema) *Executor { - e := &Executor{ - es: es, - errorPresenter: graphql.DefaultErrorPresenter, - recoverFunc: graphql.DefaultRecover, - queryCache: graphql.NoCache{}, - ext: processExtensions(nil), - } - return e -} - -func (e *Executor) CreateOperationContext( - ctx context.Context, - params *graphql.RawParams, -) (*graphql.OperationContext, gqlerror.List) { - rc := &graphql.OperationContext{ - DisableIntrospection: true, - RecoverFunc: e.recoverFunc, - ResolverMiddleware: e.ext.fieldMiddleware, - RootResolverMiddleware: e.ext.rootFieldMiddleware, - Stats: graphql.Stats{ - Read: params.ReadTime, - OperationStart: graphql.GetStartTime(ctx), - }, - } - ctx = graphql.WithOperationContext(ctx, rc) - - for _, p := range e.ext.operationParameterMutators { - if err := p.MutateOperationParameters(ctx, params); err != nil { - return rc, gqlerror.List{err} - } - } - - rc.RawQuery = params.Query - rc.OperationName = params.OperationName - rc.Headers = params.Headers - - var listErr gqlerror.List - rc.Doc, listErr = e.parseQuery(ctx, &rc.Stats, params.Query) - if len(listErr) != 0 { - return rc, listErr - } - - rc.Operation = rc.Doc.Operations.ForName(params.OperationName) - if rc.Operation == nil { - err := gqlerror.Errorf("operation %s not found", params.OperationName) - errcode.Set(err, errcode.ValidationFailed) - return rc, gqlerror.List{err} - } - - var err error - rc.Variables, err = validator.VariableValues(e.es.Schema(), rc.Operation, params.Variables) - - if err != nil { - gqlErr, ok := err.(*gqlerror.Error) - if ok { - errcode.Set(gqlErr, errcode.ValidationFailed) - return rc, gqlerror.List{gqlErr} - } - } - rc.Stats.Validation.End = graphql.Now() - - for _, p := range e.ext.operationContextMutators { - if err := p.MutateOperationContext(ctx, rc); err != nil { - return rc, gqlerror.List{err} - } - } - - return rc, nil -} - -func (e *Executor) DispatchOperation( - ctx context.Context, - rc *graphql.OperationContext, -) (graphql.ResponseHandler, context.Context) { - ctx = graphql.WithOperationContext(ctx, rc) - - var innerCtx context.Context - res := e.ext.operationMiddleware(ctx, func(ctx context.Context) graphql.ResponseHandler { - innerCtx = ctx - - tmpResponseContext := graphql.WithResponseContext(ctx, e.errorPresenter, e.recoverFunc) - responses := e.es.Exec(tmpResponseContext) - if errs := graphql.GetErrors(tmpResponseContext); errs != nil { - return graphql.OneShot(&graphql.Response{Errors: errs}) - } - - return func(ctx context.Context) *graphql.Response { - ctx = graphql.WithResponseContext(ctx, e.errorPresenter, e.recoverFunc) - resp := e.ext.responseMiddleware(ctx, func(ctx context.Context) *graphql.Response { - resp := responses(ctx) - if resp == nil { - return nil - } - resp.Errors = append(resp.Errors, graphql.GetErrors(ctx)...) - resp.Extensions = graphql.GetExtensions(ctx) - return resp - }) - if resp == nil { - return nil - } - - return resp - } - }) - - return res, innerCtx -} - -func (e *Executor) DispatchError(ctx context.Context, list gqlerror.List) *graphql.Response { - ctx = graphql.WithResponseContext(ctx, e.errorPresenter, e.recoverFunc) - for _, gErr := range list { - graphql.AddError(ctx, gErr) - } - - resp := e.ext.responseMiddleware(ctx, func(ctx context.Context) *graphql.Response { - resp := &graphql.Response{ - Errors: graphql.GetErrors(ctx), - } - resp.Extensions = graphql.GetExtensions(ctx) - return resp - }) - - return resp -} - -func (e *Executor) PresentRecoveredError(ctx context.Context, err interface{}) error { - return e.errorPresenter(ctx, e.recoverFunc(ctx, err)) -} - -func (e *Executor) SetQueryCache(cache graphql.Cache) { - e.queryCache = cache -} - -func (e *Executor) SetErrorPresenter(f graphql.ErrorPresenterFunc) { - e.errorPresenter = f -} - -func (e *Executor) SetRecoverFunc(f graphql.RecoverFunc) { - e.recoverFunc = f -} - -// parseQuery decodes the incoming query and validates it, pulling from cache if present. -// -// NOTE: This should NOT look at variables, they will change per request. It should only parse and -// validate -// the raw query string. -func (e *Executor) parseQuery( - ctx context.Context, - stats *graphql.Stats, - query string, -) (*ast.QueryDocument, gqlerror.List) { - stats.Parsing.Start = graphql.Now() - - if doc, ok := e.queryCache.Get(ctx, query); ok { - now := graphql.Now() - - stats.Parsing.End = now - stats.Validation.Start = now - return doc.(*ast.QueryDocument), nil - } - - doc, err := parser.ParseQuery(&ast.Source{Input: query}) - if err != nil { - gqlErr, ok := err.(*gqlerror.Error) - if ok { - errcode.Set(gqlErr, errcode.ParseFailed) - return nil, gqlerror.List{gqlErr} - } - } - stats.Parsing.End = graphql.Now() - - stats.Validation.Start = graphql.Now() - - if len(doc.Operations) == 0 { - err = gqlerror.Errorf("no operation provided") - gqlErr, _ := err.(*gqlerror.Error) - errcode.Set(err, errcode.ValidationFailed) - return nil, gqlerror.List{gqlErr} - } - - listErr := validator.Validate(e.es.Schema(), doc) - if len(listErr) != 0 { - for _, e := range listErr { - errcode.Set(e, errcode.ValidationFailed) - } - return nil, listErr - } - - e.queryCache.Add(ctx, query, doc) - - return doc, nil -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/executor/extensions.go b/vendor/github.com/99designs/gqlgen/graphql/executor/extensions.go deleted file mode 100644 index a8eebf110c..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/executor/extensions.go +++ /dev/null @@ -1,195 +0,0 @@ -package executor - -import ( - "context" - "fmt" - - "github.com/99designs/gqlgen/graphql" -) - -// Use adds the given extension to this Executor. -func (e *Executor) Use(extension graphql.HandlerExtension) { - if err := extension.Validate(e.es); err != nil { - panic(err) - } - - switch extension.(type) { - case graphql.OperationParameterMutator, - graphql.OperationContextMutator, - graphql.OperationInterceptor, - graphql.RootFieldInterceptor, - graphql.FieldInterceptor, - graphql.ResponseInterceptor: - e.extensions = append(e.extensions, extension) - e.ext = processExtensions(e.extensions) - - default: - panic(fmt.Errorf("cannot Use %T as a gqlgen handler extension because it does not implement any extension hooks", extension)) - } -} - -// AroundFields is a convenience method for creating an extension that only implements field middleware -func (e *Executor) AroundFields(f graphql.FieldMiddleware) { - e.Use(aroundFieldFunc(f)) -} - -// AroundRootFields is a convenience method for creating an extension that only implements root field middleware -func (e *Executor) AroundRootFields(f graphql.RootFieldMiddleware) { - e.Use(aroundRootFieldFunc(f)) -} - -// AroundOperations is a convenience method for creating an extension that only implements operation middleware -func (e *Executor) AroundOperations(f graphql.OperationMiddleware) { - e.Use(aroundOpFunc(f)) -} - -// AroundResponses is a convenience method for creating an extension that only implements response middleware -func (e *Executor) AroundResponses(f graphql.ResponseMiddleware) { - e.Use(aroundRespFunc(f)) -} - -type extensions struct { - operationMiddleware graphql.OperationMiddleware - responseMiddleware graphql.ResponseMiddleware - rootFieldMiddleware graphql.RootFieldMiddleware - fieldMiddleware graphql.FieldMiddleware - operationParameterMutators []graphql.OperationParameterMutator - operationContextMutators []graphql.OperationContextMutator -} - -func processExtensions(exts []graphql.HandlerExtension) extensions { - e := extensions{ - operationMiddleware: func(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler { - return next(ctx) - }, - responseMiddleware: func(ctx context.Context, next graphql.ResponseHandler) *graphql.Response { - return next(ctx) - }, - rootFieldMiddleware: func(ctx context.Context, next graphql.RootResolver) graphql.Marshaler { - return next(ctx) - }, - fieldMiddleware: func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { - return next(ctx) - }, - } - - // this loop goes backwards so the first extension is the outer most middleware and runs first. - for i := len(exts) - 1; i >= 0; i-- { - p := exts[i] - if p, ok := p.(graphql.OperationInterceptor); ok { - previous := e.operationMiddleware - e.operationMiddleware = func(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler { - return p.InterceptOperation(ctx, func(ctx context.Context) graphql.ResponseHandler { - return previous(ctx, next) - }) - } - } - - if p, ok := p.(graphql.ResponseInterceptor); ok { - previous := e.responseMiddleware - e.responseMiddleware = func(ctx context.Context, next graphql.ResponseHandler) *graphql.Response { - return p.InterceptResponse(ctx, func(ctx context.Context) *graphql.Response { - return previous(ctx, next) - }) - } - } - - if p, ok := p.(graphql.RootFieldInterceptor); ok { - previous := e.rootFieldMiddleware - e.rootFieldMiddleware = func(ctx context.Context, next graphql.RootResolver) graphql.Marshaler { - return p.InterceptRootField(ctx, func(ctx context.Context) graphql.Marshaler { - return previous(ctx, next) - }) - } - } - - if p, ok := p.(graphql.FieldInterceptor); ok { - previous := e.fieldMiddleware - e.fieldMiddleware = func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { - return p.InterceptField(ctx, func(ctx context.Context) (res interface{}, err error) { - return previous(ctx, next) - }) - } - } - } - - for _, p := range exts { - if p, ok := p.(graphql.OperationParameterMutator); ok { - e.operationParameterMutators = append(e.operationParameterMutators, p) - } - - if p, ok := p.(graphql.OperationContextMutator); ok { - e.operationContextMutators = append(e.operationContextMutators, p) - } - } - - return e -} - -type aroundOpFunc func(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler - -func (r aroundOpFunc) ExtensionName() string { - return "InlineOperationFunc" -} - -func (r aroundOpFunc) Validate(schema graphql.ExecutableSchema) error { - if r == nil { - return fmt.Errorf("OperationFunc can not be nil") - } - return nil -} - -func (r aroundOpFunc) InterceptOperation(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler { - return r(ctx, next) -} - -type aroundRespFunc func(ctx context.Context, next graphql.ResponseHandler) *graphql.Response - -func (r aroundRespFunc) ExtensionName() string { - return "InlineResponseFunc" -} - -func (r aroundRespFunc) Validate(schema graphql.ExecutableSchema) error { - if r == nil { - return fmt.Errorf("ResponseFunc can not be nil") - } - return nil -} - -func (r aroundRespFunc) InterceptResponse(ctx context.Context, next graphql.ResponseHandler) *graphql.Response { - return r(ctx, next) -} - -type aroundFieldFunc func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) - -func (f aroundFieldFunc) ExtensionName() string { - return "InlineFieldFunc" -} - -func (f aroundFieldFunc) Validate(schema graphql.ExecutableSchema) error { - if f == nil { - return fmt.Errorf("FieldFunc can not be nil") - } - return nil -} - -func (f aroundFieldFunc) InterceptField(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { - return f(ctx, next) -} - -type aroundRootFieldFunc func(ctx context.Context, next graphql.RootResolver) graphql.Marshaler - -func (f aroundRootFieldFunc) ExtensionName() string { - return "InlineRootFieldFunc" -} - -func (f aroundRootFieldFunc) Validate(schema graphql.ExecutableSchema) error { - if f == nil { - return fmt.Errorf("RootFieldFunc can not be nil") - } - return nil -} - -func (f aroundRootFieldFunc) InterceptRootField(ctx context.Context, next graphql.RootResolver) graphql.Marshaler { - return f(ctx, next) -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/fieldset.go b/vendor/github.com/99designs/gqlgen/graphql/fieldset.go deleted file mode 100644 index 351e266fdb..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/fieldset.go +++ /dev/null @@ -1,63 +0,0 @@ -package graphql - -import ( - "io" - "sync" -) - -type FieldSet struct { - fields []CollectedField - Values []Marshaler - delayed []delayedResult -} - -type delayedResult struct { - i int - f func() Marshaler -} - -func NewFieldSet(fields []CollectedField) *FieldSet { - return &FieldSet{ - fields: fields, - Values: make([]Marshaler, len(fields)), - } -} - -func (m *FieldSet) Concurrently(i int, f func() Marshaler) { - m.delayed = append(m.delayed, delayedResult{i: i, f: f}) -} - -func (m *FieldSet) Dispatch() { - if len(m.delayed) == 1 { - // only one concurrent task, no need to spawn a goroutine or deal create waitgroups - d := m.delayed[0] - m.Values[d.i] = d.f() - } else if len(m.delayed) > 1 { - // more than one concurrent task, use the main goroutine to do one, only spawn goroutines for the others - - var wg sync.WaitGroup - for _, d := range m.delayed[1:] { - wg.Add(1) - go func(d delayedResult) { - m.Values[d.i] = d.f() - wg.Done() - }(d) - } - - m.Values[m.delayed[0].i] = m.delayed[0].f() - wg.Wait() - } -} - -func (m *FieldSet) MarshalGQL(writer io.Writer) { - writer.Write(openBrace) - for i, field := range m.fields { - if i != 0 { - writer.Write(comma) - } - writeQuotedString(writer, field.Alias) - writer.Write(colon) - m.Values[i].MarshalGQL(writer) - } - writer.Write(closeBrace) -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/float.go b/vendor/github.com/99designs/gqlgen/graphql/float.go deleted file mode 100644 index ccb825ddb8..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/float.go +++ /dev/null @@ -1,47 +0,0 @@ -package graphql - -import ( - "context" - "encoding/json" - "fmt" - "io" - "math" - "strconv" -) - -func MarshalFloat(f float64) Marshaler { - return WriterFunc(func(w io.Writer) { - io.WriteString(w, fmt.Sprintf("%g", f)) - }) -} - -func UnmarshalFloat(v interface{}) (float64, error) { - switch v := v.(type) { - case string: - return strconv.ParseFloat(v, 64) - case int: - return float64(v), nil - case int64: - return float64(v), nil - case float64: - return v, nil - case json.Number: - return strconv.ParseFloat(string(v), 64) - default: - return 0, fmt.Errorf("%T is not an float", v) - } -} - -func MarshalFloatContext(f float64) ContextMarshaler { - return ContextWriterFunc(func(ctx context.Context, w io.Writer) error { - if math.IsInf(f, 0) || math.IsNaN(f) { - return fmt.Errorf("cannot marshal infinite no NaN float values") - } - io.WriteString(w, fmt.Sprintf("%g", f)) - return nil - }) -} - -func UnmarshalFloatContext(ctx context.Context, v interface{}) (float64, error) { - return UnmarshalFloat(v) -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/handler.go b/vendor/github.com/99designs/gqlgen/graphql/handler.go deleted file mode 100644 index cd358740c8..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/handler.go +++ /dev/null @@ -1,131 +0,0 @@ -package graphql - -import ( - "context" - "net/http" - "strconv" - "strings" - - "github.com/vektah/gqlparser/v2/gqlerror" -) - -type ( - OperationMiddleware func(ctx context.Context, next OperationHandler) ResponseHandler - OperationHandler func(ctx context.Context) ResponseHandler - - ResponseHandler func(ctx context.Context) *Response - ResponseMiddleware func(ctx context.Context, next ResponseHandler) *Response - - Resolver func(ctx context.Context) (res interface{}, err error) - FieldMiddleware func(ctx context.Context, next Resolver) (res interface{}, err error) - - RootResolver func(ctx context.Context) Marshaler - RootFieldMiddleware func(ctx context.Context, next RootResolver) Marshaler - - RawParams struct { - Query string `json:"query"` - OperationName string `json:"operationName"` - Variables map[string]interface{} `json:"variables"` - Extensions map[string]interface{} `json:"extensions"` - Headers http.Header `json:"headers"` - - ReadTime TraceTiming `json:"-"` - } - - GraphExecutor interface { - CreateOperationContext(ctx context.Context, params *RawParams) (*OperationContext, gqlerror.List) - DispatchOperation(ctx context.Context, rc *OperationContext) (ResponseHandler, context.Context) - DispatchError(ctx context.Context, list gqlerror.List) *Response - } - - // HandlerExtension adds functionality to the http handler. See the list of possible hook points below - // Its important to understand the lifecycle of a graphql request and the terminology we use in gqlgen - // before working with these - // - // +--- REQUEST POST /graphql --------------------------------------------+ - // | +- OPERATION query OpName { viewer { name } } -----------------------+ | - // | | RESPONSE { "data": { "viewer": { "name": "bob" } } } | | - // | +- OPERATION subscription OpName2 { chat { message } } --------------+ | - // | | RESPONSE { "data": { "chat": { "message": "hello" } } } | | - // | | RESPONSE { "data": { "chat": { "message": "byee" } } } | | - // | +--------------------------------------------------------------------+ | - // +------------------------------------------------------------------------+ - HandlerExtension interface { - // ExtensionName should be a CamelCase string version of the extension which may be shown in stats and logging. - ExtensionName() string - // Validate is called when adding an extension to the server, it allows validation against the servers schema. - Validate(schema ExecutableSchema) error - } - - // OperationParameterMutator is called before creating a request context. allows manipulating the raw query - // on the way in. - OperationParameterMutator interface { - MutateOperationParameters(ctx context.Context, request *RawParams) *gqlerror.Error - } - - // OperationContextMutator is called after creating the request context, but before executing the root resolver. - OperationContextMutator interface { - MutateOperationContext(ctx context.Context, rc *OperationContext) *gqlerror.Error - } - - // OperationInterceptor is called for each incoming query, for basic requests the writer will be invoked once, - // for subscriptions it will be invoked multiple times. - OperationInterceptor interface { - InterceptOperation(ctx context.Context, next OperationHandler) ResponseHandler - } - - // ResponseInterceptor is called around each graphql operation response. This can be called many times for a single - // operation the case of subscriptions. - ResponseInterceptor interface { - InterceptResponse(ctx context.Context, next ResponseHandler) *Response - } - - RootFieldInterceptor interface { - InterceptRootField(ctx context.Context, next RootResolver) Marshaler - } - - // FieldInterceptor called around each field - FieldInterceptor interface { - InterceptField(ctx context.Context, next Resolver) (res interface{}, err error) - } - - // Transport provides support for different wire level encodings of graphql requests, eg Form, Get, Post, Websocket - Transport interface { - Supports(r *http.Request) bool - Do(w http.ResponseWriter, r *http.Request, exec GraphExecutor) - } -) - -type Status int - -func (p *RawParams) AddUpload(upload Upload, key, path string) *gqlerror.Error { - if !strings.HasPrefix(path, "variables.") { - return gqlerror.Errorf("invalid operations paths for key %s", key) - } - - var ptr interface{} = p.Variables - parts := strings.Split(path, ".") - - // skip the first part (variables) because we started there - for i, p := range parts[1:] { - last := i == len(parts)-2 - if ptr == nil { - return gqlerror.Errorf("path is missing \"variables.\" prefix, key: %s, path: %s", key, path) - } - if index, parseNbrErr := strconv.Atoi(p); parseNbrErr == nil { - if last { - ptr.([]interface{})[index] = upload - } else { - ptr = ptr.([]interface{})[index] - } - } else { - if last { - ptr.(map[string]interface{})[p] = upload - } else { - ptr = ptr.(map[string]interface{})[p] - } - } - } - - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/id.go b/vendor/github.com/99designs/gqlgen/graphql/id.go deleted file mode 100644 index b24605d1d8..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/id.go +++ /dev/null @@ -1,58 +0,0 @@ -package graphql - -import ( - "encoding/json" - "fmt" - "io" - "strconv" -) - -func MarshalID(s string) Marshaler { - return MarshalString(s) -} - -func UnmarshalID(v interface{}) (string, error) { - switch v := v.(type) { - case string: - return v, nil - case json.Number: - return string(v), nil - case int: - return strconv.Itoa(v), nil - case int64: - return strconv.FormatInt(v, 10), nil - case float64: - return fmt.Sprintf("%f", v), nil - case bool: - if v { - return "true", nil - } else { - return "false", nil - } - case nil: - return "null", nil - default: - return "", fmt.Errorf("%T is not a string", v) - } -} - -func MarshalIntID(i int) Marshaler { - return WriterFunc(func(w io.Writer) { - writeQuotedString(w, strconv.Itoa(i)) - }) -} - -func UnmarshalIntID(v interface{}) (int, error) { - switch v := v.(type) { - case string: - return strconv.Atoi(v) - case int: - return v, nil - case int64: - return int(v), nil - case json.Number: - return strconv.Atoi(string(v)) - default: - return 0, fmt.Errorf("%T is not an int", v) - } -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/input.go b/vendor/github.com/99designs/gqlgen/graphql/input.go deleted file mode 100644 index 88c3efaa6e..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/input.go +++ /dev/null @@ -1,55 +0,0 @@ -package graphql - -import ( - "context" - "errors" - "reflect" -) - -const unmarshalInputCtx key = "unmarshal_input_context" - -// BuildUnmarshalerMap returns a map of unmarshal functions of the ExecutableContext -// to use with the WithUnmarshalerMap function. -func BuildUnmarshalerMap(unmarshaler ...interface{}) map[reflect.Type]reflect.Value { - maps := make(map[reflect.Type]reflect.Value) - for _, v := range unmarshaler { - ft := reflect.TypeOf(v) - if ft.Kind() == reflect.Func { - maps[ft.Out(0)] = reflect.ValueOf(v) - } - } - - return maps -} - -// WithUnmarshalerMap returns a new context with a map from input types to their unmarshaler functions. -func WithUnmarshalerMap(ctx context.Context, maps map[reflect.Type]reflect.Value) context.Context { - return context.WithValue(ctx, unmarshalInputCtx, maps) -} - -// UnmarshalInputFromContext allows unmarshaling input object from a context. -func UnmarshalInputFromContext(ctx context.Context, raw, v interface{}) error { - m, ok := ctx.Value(unmarshalInputCtx).(map[reflect.Type]reflect.Value) - if m == nil || !ok { - return errors.New("graphql: the input context is empty") - } - - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return errors.New("graphql: input must be a non-nil pointer") - } - if fn, ok := m[rv.Elem().Type()]; ok { - res := fn.Call([]reflect.Value{ - reflect.ValueOf(ctx), - reflect.ValueOf(raw), - }) - if err := res[1].Interface(); err != nil { - return err.(error) - } - - rv.Elem().Set(res[0]) - return nil - } - - return errors.New("graphql: no unmarshal function found") -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/int.go b/vendor/github.com/99designs/gqlgen/graphql/int.go deleted file mode 100644 index 57d0d589ba..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/int.go +++ /dev/null @@ -1,79 +0,0 @@ -package graphql - -import ( - "encoding/json" - "fmt" - "io" - "strconv" -) - -func MarshalInt(i int) Marshaler { - return WriterFunc(func(w io.Writer) { - io.WriteString(w, strconv.Itoa(i)) - }) -} - -func UnmarshalInt(v interface{}) (int, error) { - switch v := v.(type) { - case string: - return strconv.Atoi(v) - case int: - return v, nil - case int64: - return int(v), nil - case json.Number: - return strconv.Atoi(string(v)) - default: - return 0, fmt.Errorf("%T is not an int", v) - } -} - -func MarshalInt64(i int64) Marshaler { - return WriterFunc(func(w io.Writer) { - io.WriteString(w, strconv.FormatInt(i, 10)) - }) -} - -func UnmarshalInt64(v interface{}) (int64, error) { - switch v := v.(type) { - case string: - return strconv.ParseInt(v, 10, 64) - case int: - return int64(v), nil - case int64: - return v, nil - case json.Number: - return strconv.ParseInt(string(v), 10, 64) - default: - return 0, fmt.Errorf("%T is not an int", v) - } -} - -func MarshalInt32(i int32) Marshaler { - return WriterFunc(func(w io.Writer) { - io.WriteString(w, strconv.FormatInt(int64(i), 10)) - }) -} - -func UnmarshalInt32(v interface{}) (int32, error) { - switch v := v.(type) { - case string: - iv, err := strconv.ParseInt(v, 10, 32) - if err != nil { - return 0, err - } - return int32(iv), nil - case int: - return int32(v), nil - case int64: - return int32(v), nil - case json.Number: - iv, err := strconv.ParseInt(string(v), 10, 32) - if err != nil { - return 0, err - } - return int32(iv), nil - default: - return 0, fmt.Errorf("%T is not an int", v) - } -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/introspection/introspection.go b/vendor/github.com/99designs/gqlgen/graphql/introspection/introspection.go deleted file mode 100644 index 8482d62a86..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/introspection/introspection.go +++ /dev/null @@ -1,101 +0,0 @@ -// introspection implements the spec defined in https://github.com/facebook/graphql/blob/master/spec/Section%204%20--%20Introspection.md#schema-introspection -package introspection - -import "github.com/vektah/gqlparser/v2/ast" - -type ( - Directive struct { - Name string - description string - Locations []string - Args []InputValue - IsRepeatable bool - } - - EnumValue struct { - Name string - description string - deprecation *ast.Directive - } - - Field struct { - Name string - description string - Type *Type - Args []InputValue - deprecation *ast.Directive - } - - InputValue struct { - Name string - description string - DefaultValue *string - Type *Type - } -) - -func WrapSchema(schema *ast.Schema) *Schema { - return &Schema{schema: schema} -} - -func (f *EnumValue) Description() *string { - if f.description == "" { - return nil - } - return &f.description -} - -func (f *EnumValue) IsDeprecated() bool { - return f.deprecation != nil -} - -func (f *EnumValue) DeprecationReason() *string { - if f.deprecation == nil { - return nil - } - - reason := f.deprecation.Arguments.ForName("reason") - if reason == nil { - return nil - } - - return &reason.Value.Raw -} - -func (f *Field) Description() *string { - if f.description == "" { - return nil - } - return &f.description -} - -func (f *Field) IsDeprecated() bool { - return f.deprecation != nil -} - -func (f *Field) DeprecationReason() *string { - if f.deprecation == nil { - return nil - } - - reason := f.deprecation.Arguments.ForName("reason") - if reason == nil { - return nil - } - - return &reason.Value.Raw -} - -func (f *InputValue) Description() *string { - if f.description == "" { - return nil - } - return &f.description -} - -func (f *Directive) Description() *string { - if f.description == "" { - return nil - } - return &f.description -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/introspection/query.go b/vendor/github.com/99designs/gqlgen/graphql/introspection/query.go deleted file mode 100644 index 389a5d85c0..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/introspection/query.go +++ /dev/null @@ -1,106 +0,0 @@ -package introspection - -// Query is the query generated by graphiql to determine type information -const Query = ` -query IntrospectionQuery { - __schema { - description - queryType { - name - } - mutationType { - name - } - subscriptionType { - name - } - types { - ...FullType - } - directives { - name - description - locations - args { - ...InputValue - } - } - } -} - -fragment FullType on __Type { - kind - name - description - specifiedByURL - fields(includeDeprecated: true) { - name - description - args { - ...InputValue - } - type { - ...TypeRef - } - isDeprecated - deprecationReason - } - inputFields { - ...InputValue - } - interfaces { - ...TypeRef - } - enumValues(includeDeprecated: true) { - name - description - isDeprecated - deprecationReason - } - possibleTypes { - ...TypeRef - } -} - -fragment InputValue on __InputValue { - name - description - type { - ...TypeRef - } - defaultValue -} - -fragment TypeRef on __Type { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - } - } - } - } - } - } - } -} -` diff --git a/vendor/github.com/99designs/gqlgen/graphql/introspection/schema.go b/vendor/github.com/99designs/gqlgen/graphql/introspection/schema.go deleted file mode 100644 index b7b0ad94e0..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/introspection/schema.go +++ /dev/null @@ -1,93 +0,0 @@ -package introspection - -import ( - "sort" - "strings" - - "github.com/vektah/gqlparser/v2/ast" -) - -type Schema struct { - schema *ast.Schema -} - -func (s *Schema) Description() *string { - if s.schema.Description == "" { - return nil - } - return &s.schema.Description -} - -func (s *Schema) Types() []Type { - typeIndex := map[string]Type{} - typeNames := make([]string, 0, len(s.schema.Types)) - for _, typ := range s.schema.Types { - if strings.HasPrefix(typ.Name, "__") { - continue - } - typeNames = append(typeNames, typ.Name) - typeIndex[typ.Name] = *WrapTypeFromDef(s.schema, typ) - } - sort.Strings(typeNames) - - types := make([]Type, len(typeNames)) - for i, t := range typeNames { - types[i] = typeIndex[t] - } - return types -} - -func (s *Schema) QueryType() *Type { - return WrapTypeFromDef(s.schema, s.schema.Query) -} - -func (s *Schema) MutationType() *Type { - return WrapTypeFromDef(s.schema, s.schema.Mutation) -} - -func (s *Schema) SubscriptionType() *Type { - return WrapTypeFromDef(s.schema, s.schema.Subscription) -} - -func (s *Schema) Directives() []Directive { - dIndex := map[string]Directive{} - dNames := make([]string, 0, len(s.schema.Directives)) - - for _, d := range s.schema.Directives { - dNames = append(dNames, d.Name) - dIndex[d.Name] = s.directiveFromDef(d) - } - sort.Strings(dNames) - - res := make([]Directive, len(dNames)) - for i, d := range dNames { - res[i] = dIndex[d] - } - - return res -} - -func (s *Schema) directiveFromDef(d *ast.DirectiveDefinition) Directive { - locs := make([]string, len(d.Locations)) - for i, loc := range d.Locations { - locs[i] = string(loc) - } - - args := make([]InputValue, len(d.Arguments)) - for i, arg := range d.Arguments { - args[i] = InputValue{ - Name: arg.Name, - description: arg.Description, - DefaultValue: defaultValue(arg.DefaultValue), - Type: WrapTypeFromType(s.schema, arg.Type), - } - } - - return Directive{ - Name: d.Name, - description: d.Description, - Locations: locs, - Args: args, - IsRepeatable: d.IsRepeatable, - } -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/introspection/type.go b/vendor/github.com/99designs/gqlgen/graphql/introspection/type.go deleted file mode 100644 index c50733d0df..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/introspection/type.go +++ /dev/null @@ -1,191 +0,0 @@ -package introspection - -import ( - "strings" - - "github.com/vektah/gqlparser/v2/ast" -) - -type Type struct { - schema *ast.Schema - def *ast.Definition - typ *ast.Type -} - -func WrapTypeFromDef(s *ast.Schema, def *ast.Definition) *Type { - if def == nil { - return nil - } - return &Type{schema: s, def: def} -} - -func WrapTypeFromType(s *ast.Schema, typ *ast.Type) *Type { - if typ == nil { - return nil - } - - if !typ.NonNull && typ.NamedType != "" { - return &Type{schema: s, def: s.Types[typ.NamedType]} - } - return &Type{schema: s, typ: typ} -} - -func (t *Type) Kind() string { - if t.typ != nil { - if t.typ.NonNull { - return "NON_NULL" - } - - if t.typ.Elem != nil { - return "LIST" - } - } else { - return string(t.def.Kind) - } - - panic("UNKNOWN") -} - -func (t *Type) Name() *string { - if t.def == nil { - return nil - } - return &t.def.Name -} - -func (t *Type) Description() *string { - if t.def == nil || t.def.Description == "" { - return nil - } - return &t.def.Description -} - -func (t *Type) Fields(includeDeprecated bool) []Field { - if t.def == nil || (t.def.Kind != ast.Object && t.def.Kind != ast.Interface) { - return []Field{} - } - fields := []Field{} - for _, f := range t.def.Fields { - if strings.HasPrefix(f.Name, "__") { - continue - } - - if !includeDeprecated && f.Directives.ForName("deprecated") != nil { - continue - } - - var args []InputValue - for _, arg := range f.Arguments { - args = append(args, InputValue{ - Type: WrapTypeFromType(t.schema, arg.Type), - Name: arg.Name, - description: arg.Description, - DefaultValue: defaultValue(arg.DefaultValue), - }) - } - - fields = append(fields, Field{ - Name: f.Name, - description: f.Description, - Args: args, - Type: WrapTypeFromType(t.schema, f.Type), - deprecation: f.Directives.ForName("deprecated"), - }) - } - return fields -} - -func (t *Type) InputFields() []InputValue { - if t.def == nil || t.def.Kind != ast.InputObject { - return []InputValue{} - } - - res := []InputValue{} - for _, f := range t.def.Fields { - res = append(res, InputValue{ - Name: f.Name, - description: f.Description, - Type: WrapTypeFromType(t.schema, f.Type), - DefaultValue: defaultValue(f.DefaultValue), - }) - } - return res -} - -func defaultValue(value *ast.Value) *string { - if value == nil { - return nil - } - val := value.String() - return &val -} - -func (t *Type) Interfaces() []Type { - if t.def == nil || t.def.Kind != ast.Object { - return []Type{} - } - - res := []Type{} - for _, intf := range t.def.Interfaces { - res = append(res, *WrapTypeFromDef(t.schema, t.schema.Types[intf])) - } - - return res -} - -func (t *Type) PossibleTypes() []Type { - if t.def == nil || (t.def.Kind != ast.Interface && t.def.Kind != ast.Union) { - return []Type{} - } - - res := []Type{} - for _, pt := range t.schema.GetPossibleTypes(t.def) { - res = append(res, *WrapTypeFromDef(t.schema, pt)) - } - return res -} - -func (t *Type) EnumValues(includeDeprecated bool) []EnumValue { - if t.def == nil || t.def.Kind != ast.Enum { - return []EnumValue{} - } - - res := []EnumValue{} - for _, val := range t.def.EnumValues { - if !includeDeprecated && val.Directives.ForName("deprecated") != nil { - continue - } - - res = append(res, EnumValue{ - Name: val.Name, - description: val.Description, - deprecation: val.Directives.ForName("deprecated"), - }) - } - return res -} - -func (t *Type) OfType() *Type { - if t.typ == nil { - return nil - } - if t.typ.NonNull { - // fake non null nodes - cpy := *t.typ - cpy.NonNull = false - - return WrapTypeFromType(t.schema, &cpy) - } - return WrapTypeFromType(t.schema, t.typ.Elem) -} - -func (t *Type) SpecifiedByURL() *string { - directive := t.def.Directives.ForName("specifiedBy") - if t.def.Kind != ast.Scalar || directive == nil { - return nil - } - // def: directive @specifiedBy(url: String!) on SCALAR - // the argument "url" is required. - url := directive.Arguments.ForName("url") - return &url.Value.Raw -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/jsonw.go b/vendor/github.com/99designs/gqlgen/graphql/jsonw.go deleted file mode 100644 index 54e293f1ad..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/jsonw.go +++ /dev/null @@ -1,93 +0,0 @@ -package graphql - -import ( - "context" - "io" -) - -var ( - nullLit = []byte(`null`) - trueLit = []byte(`true`) - falseLit = []byte(`false`) - openBrace = []byte(`{`) - closeBrace = []byte(`}`) - openBracket = []byte(`[`) - closeBracket = []byte(`]`) - colon = []byte(`:`) - comma = []byte(`,`) -) - -var ( - Null = &lit{nullLit} - True = &lit{trueLit} - False = &lit{falseLit} -) - -type Marshaler interface { - MarshalGQL(w io.Writer) -} - -type Unmarshaler interface { - UnmarshalGQL(v interface{}) error -} - -type ContextMarshaler interface { - MarshalGQLContext(ctx context.Context, w io.Writer) error -} - -type ContextUnmarshaler interface { - UnmarshalGQLContext(ctx context.Context, v interface{}) error -} - -type contextMarshalerAdapter struct { - Context context.Context - ContextMarshaler -} - -func WrapContextMarshaler(ctx context.Context, m ContextMarshaler) Marshaler { - return contextMarshalerAdapter{Context: ctx, ContextMarshaler: m} -} - -func (a contextMarshalerAdapter) MarshalGQL(w io.Writer) { - err := a.MarshalGQLContext(a.Context, w) - if err != nil { - AddError(a.Context, err) - Null.MarshalGQL(w) - } -} - -type WriterFunc func(writer io.Writer) - -func (f WriterFunc) MarshalGQL(w io.Writer) { - f(w) -} - -type ContextWriterFunc func(ctx context.Context, writer io.Writer) error - -func (f ContextWriterFunc) MarshalGQLContext(ctx context.Context, w io.Writer) error { - return f(ctx, w) -} - -type Array []Marshaler - -func (a Array) MarshalGQL(writer io.Writer) { - writer.Write(openBracket) - for i, val := range a { - if i != 0 { - writer.Write(comma) - } - val.MarshalGQL(writer) - } - writer.Write(closeBracket) -} - -type lit struct{ b []byte } - -func (l lit) MarshalGQL(w io.Writer) { - w.Write(l.b) -} - -func (l lit) MarshalGQLContext(ctx context.Context, w io.Writer) error { - w.Write(l.b) - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/map.go b/vendor/github.com/99designs/gqlgen/graphql/map.go deleted file mode 100644 index 1e91d1d98c..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/map.go +++ /dev/null @@ -1,24 +0,0 @@ -package graphql - -import ( - "encoding/json" - "fmt" - "io" -) - -func MarshalMap(val map[string]interface{}) Marshaler { - return WriterFunc(func(w io.Writer) { - err := json.NewEncoder(w).Encode(val) - if err != nil { - panic(err) - } - }) -} - -func UnmarshalMap(v interface{}) (map[string]interface{}, error) { - if m, ok := v.(map[string]interface{}); ok { - return m, nil - } - - return nil, fmt.Errorf("%T is not a map", v) -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/oneshot.go b/vendor/github.com/99designs/gqlgen/graphql/oneshot.go deleted file mode 100644 index 01fa15f896..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/oneshot.go +++ /dev/null @@ -1,16 +0,0 @@ -package graphql - -import "context" - -func OneShot(resp *Response) ResponseHandler { - var oneshot bool - - return func(context context.Context) *Response { - if oneshot { - return nil - } - oneshot = true - - return resp - } -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/recovery.go b/vendor/github.com/99designs/gqlgen/graphql/recovery.go deleted file mode 100644 index 9bc0e47e1d..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/recovery.go +++ /dev/null @@ -1,20 +0,0 @@ -package graphql - -import ( - "context" - "fmt" - "os" - "runtime/debug" - - "github.com/vektah/gqlparser/v2/gqlerror" -) - -type RecoverFunc func(ctx context.Context, err interface{}) (userMessage error) - -func DefaultRecover(ctx context.Context, err interface{}) error { - fmt.Fprintln(os.Stderr, err) - fmt.Fprintln(os.Stderr) - debug.PrintStack() - - return gqlerror.Errorf("internal system error") -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/response.go b/vendor/github.com/99designs/gqlgen/graphql/response.go deleted file mode 100644 index 0d36049a33..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/response.go +++ /dev/null @@ -1,24 +0,0 @@ -package graphql - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/vektah/gqlparser/v2/gqlerror" -) - -// Errors are intentionally serialized first based on the advice in -// https://github.com/facebook/graphql/commit/7b40390d48680b15cb93e02d46ac5eb249689876#diff-757cea6edf0288677a9eea4cfc801d87R107 -// and https://github.com/facebook/graphql/pull/384 -type Response struct { - Errors gqlerror.List `json:"errors,omitempty"` - Data json.RawMessage `json:"data"` - Extensions map[string]interface{} `json:"extensions,omitempty"` -} - -func ErrorResponse(ctx context.Context, messagef string, args ...interface{}) *Response { - return &Response{ - Errors: gqlerror.List{{Message: fmt.Sprintf(messagef, args...)}}, - } -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/root.go b/vendor/github.com/99designs/gqlgen/graphql/root.go deleted file mode 100644 index 3405d18054..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/root.go +++ /dev/null @@ -1,7 +0,0 @@ -package graphql - -type Query struct{} - -type Mutation struct{} - -type Subscription struct{} diff --git a/vendor/github.com/99designs/gqlgen/graphql/stats.go b/vendor/github.com/99designs/gqlgen/graphql/stats.go deleted file mode 100644 index a52e143ebe..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/stats.go +++ /dev/null @@ -1,60 +0,0 @@ -package graphql - -import ( - "context" - "fmt" - "time" -) - -type Stats struct { - OperationStart time.Time - Read TraceTiming - Parsing TraceTiming - Validation TraceTiming - - // Stats collected by handler extensions. Dont use directly, the extension should provide a type safe way to - // access this. - extension map[string]interface{} -} - -type TraceTiming struct { - Start time.Time - End time.Time -} - -var ctxTraceStart key = "trace_start" - -// StartOperationTrace captures the current time and stores it in context. This will eventually be added to request -// context but we want to grab it as soon as possible. For transports that can only handle a single graphql query -// per http requests you dont need to call this at all, the server will do it for you. For transports that handle -// multiple (eg batching, subscriptions) this should be called before decoding each request. -func StartOperationTrace(ctx context.Context) context.Context { - return context.WithValue(ctx, ctxTraceStart, Now()) -} - -// GetStartTime should only be called by the handler package, it will be set into request context -// as Stats.Start -func GetStartTime(ctx context.Context) time.Time { - t, ok := ctx.Value(ctxTraceStart).(time.Time) - if !ok { - panic(fmt.Sprintf("missing start time: %T", ctx.Value(ctxTraceStart))) - } - return t -} - -func (c *Stats) SetExtension(name string, data interface{}) { - if c.extension == nil { - c.extension = map[string]interface{}{} - } - c.extension[name] = data -} - -func (c *Stats) GetExtension(name string) interface{} { - if c.extension == nil { - return nil - } - return c.extension[name] -} - -// Now is time.Now, except in tests. Then it can be whatever you want it to be. -var Now = time.Now diff --git a/vendor/github.com/99designs/gqlgen/graphql/string.go b/vendor/github.com/99designs/gqlgen/graphql/string.go deleted file mode 100644 index 742e50cc3b..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/string.go +++ /dev/null @@ -1,70 +0,0 @@ -package graphql - -import ( - "fmt" - "io" - "strconv" -) - -const encodeHex = "0123456789ABCDEF" - -func MarshalString(s string) Marshaler { - return WriterFunc(func(w io.Writer) { - writeQuotedString(w, s) - }) -} - -func writeQuotedString(w io.Writer, s string) { - start := 0 - io.WriteString(w, `"`) - - for i, c := range s { - if c < 0x20 || c == '\\' || c == '"' { - io.WriteString(w, s[start:i]) - - switch c { - case '\t': - io.WriteString(w, `\t`) - case '\r': - io.WriteString(w, `\r`) - case '\n': - io.WriteString(w, `\n`) - case '\\': - io.WriteString(w, `\\`) - case '"': - io.WriteString(w, `\"`) - default: - io.WriteString(w, `\u00`) - w.Write([]byte{encodeHex[c>>4], encodeHex[c&0xf]}) - } - - start = i + 1 - } - } - - io.WriteString(w, s[start:]) - io.WriteString(w, `"`) -} - -func UnmarshalString(v interface{}) (string, error) { - switch v := v.(type) { - case string: - return v, nil - case int: - return strconv.Itoa(v), nil - case int64: - return strconv.FormatInt(v, 10), nil - case float64: - return fmt.Sprintf("%f", v), nil - case bool: - if v { - return "true", nil - } else { - return "false", nil - } - case nil: - return "null", nil - default: - return "", fmt.Errorf("%T is not a string", v) - } -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/time.go b/vendor/github.com/99designs/gqlgen/graphql/time.go deleted file mode 100644 index ef3d17da32..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/time.go +++ /dev/null @@ -1,25 +0,0 @@ -package graphql - -import ( - "errors" - "io" - "strconv" - "time" -) - -func MarshalTime(t time.Time) Marshaler { - if t.IsZero() { - return Null - } - - return WriterFunc(func(w io.Writer) { - io.WriteString(w, strconv.Quote(t.Format(time.RFC3339Nano))) - }) -} - -func UnmarshalTime(v interface{}) (time.Time, error) { - if tmpStr, ok := v.(string); ok { - return time.Parse(time.RFC3339Nano, tmpStr) - } - return time.Time{}, errors.New("time should be RFC3339Nano formatted string") -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/uint.go b/vendor/github.com/99designs/gqlgen/graphql/uint.go deleted file mode 100644 index 9349c2f4d2..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/uint.go +++ /dev/null @@ -1,81 +0,0 @@ -package graphql - -import ( - "encoding/json" - "fmt" - "io" - "strconv" -) - -func MarshalUint(i uint) Marshaler { - return WriterFunc(func(w io.Writer) { - _, _ = io.WriteString(w, strconv.FormatUint(uint64(i), 10)) - }) -} - -func UnmarshalUint(v interface{}) (uint, error) { - switch v := v.(type) { - case string: - u64, err := strconv.ParseUint(v, 10, 64) - return uint(u64), err - case int: - return uint(v), nil - case int64: - return uint(v), nil - case json.Number: - u64, err := strconv.ParseUint(string(v), 10, 64) - return uint(u64), err - default: - return 0, fmt.Errorf("%T is not an uint", v) - } -} - -func MarshalUint64(i uint64) Marshaler { - return WriterFunc(func(w io.Writer) { - _, _ = io.WriteString(w, strconv.FormatUint(i, 10)) - }) -} - -func UnmarshalUint64(v interface{}) (uint64, error) { - switch v := v.(type) { - case string: - return strconv.ParseUint(v, 10, 64) - case int: - return uint64(v), nil - case int64: - return uint64(v), nil - case json.Number: - return strconv.ParseUint(string(v), 10, 64) - default: - return 0, fmt.Errorf("%T is not an uint", v) - } -} - -func MarshalUint32(i uint32) Marshaler { - return WriterFunc(func(w io.Writer) { - _, _ = io.WriteString(w, strconv.FormatUint(uint64(i), 10)) - }) -} - -func UnmarshalUint32(v interface{}) (uint32, error) { - switch v := v.(type) { - case string: - iv, err := strconv.ParseInt(v, 10, 32) - if err != nil { - return 0, err - } - return uint32(iv), nil - case int: - return uint32(v), nil - case int64: - return uint32(v), nil - case json.Number: - iv, err := strconv.ParseUint(string(v), 10, 32) - if err != nil { - return 0, err - } - return uint32(iv), nil - default: - return 0, fmt.Errorf("%T is not an uint", v) - } -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/upload.go b/vendor/github.com/99designs/gqlgen/graphql/upload.go deleted file mode 100644 index dafbde6508..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/upload.go +++ /dev/null @@ -1,27 +0,0 @@ -package graphql - -import ( - "fmt" - "io" -) - -type Upload struct { - File io.ReadSeeker - Filename string - Size int64 - ContentType string -} - -func MarshalUpload(f Upload) Marshaler { - return WriterFunc(func(w io.Writer) { - io.Copy(w, f.File) - }) -} - -func UnmarshalUpload(v interface{}) (Upload, error) { - upload, ok := v.(Upload) - if !ok { - return Upload{}, fmt.Errorf("%T is not an Upload", v) - } - return upload, nil -} diff --git a/vendor/github.com/99designs/gqlgen/graphql/version.go b/vendor/github.com/99designs/gqlgen/graphql/version.go deleted file mode 100644 index c0c06f6599..0000000000 --- a/vendor/github.com/99designs/gqlgen/graphql/version.go +++ /dev/null @@ -1,3 +0,0 @@ -package graphql - -const Version = "v0.17.20" diff --git a/vendor/github.com/99designs/gqlgen/internal/code/compare.go b/vendor/github.com/99designs/gqlgen/internal/code/compare.go deleted file mode 100644 index 1150a24e48..0000000000 --- a/vendor/github.com/99designs/gqlgen/internal/code/compare.go +++ /dev/null @@ -1,161 +0,0 @@ -package code - -import ( - "fmt" - "go/types" -) - -// CompatibleTypes isnt a strict comparison, it allows for pointer differences -func CompatibleTypes(expected types.Type, actual types.Type) error { - // Special case to deal with pointer mismatches - { - expectedPtr, expectedIsPtr := expected.(*types.Pointer) - actualPtr, actualIsPtr := actual.(*types.Pointer) - - if expectedIsPtr && actualIsPtr { - return CompatibleTypes(expectedPtr.Elem(), actualPtr.Elem()) - } - if expectedIsPtr && !actualIsPtr { - return CompatibleTypes(expectedPtr.Elem(), actual) - } - if !expectedIsPtr && actualIsPtr { - return CompatibleTypes(expected, actualPtr.Elem()) - } - } - - switch expected := expected.(type) { - case *types.Slice: - if actual, ok := actual.(*types.Slice); ok { - return CompatibleTypes(expected.Elem(), actual.Elem()) - } - - case *types.Array: - if actual, ok := actual.(*types.Array); ok { - if expected.Len() != actual.Len() { - return fmt.Errorf("array length differs") - } - - return CompatibleTypes(expected.Elem(), actual.Elem()) - } - - case *types.Basic: - if actual, ok := actual.(*types.Basic); ok { - if actual.Kind() != expected.Kind() { - return fmt.Errorf("basic kind differs, %s != %s", expected.Name(), actual.Name()) - } - - return nil - } - - case *types.Struct: - if actual, ok := actual.(*types.Struct); ok { - if expected.NumFields() != actual.NumFields() { - return fmt.Errorf("number of struct fields differ") - } - - for i := 0; i < expected.NumFields(); i++ { - if expected.Field(i).Name() != actual.Field(i).Name() { - return fmt.Errorf("struct field %d name differs, %s != %s", i, expected.Field(i).Name(), actual.Field(i).Name()) - } - if err := CompatibleTypes(expected.Field(i).Type(), actual.Field(i).Type()); err != nil { - return err - } - } - return nil - } - - case *types.Tuple: - if actual, ok := actual.(*types.Tuple); ok { - if expected.Len() != actual.Len() { - return fmt.Errorf("tuple length differs, %d != %d", expected.Len(), actual.Len()) - } - - for i := 0; i < expected.Len(); i++ { - if err := CompatibleTypes(expected.At(i).Type(), actual.At(i).Type()); err != nil { - return err - } - } - - return nil - } - - case *types.Signature: - if actual, ok := actual.(*types.Signature); ok { - if err := CompatibleTypes(expected.Params(), actual.Params()); err != nil { - return err - } - if err := CompatibleTypes(expected.Results(), actual.Results()); err != nil { - return err - } - - return nil - } - case *types.Interface: - if actual, ok := actual.(*types.Interface); ok { - if expected.NumMethods() != actual.NumMethods() { - return fmt.Errorf("interface method count differs, %d != %d", expected.NumMethods(), actual.NumMethods()) - } - - for i := 0; i < expected.NumMethods(); i++ { - if expected.Method(i).Name() != actual.Method(i).Name() { - return fmt.Errorf("interface method %d name differs, %s != %s", i, expected.Method(i).Name(), actual.Method(i).Name()) - } - if err := CompatibleTypes(expected.Method(i).Type(), actual.Method(i).Type()); err != nil { - return err - } - } - - return nil - } - - case *types.Map: - if actual, ok := actual.(*types.Map); ok { - if err := CompatibleTypes(expected.Key(), actual.Key()); err != nil { - return err - } - - if err := CompatibleTypes(expected.Elem(), actual.Elem()); err != nil { - return err - } - - return nil - } - - case *types.Chan: - if actual, ok := actual.(*types.Chan); ok { - return CompatibleTypes(expected.Elem(), actual.Elem()) - } - - case *types.Named: - if actual, ok := actual.(*types.Named); ok { - if NormalizeVendor(expected.Obj().Pkg().Path()) != NormalizeVendor(actual.Obj().Pkg().Path()) { - return fmt.Errorf( - "package name of named type differs, %s != %s", - NormalizeVendor(expected.Obj().Pkg().Path()), - NormalizeVendor(actual.Obj().Pkg().Path()), - ) - } - - if expected.Obj().Name() != actual.Obj().Name() { - return fmt.Errorf( - "named type name differs, %s != %s", - NormalizeVendor(expected.Obj().Name()), - NormalizeVendor(actual.Obj().Name()), - ) - } - - return nil - } - - // Before models are generated all missing references will be Invalid Basic references. - // lets assume these are valid too. - if actual, ok := actual.(*types.Basic); ok && actual.Kind() == types.Invalid { - return nil - } - - default: - return fmt.Errorf("missing support for %T", expected) - } - - return fmt.Errorf("type mismatch %T != %T", expected, actual) -} diff --git a/vendor/github.com/99designs/gqlgen/internal/code/imports.go b/vendor/github.com/99designs/gqlgen/internal/code/imports.go deleted file mode 100644 index 0e499a171f..0000000000 --- a/vendor/github.com/99designs/gqlgen/internal/code/imports.go +++ /dev/null @@ -1,174 +0,0 @@ -package code - -import ( - "bufio" - "fmt" - "go/build" - "go/parser" - "go/token" - "os" - "path/filepath" - "regexp" - "strings" -) - -var gopaths []string - -func init() { - gopaths = filepath.SplitList(build.Default.GOPATH) - for i, p := range gopaths { - gopaths[i] = filepath.ToSlash(filepath.Join(p, "src")) - } -} - -// NameForDir manually looks for package stanzas in files located in the given directory. This can be -// much faster than having to consult go list, because we already know exactly where to look. -func NameForDir(dir string) string { - dir, err := filepath.Abs(dir) - if err != nil { - return SanitizePackageName(filepath.Base(dir)) - } - files, err := os.ReadDir(dir) - if err != nil { - return SanitizePackageName(filepath.Base(dir)) - } - fset := token.NewFileSet() - for _, file := range files { - if !strings.HasSuffix(strings.ToLower(file.Name()), ".go") { - continue - } - - filename := filepath.Join(dir, file.Name()) - if src, err := parser.ParseFile(fset, filename, nil, parser.PackageClauseOnly); err == nil { - return src.Name.Name - } - } - - return SanitizePackageName(filepath.Base(dir)) -} - -type goModuleSearchResult struct { - path string - goModPath string - moduleName string -} - -var goModuleRootCache = map[string]goModuleSearchResult{} - -// goModuleRoot returns the root of the current go module if there is a go.mod file in the directory tree -// If not, it returns false -func goModuleRoot(dir string) (string, bool) { - dir, err := filepath.Abs(dir) - if err != nil { - panic(err) - } - dir = filepath.ToSlash(dir) - - dirs := []string{dir} - result := goModuleSearchResult{} - - for { - modDir := dirs[len(dirs)-1] - - if val, ok := goModuleRootCache[dir]; ok { - result = val - break - } - - if content, err := os.ReadFile(filepath.Join(modDir, "go.mod")); err == nil { - moduleName := extractModuleName(content) - result = goModuleSearchResult{ - path: moduleName, - goModPath: modDir, - moduleName: moduleName, - } - goModuleRootCache[modDir] = result - break - } - - if modDir == "" || modDir == "." || modDir == "/" || strings.HasSuffix(modDir, "\\") { - // Reached the top of the file tree which means go.mod file is not found - // Set root folder with a sentinel cache value - goModuleRootCache[modDir] = result - break - } - - dirs = append(dirs, filepath.Dir(modDir)) - } - - // create a cache for each path in a tree traversed, except the top one as it is already cached - for _, d := range dirs[:len(dirs)-1] { - if result.moduleName == "" { - // go.mod is not found in the tree, so the same sentinel value fits all the directories in a tree - goModuleRootCache[d] = result - } else { - if relPath, err := filepath.Rel(result.goModPath, d); err != nil { - panic(err) - } else { - path := result.moduleName - relPath := filepath.ToSlash(relPath) - if !strings.HasSuffix(relPath, "/") { - path += "/" - } - path += relPath - - goModuleRootCache[d] = goModuleSearchResult{ - path: path, - goModPath: result.goModPath, - moduleName: result.moduleName, - } - } - } - } - - res := goModuleRootCache[dir] - if res.moduleName == "" { - return "", false - } - return res.path, true -} - -func extractModuleName(content []byte) string { - for { - advance, tkn, err := bufio.ScanLines(content, false) - if err != nil { - panic(fmt.Errorf("error parsing mod file: %w", err)) - } - if advance == 0 { - break - } - s := strings.Trim(string(tkn), " \t") - if len(s) != 0 && !strings.HasPrefix(s, "//") { - break - } - if advance <= len(content) { - content = content[advance:] - } - } - moduleName := string(modregex.FindSubmatch(content)[1]) - return moduleName -} - -// ImportPathForDir takes a path and returns a golang import path for the package -func ImportPathForDir(dir string) (res string) { - dir, err := filepath.Abs(dir) - if err != nil { - panic(err) - } - dir = filepath.ToSlash(dir) - - modDir, ok := goModuleRoot(dir) - if ok { - return modDir - } - - for _, gopath := range gopaths { - if len(gopath) < len(dir) && strings.EqualFold(gopath, dir[0:len(gopath)]) { - return dir[len(gopath)+1:] - } - } - - return "" -} - -var modregex = regexp.MustCompile(`module ([^\s]*)`) diff --git a/vendor/github.com/99designs/gqlgen/internal/code/packages.go b/vendor/github.com/99designs/gqlgen/internal/code/packages.go deleted file mode 100644 index c800d3d84f..0000000000 --- a/vendor/github.com/99designs/gqlgen/internal/code/packages.go +++ /dev/null @@ -1,223 +0,0 @@ -package code - -import ( - "bytes" - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - - "golang.org/x/tools/go/packages" -) - -var mode = packages.NeedName | - packages.NeedFiles | - packages.NeedImports | - packages.NeedTypes | - packages.NeedSyntax | - packages.NeedTypesInfo | - packages.NeedModule | - packages.NeedDeps - -// Packages is a wrapper around x/tools/go/packages that maintains a (hopefully prewarmed) cache of packages -// that can be invalidated as writes are made and packages are known to change. -type Packages struct { - packages map[string]*packages.Package - importToName map[string]string - loadErrors []error - - numLoadCalls int // stupid test steam. ignore. - numNameCalls int // stupid test steam. ignore. -} - -// ReloadAll will call LoadAll after clearing the package cache, so we can reload -// packages in the case that the packages have changed -func (p *Packages) ReloadAll(importPaths ...string) []*packages.Package { - p.packages = nil - return p.LoadAll(importPaths...) -} - -func (p *Packages) checkModuleLoaded(pkgs []*packages.Package) bool { - for i := range pkgs { - if pkgs[i] == nil || pkgs[i].Module == nil { - return false - } - } - return true -} - -// LoadAll will call packages.Load and return the package data for the given packages, -// but if the package already have been loaded it will return cached values instead. -func (p *Packages) LoadAll(importPaths ...string) []*packages.Package { - if p.packages == nil { - p.packages = map[string]*packages.Package{} - } - - missing := make([]string, 0, len(importPaths)) - for _, path := range importPaths { - if _, ok := p.packages[path]; ok { - continue - } - missing = append(missing, path) - } - - if len(missing) > 0 { - p.numLoadCalls++ - pkgs, err := packages.Load(&packages.Config{Mode: mode}, missing...) - - // Sometimes packages.Load not loaded the module info. Call it again to reload it. - if !p.checkModuleLoaded(pkgs) { - fmt.Println("reloading module info") - pkgs, err = packages.Load(&packages.Config{Mode: mode}, missing...) - } - - if err != nil { - p.loadErrors = append(p.loadErrors, err) - } - - for _, pkg := range pkgs { - p.addToCache(pkg) - } - } - - res := make([]*packages.Package, 0, len(importPaths)) - for _, path := range importPaths { - res = append(res, p.packages[NormalizeVendor(path)]) - } - return res -} - -func (p *Packages) addToCache(pkg *packages.Package) { - imp := NormalizeVendor(pkg.PkgPath) - p.packages[imp] = pkg - for _, imp := range pkg.Imports { - if _, found := p.packages[NormalizeVendor(imp.PkgPath)]; !found { - p.addToCache(imp) - } - } -} - -// Load works the same as LoadAll, except a single package at a time. -func (p *Packages) Load(importPath string) *packages.Package { - // Quick cache check first to avoid expensive allocations of LoadAll() - if p.packages != nil { - if pkg, ok := p.packages[importPath]; ok { - return pkg - } - } - - pkgs := p.LoadAll(importPath) - if len(pkgs) == 0 { - return nil - } - return pkgs[0] -} - -// LoadWithTypes tries a standard load, which may not have enough type info (TypesInfo== nil) available if the imported package is a -// second order dependency. Fortunately this doesnt happen very often, so we can just issue a load when we detect it. -func (p *Packages) LoadWithTypes(importPath string) *packages.Package { - pkg := p.Load(importPath) - if pkg == nil || pkg.TypesInfo == nil { - p.numLoadCalls++ - pkgs, err := packages.Load(&packages.Config{Mode: mode}, importPath) - if err != nil { - p.loadErrors = append(p.loadErrors, err) - return nil - } - p.addToCache(pkgs[0]) - pkg = pkgs[0] - } - return pkg -} - -// NameForPackage looks up the package name from the package stanza in the go files at the given import path. -func (p *Packages) NameForPackage(importPath string) string { - if importPath == "" { - panic(errors.New("import path can not be empty")) - } - if p.importToName == nil { - p.importToName = map[string]string{} - } - - importPath = NormalizeVendor(importPath) - - // if its in the name cache use it - if name := p.importToName[importPath]; name != "" { - return name - } - - // otherwise we might have already loaded the full package data for it cached - pkg := p.packages[importPath] - - if pkg == nil { - // otherwise do a name only lookup for it but dont put it in the package cache. - p.numNameCalls++ - pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedName}, importPath) - if err != nil { - p.loadErrors = append(p.loadErrors, err) - } else { - pkg = pkgs[0] - } - } - - if pkg == nil || pkg.Name == "" { - return SanitizePackageName(filepath.Base(importPath)) - } - - p.importToName[importPath] = pkg.Name - - return pkg.Name -} - -// Evict removes a given package import path from the cache, along with any packages that depend on it. Further calls -// to Load will fetch it from disk. -func (p *Packages) Evict(importPath string) { - delete(p.packages, importPath) - - for _, pkg := range p.packages { - for _, imported := range pkg.Imports { - if imported.PkgPath == importPath { - p.Evict(pkg.PkgPath) - } - } - } -} - -func (p *Packages) ModTidy() error { - p.packages = nil - tidyCmd := exec.Command("go", "mod", "tidy") - tidyCmd.Stdout = os.Stdout - tidyCmd.Stderr = os.Stdout - if err := tidyCmd.Run(); err != nil { - return fmt.Errorf("go mod tidy failed: %w", err) - } - return nil -} - -// Errors returns any errors that were returned by Load, either from the call itself or any of the loaded packages. -func (p *Packages) Errors() PkgErrors { - var res []error //nolint:prealloc - res = append(res, p.loadErrors...) - for _, pkg := range p.packages { - for _, err := range pkg.Errors { - res = append(res, err) - } - } - return res -} - -func (p *Packages) Count() int { - return len(p.packages) -} - -type PkgErrors []error - -func (p PkgErrors) Error() string { - var b bytes.Buffer - b.WriteString("packages.Load: ") - for _, e := range p { - b.WriteString(e.Error() + "\n") - } - return b.String() -} diff --git a/vendor/github.com/99designs/gqlgen/internal/code/util.go b/vendor/github.com/99designs/gqlgen/internal/code/util.go deleted file mode 100644 index cbe40858e2..0000000000 --- a/vendor/github.com/99designs/gqlgen/internal/code/util.go +++ /dev/null @@ -1,61 +0,0 @@ -package code - -import ( - "go/build" - "os" - "path/filepath" - "regexp" - "strings" -) - -// take a string in the form github.com/package/blah.Type and split it into package and type -func PkgAndType(name string) (string, string) { - parts := strings.Split(name, ".") - if len(parts) == 1 { - return "", name - } - - return strings.Join(parts[:len(parts)-1], "."), parts[len(parts)-1] -} - -var modsRegex = regexp.MustCompile(`^(\*|\[\])*`) - -// NormalizeVendor takes a qualified package path and turns it into normal one. -// eg . -// github.com/foo/vendor/github.com/99designs/gqlgen/graphql becomes -// github.com/99designs/gqlgen/graphql -func NormalizeVendor(pkg string) string { - modifiers := modsRegex.FindAllString(pkg, 1)[0] - pkg = strings.TrimPrefix(pkg, modifiers) - parts := strings.Split(pkg, "/vendor/") - return modifiers + parts[len(parts)-1] -} - -// QualifyPackagePath takes an import and fully qualifies it with a vendor dir, if one is required. -// eg . -// github.com/99designs/gqlgen/graphql becomes -// github.com/foo/vendor/github.com/99designs/gqlgen/graphql -// -// x/tools/packages only supports 'qualified package paths' so this will need to be done prior to calling it -// See https://github.com/golang/go/issues/30289 -func QualifyPackagePath(importPath string) string { - wd, _ := os.Getwd() - - // in go module mode, the import path doesn't need fixing - if _, ok := goModuleRoot(wd); ok { - return importPath - } - - pkg, err := build.Import(importPath, wd, 0) - if err != nil { - return importPath - } - - return pkg.ImportPath -} - -var invalidPackageNameChar = regexp.MustCompile(`[^\w]`) - -func SanitizePackageName(pkg string) string { - return invalidPackageNameChar.ReplaceAllLiteralString(filepath.Base(pkg), "_") -} diff --git a/vendor/github.com/99designs/gqlgen/internal/imports/prune.go b/vendor/github.com/99designs/gqlgen/internal/imports/prune.go deleted file mode 100644 index d42a415791..0000000000 --- a/vendor/github.com/99designs/gqlgen/internal/imports/prune.go +++ /dev/null @@ -1,100 +0,0 @@ -// Wrapper around x/tools/imports that only removes imports, never adds new ones. - -package imports - -import ( - "bytes" - "go/ast" - "go/parser" - "go/printer" - "go/token" - "strings" - - "github.com/99designs/gqlgen/internal/code" - - "golang.org/x/tools/go/ast/astutil" - "golang.org/x/tools/imports" -) - -type visitFn func(node ast.Node) - -func (fn visitFn) Visit(node ast.Node) ast.Visitor { - fn(node) - return fn -} - -// Prune removes any unused imports -func Prune(filename string, src []byte, packages *code.Packages) ([]byte, error) { - fset := token.NewFileSet() - - file, err := parser.ParseFile(fset, filename, src, parser.ParseComments|parser.AllErrors) - if err != nil { - return nil, err - } - - unused := getUnusedImports(file, packages) - for ipath, name := range unused { - astutil.DeleteNamedImport(fset, file, name, ipath) - } - printConfig := &printer.Config{Mode: printer.TabIndent, Tabwidth: 8} - - var buf bytes.Buffer - if err := printConfig.Fprint(&buf, fset, file); err != nil { - return nil, err - } - - return imports.Process(filename, buf.Bytes(), &imports.Options{FormatOnly: true, Comments: true, TabIndent: true, TabWidth: 8}) -} - -func getUnusedImports(file ast.Node, packages *code.Packages) map[string]string { - imported := map[string]*ast.ImportSpec{} - used := map[string]bool{} - - ast.Walk(visitFn(func(node ast.Node) { - if node == nil { - return - } - switch v := node.(type) { - case *ast.ImportSpec: - if v.Name != nil { - imported[v.Name.Name] = v - break - } - ipath := strings.Trim(v.Path.Value, `"`) - if ipath == "C" { - break - } - - local := packages.NameForPackage(ipath) - - imported[local] = v - case *ast.SelectorExpr: - xident, ok := v.X.(*ast.Ident) - if !ok { - break - } - if xident.Obj != nil { - // if the parser can resolve it, it's not a package ref - break - } - used[xident.Name] = true - } - }), file) - - for pkg := range used { - delete(imported, pkg) - } - - unusedImport := map[string]string{} - for pkg, is := range imported { - if !used[pkg] && pkg != "_" && pkg != "." { - name := "" - if is.Name != nil { - name = is.Name.Name - } - unusedImport[strings.Trim(is.Path.Value, `"`)] = name - } - } - - return unusedImport -} diff --git a/vendor/github.com/99designs/gqlgen/internal/rewrite/rewriter.go b/vendor/github.com/99designs/gqlgen/internal/rewrite/rewriter.go deleted file mode 100644 index a8a6485cff..0000000000 --- a/vendor/github.com/99designs/gqlgen/internal/rewrite/rewriter.go +++ /dev/null @@ -1,226 +0,0 @@ -package rewrite - -import ( - "bytes" - "fmt" - "go/ast" - "go/token" - "os" - "path/filepath" - "strconv" - "strings" - - "github.com/99designs/gqlgen/internal/code" - "golang.org/x/tools/go/packages" -) - -type Rewriter struct { - pkg *packages.Package - files map[string]string - copied map[ast.Decl]bool -} - -func New(dir string) (*Rewriter, error) { - importPath := code.ImportPathForDir(dir) - if importPath == "" { - return nil, fmt.Errorf("import path not found for directory: %q", dir) - } - pkgs, err := packages.Load(&packages.Config{ - Mode: packages.NeedSyntax | packages.NeedTypes, - }, importPath) - if err != nil { - return nil, err - } - if len(pkgs) == 0 { - return nil, fmt.Errorf("package not found for importPath: %s", importPath) - } - - return &Rewriter{ - pkg: pkgs[0], - files: map[string]string{}, - copied: map[ast.Decl]bool{}, - }, nil -} - -func (r *Rewriter) getSource(start, end token.Pos) string { - startPos := r.pkg.Fset.Position(start) - endPos := r.pkg.Fset.Position(end) - - if startPos.Filename != endPos.Filename { - panic("cant get source spanning multiple files") - } - - file := r.getFile(startPos.Filename) - return file[startPos.Offset:endPos.Offset] -} - -func (r *Rewriter) getFile(filename string) string { - if _, ok := r.files[filename]; !ok { - b, err := os.ReadFile(filename) - if err != nil { - panic(fmt.Errorf("unable to load file, already exists: %w", err)) - } - - r.files[filename] = string(b) - - } - - return r.files[filename] -} - -func (r *Rewriter) GetMethodComment(structname string, methodname string) string { - for _, f := range r.pkg.Syntax { - for _, d := range f.Decls { - d, isFunc := d.(*ast.FuncDecl) - if !isFunc { - continue - } - if d.Name.Name != methodname { - continue - } - if d.Recv == nil || len(d.Recv.List) == 0 { - continue - } - recv := d.Recv.List[0].Type - if star, isStar := recv.(*ast.StarExpr); isStar { - recv = star.X - } - ident, ok := recv.(*ast.Ident) - if !ok { - continue - } - - if ident.Name != structname { - continue - } - return d.Doc.Text() - } - } - - return "" -} -func (r *Rewriter) GetMethodBody(structname string, methodname string) string { - for _, f := range r.pkg.Syntax { - for _, d := range f.Decls { - d, isFunc := d.(*ast.FuncDecl) - if !isFunc { - continue - } - if d.Name.Name != methodname { - continue - } - if d.Recv == nil || len(d.Recv.List) == 0 { - continue - } - recv := d.Recv.List[0].Type - if star, isStar := recv.(*ast.StarExpr); isStar { - recv = star.X - } - ident, ok := recv.(*ast.Ident) - if !ok { - continue - } - - if ident.Name != structname { - continue - } - - r.copied[d] = true - - return r.getSource(d.Body.Pos()+1, d.Body.End()-1) - } - } - - return "" -} - -func (r *Rewriter) MarkStructCopied(name string) { - for _, f := range r.pkg.Syntax { - for _, d := range f.Decls { - d, isGen := d.(*ast.GenDecl) - if !isGen { - continue - } - if d.Tok != token.TYPE || len(d.Specs) == 0 { - continue - } - - spec, isTypeSpec := d.Specs[0].(*ast.TypeSpec) - if !isTypeSpec { - continue - } - - if spec.Name.Name != name { - continue - } - - r.copied[d] = true - } - } -} - -func (r *Rewriter) ExistingImports(filename string) []Import { - filename, err := filepath.Abs(filename) - if err != nil { - panic(err) - } - for _, f := range r.pkg.Syntax { - pos := r.pkg.Fset.Position(f.Pos()) - - if filename != pos.Filename { - continue - } - - var imps []Import - for _, i := range f.Imports { - name := "" - if i.Name != nil { - name = i.Name.Name - } - path, err := strconv.Unquote(i.Path.Value) - if err != nil { - panic(err) - } - imps = append(imps, Import{name, path}) - } - return imps - } - return nil -} - -func (r *Rewriter) RemainingSource(filename string) string { - filename, err := filepath.Abs(filename) - if err != nil { - panic(err) - } - for _, f := range r.pkg.Syntax { - pos := r.pkg.Fset.Position(f.Pos()) - - if filename != pos.Filename { - continue - } - - var buf bytes.Buffer - - for _, d := range f.Decls { - if r.copied[d] { - continue - } - - if d, isGen := d.(*ast.GenDecl); isGen && d.Tok == token.IMPORT { - continue - } - - buf.WriteString(r.getSource(d.Pos(), d.End())) - buf.WriteString("\n") - } - - return strings.TrimSpace(buf.String()) - } - return "" -} - -type Import struct { - Alias string - ImportPath string -} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/federation.go b/vendor/github.com/99designs/gqlgen/plugin/federation/federation.go deleted file mode 100644 index cd60acee25..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/federation/federation.go +++ /dev/null @@ -1,424 +0,0 @@ -package federation - -import ( - _ "embed" - "fmt" - "sort" - "strings" - - "github.com/vektah/gqlparser/v2/ast" - - "github.com/99designs/gqlgen/codegen" - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/codegen/templates" - "github.com/99designs/gqlgen/plugin" - "github.com/99designs/gqlgen/plugin/federation/fieldset" -) - -//go:embed federation.gotpl -var federationTemplate string - -type federation struct { - Entities []*Entity - Version int -} - -// New returns a federation plugin that injects -// federated directives and types into the schema -func New(version int) plugin.Plugin { - if version == 0 { - version = 1 - } - - return &federation{Version: version} -} - -// Name returns the plugin name -func (f *federation) Name() string { - return "federation" -} - -// MutateConfig mutates the configuration -func (f *federation) MutateConfig(cfg *config.Config) error { - builtins := config.TypeMap{ - "_Service": { - Model: config.StringList{ - "github.com/99designs/gqlgen/plugin/federation/fedruntime.Service", - }, - }, - "_Entity": { - Model: config.StringList{ - "github.com/99designs/gqlgen/plugin/federation/fedruntime.Entity", - }, - }, - "Entity": { - Model: config.StringList{ - "github.com/99designs/gqlgen/plugin/federation/fedruntime.Entity", - }, - }, - "_Any": { - Model: config.StringList{"github.com/99designs/gqlgen/graphql.Map"}, - }, - } - - for typeName, entry := range builtins { - if cfg.Models.Exists(typeName) { - return fmt.Errorf("%v already exists which must be reserved when Federation is enabled", typeName) - } - cfg.Models[typeName] = entry - } - cfg.Directives["external"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["requires"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["provides"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["key"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["extends"] = config.DirectiveConfig{SkipRuntime: true} - - // Federation 2 specific directives - if f.Version == 2 { - cfg.Directives["shareable"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["link"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["tag"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["override"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["inaccessible"] = config.DirectiveConfig{SkipRuntime: true} - } - - return nil -} - -func (f *federation) InjectSourceEarly() *ast.Source { - input := ` - scalar _Any - scalar _FieldSet - - directive @external on FIELD_DEFINITION - directive @requires(fields: _FieldSet!) on FIELD_DEFINITION - directive @provides(fields: _FieldSet!) on FIELD_DEFINITION - directive @extends on OBJECT | INTERFACE -` - // add version-specific changes on key directive, as well as adding the new directives for federation 2 - if f.Version == 1 { - input += ` - directive @key(fields: _FieldSet!) repeatable on OBJECT | INTERFACE -` - } else if f.Version == 2 { - input += ` - directive @key(fields: _FieldSet!, resolvable: Boolean = true) repeatable on OBJECT | INTERFACE - directive @link(import: [String!], url: String!) repeatable on SCHEMA - directive @shareable on OBJECT | FIELD_DEFINITION - directive @tag(name: String!) repeatable on FIELD_DEFINITION | INTERFACE | OBJECT | UNION | ARGUMENT_DEFINITION | SCALAR | ENUM | ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION - directive @override(from: String!) on FIELD_DEFINITION - directive @inaccessible on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | INTERFACE | UNION | ENUM | ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION -` - } - return &ast.Source{ - Name: "federation/directives.graphql", - Input: input, - BuiltIn: true, - } -} - -// InjectSources creates a GraphQL Entity type with all -// the fields that had the @key directive -func (f *federation) InjectSourceLate(schema *ast.Schema) *ast.Source { - f.setEntities(schema) - - var entities, resolvers, entityResolverInputDefinitions string - for i, e := range f.Entities { - if i != 0 { - entities += " | " - } - entities += e.Name - - for _, r := range e.Resolvers { - if e.Multi { - if entityResolverInputDefinitions != "" { - entityResolverInputDefinitions += "\n\n" - } - entityResolverInputDefinitions += "input " + r.InputType + " {\n" - for _, keyField := range r.KeyFields { - entityResolverInputDefinitions += fmt.Sprintf("\t%s: %s\n", keyField.Field.ToGo(), keyField.Definition.Type.String()) - } - entityResolverInputDefinitions += "}" - resolvers += fmt.Sprintf("\t%s(reps: [%s!]!): [%s]\n", r.ResolverName, r.InputType, e.Name) - } else { - resolverArgs := "" - for _, keyField := range r.KeyFields { - resolverArgs += fmt.Sprintf("%s: %s,", keyField.Field.ToGoPrivate(), keyField.Definition.Type.String()) - } - resolvers += fmt.Sprintf("\t%s(%s): %s!\n", r.ResolverName, resolverArgs, e.Name) - } - } - } - - var blocks []string - if entities != "" { - entities = `# a union of all types that use the @key directive -union _Entity = ` + entities - blocks = append(blocks, entities) - } - - // resolvers can be empty if a service defines only "empty - // extend" types. This should be rare. - if resolvers != "" { - if entityResolverInputDefinitions != "" { - blocks = append(blocks, entityResolverInputDefinitions) - } - resolvers = `# fake type to build resolver interfaces for users to implement -type Entity { - ` + resolvers + ` -}` - blocks = append(blocks, resolvers) - } - - _serviceTypeDef := `type _Service { - sdl: String -}` - blocks = append(blocks, _serviceTypeDef) - - var additionalQueryFields string - // Quote from the Apollo Federation subgraph specification: - // If no types are annotated with the key directive, then the - // _Entity union and _entities field should be removed from the schema - if len(f.Entities) > 0 { - additionalQueryFields += ` _entities(representations: [_Any!]!): [_Entity]! -` - } - // _service field is required in any case - additionalQueryFields += ` _service: _Service!` - - extendTypeQueryDef := `extend type ` + schema.Query.Name + ` { -` + additionalQueryFields + ` -}` - blocks = append(blocks, extendTypeQueryDef) - - return &ast.Source{ - Name: "federation/entity.graphql", - BuiltIn: true, - Input: "\n" + strings.Join(blocks, "\n\n") + "\n", - } -} - -// Entity represents a federated type -// that was declared in the GQL schema. -type Entity struct { - Name string // The same name as the type declaration - Def *ast.Definition - Resolvers []*EntityResolver - Requires []*Requires - Multi bool -} - -type EntityResolver struct { - ResolverName string // The resolver name, such as FindUserByID - KeyFields []*KeyField // The fields declared in @key. - InputType string // The Go generated input type for multi entity resolvers -} - -type KeyField struct { - Definition *ast.FieldDefinition - Field fieldset.Field // len > 1 for nested fields - Type *config.TypeReference // The Go representation of that field type -} - -// Requires represents an @requires clause -type Requires struct { - Name string // the name of the field - Field fieldset.Field // source Field, len > 1 for nested fields - Type *config.TypeReference // The Go representation of that field type -} - -func (e *Entity) allFieldsAreExternal() bool { - for _, field := range e.Def.Fields { - if field.Directives.ForName("external") == nil { - return false - } - } - return true -} - -func (f *federation) GenerateCode(data *codegen.Data) error { - if len(f.Entities) > 0 { - if data.Objects.ByName("Entity") != nil { - data.Objects.ByName("Entity").Root = true - } - for _, e := range f.Entities { - obj := data.Objects.ByName(e.Def.Name) - - for _, r := range e.Resolvers { - // fill in types for key fields - // - for _, keyField := range r.KeyFields { - if len(keyField.Field) == 0 { - fmt.Println( - "skipping @key field " + keyField.Definition.Name + " in " + r.ResolverName + " in " + e.Def.Name, - ) - continue - } - cgField := keyField.Field.TypeReference(obj, data.Objects) - keyField.Type = cgField.TypeReference - } - } - - // fill in types for requires fields - // - for _, reqField := range e.Requires { - if len(reqField.Field) == 0 { - fmt.Println("skipping @requires field " + reqField.Name + " in " + e.Def.Name) - continue - } - cgField := reqField.Field.TypeReference(obj, data.Objects) - reqField.Type = cgField.TypeReference - } - } - } - - return templates.Render(templates.Options{ - PackageName: data.Config.Federation.Package, - Filename: data.Config.Federation.Filename, - Data: f, - GeneratedHeader: true, - Packages: data.Config.Packages, - Template: federationTemplate, - }) -} - -func (f *federation) setEntities(schema *ast.Schema) { - for _, schemaType := range schema.Types { - keys, ok := isFederatedEntity(schemaType) - if !ok { - continue - } - e := &Entity{ - Name: schemaType.Name, - Def: schemaType, - Resolvers: nil, - Requires: nil, - } - - // Let's process custom entity resolver settings. - dir := schemaType.Directives.ForName("entityResolver") - if dir != nil { - if dirArg := dir.Arguments.ForName("multi"); dirArg != nil { - if dirVal, err := dirArg.Value.Value(nil); err == nil { - e.Multi = dirVal.(bool) - } - } - } - - // If our schema has a field with a type defined in - // another service, then we need to define an "empty - // extend" of that type in this service, so this service - // knows what the type is like. But the graphql-server - // will never ask us to actually resolve this "empty - // extend", so we don't require a resolver function for - // it. (Well, it will never ask in practice; it's - // unclear whether the spec guarantees this. See - // https://github.com/apollographql/apollo-server/issues/3852 - // ). Example: - // type MyType { - // myvar: TypeDefinedInOtherService - // } - // // Federation needs this type, but - // // it doesn't need a resolver for it! - // extend TypeDefinedInOtherService @key(fields: "id") { - // id: ID @external - // } - if !e.allFieldsAreExternal() { - for _, dir := range keys { - if len(dir.Arguments) > 2 { - panic("More than two arguments provided for @key declaration.") - } - var arg *ast.Argument - - // since keys are able to now have multiple arguments, we need to check both possible for a possible @key(fields="" fields="") - for _, a := range dir.Arguments { - if a.Name == "fields" { - if arg != nil { - panic("More than one `fields` provided for @key declaration.") - } - arg = a - } - } - - keyFieldSet := fieldset.New(arg.Value.Raw, nil) - - keyFields := make([]*KeyField, len(keyFieldSet)) - resolverFields := []string{} - for i, field := range keyFieldSet { - def := field.FieldDefinition(schemaType, schema) - - if def == nil { - panic(fmt.Sprintf("no field for %v", field)) - } - - keyFields[i] = &KeyField{Definition: def, Field: field} - resolverFields = append(resolverFields, keyFields[i].Field.ToGo()) - } - - resolverFieldsToGo := schemaType.Name + "By" + strings.Join(resolverFields, "And") - var resolverName string - if e.Multi { - resolverFieldsToGo += "s" // Pluralize for better API readability - resolverName = fmt.Sprintf("findMany%s", resolverFieldsToGo) - } else { - resolverName = fmt.Sprintf("find%s", resolverFieldsToGo) - } - - e.Resolvers = append(e.Resolvers, &EntityResolver{ - ResolverName: resolverName, - KeyFields: keyFields, - InputType: resolverFieldsToGo + "Input", - }) - } - - e.Requires = []*Requires{} - for _, f := range schemaType.Fields { - dir := f.Directives.ForName("requires") - if dir == nil { - continue - } - if len(dir.Arguments) != 1 || dir.Arguments[0].Name != "fields" { - panic("Exactly one `fields` argument needed for @requires declaration.") - } - requiresFieldSet := fieldset.New(dir.Arguments[0].Value.Raw, nil) - for _, field := range requiresFieldSet { - e.Requires = append(e.Requires, &Requires{ - Name: field.ToGoPrivate(), - Field: field, - }) - } - } - } - f.Entities = append(f.Entities, e) - } - - // make sure order remains stable across multiple builds - sort.Slice(f.Entities, func(i, j int) bool { - return f.Entities[i].Name < f.Entities[j].Name - }) -} - -func isFederatedEntity(schemaType *ast.Definition) ([]*ast.Directive, bool) { - switch schemaType.Kind { - case ast.Object: - keys := schemaType.Directives.ForNames("key") - if len(keys) > 0 { - return keys, true - } - case ast.Interface: - // TODO: support @key and @extends for interfaces - if dir := schemaType.Directives.ForName("key"); dir != nil { - fmt.Printf("@key directive found on \"interface %s\". Will be ignored.\n", schemaType.Name) - } - if dir := schemaType.Directives.ForName("extends"); dir != nil { - panic( - fmt.Sprintf( - "@extends directive is not currently supported for interfaces, use \"extend interface %s\" instead.", - schemaType.Name, - )) - } - default: - // ignore - } - return nil, false -} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/federation.gotpl b/vendor/github.com/99designs/gqlgen/plugin/federation/federation.gotpl deleted file mode 100644 index 4a30b6c978..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/federation/federation.gotpl +++ /dev/null @@ -1,259 +0,0 @@ -{{ reserveImport "context" }} -{{ reserveImport "errors" }} -{{ reserveImport "fmt" }} -{{ reserveImport "strings" }} -{{ reserveImport "sync" }} - -{{ reserveImport "github.com/99designs/gqlgen/plugin/federation/fedruntime" }} - -var ( - ErrUnknownType = errors.New("unknown type") - ErrTypeNotFound = errors.New("type not found") -) - -func (ec *executionContext) __resolve__service(ctx context.Context) (fedruntime.Service, error) { - if ec.DisableIntrospection { - return fedruntime.Service{}, errors.New("federated introspection disabled") - } - - var sdl []string - - for _, src := range sources { - if src.BuiltIn { - continue - } - sdl = append(sdl, src.Input) - } - - return fedruntime.Service{ - SDL: strings.Join(sdl, "\n"), - }, nil -} - -{{if .Entities}} -func (ec *executionContext) __resolve_entities(ctx context.Context, representations []map[string]interface{}) []fedruntime.Entity { - list := make([]fedruntime.Entity, len(representations)) - - repsMap := map[string]struct { - i []int - r []map[string]interface{} - }{} - - // We group entities by typename so that we can parallelize their resolution. - // This is particularly helpful when there are entity groups in multi mode. - buildRepresentationGroups := func(reps []map[string]interface{}) { - for i, rep := range reps { - typeName, ok := rep["__typename"].(string) - if !ok { - // If there is no __typename, we just skip the representation; - // we just won't be resolving these unknown types. - ec.Error(ctx, errors.New("__typename must be an existing string")) - continue - } - - _r := repsMap[typeName] - _r.i = append(_r.i, i) - _r.r = append(_r.r, rep) - repsMap[typeName] = _r - } - } - - isMulti := func(typeName string) bool { - switch typeName { - {{- range .Entities -}} - {{- if .Resolvers -}} - {{- if .Multi -}} - case "{{.Def.Name}}": - return true - {{ end }} - {{- end -}} - {{- end -}} - default: - return false - } - } - - resolveEntity := func(ctx context.Context, typeName string, rep map[string]interface{}, idx []int, i int) (err error) { - // we need to do our own panic handling, because we may be called in a - // goroutine, where the usual panic handling can't catch us - defer func () { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - } - }() - - switch typeName { - {{ range $_, $entity := .Entities }} - {{- if and .Resolvers (not .Multi) -}} - case "{{.Def.Name}}": - resolverName, err := entityResolverNameFor{{.Def.Name}}(ctx, rep) - if err != nil { - return fmt.Errorf(`finding resolver for Entity "{{.Def.Name}}": %w`, err) - } - switch resolverName { - {{ range $i, $resolver := .Resolvers }} - case "{{.ResolverName}}": - {{- range $j, $keyField := .KeyFields }} - id{{$j}}, err := ec.{{.Type.UnmarshalFunc}}(ctx, rep["{{.Field.Join `"].(map[string]interface{})["`}}"]) - if err != nil { - return fmt.Errorf(`unmarshalling param {{$j}} for {{$resolver.ResolverName}}(): %w`, err) - } - {{- end}} - entity, err := ec.resolvers.Entity().{{.ResolverName | go}}(ctx, {{- range $j, $_ := .KeyFields -}} id{{$j}}, {{end}}) - if err != nil { - return fmt.Errorf(`resolving Entity "{{$entity.Def.Name}}": %w`, err) - } - {{ range $entity.Requires }} - entity.{{.Field.JoinGo `.`}}, err = ec.{{.Type.UnmarshalFunc}}(ctx, rep["{{.Field.Join `"].(map[string]interface{})["`}}"]) - if err != nil { - return err - } - {{- end }} - list[idx[i]] = entity - return nil - {{- end }} - } - {{ end }} - {{- end }} - } - return fmt.Errorf("%w: %s", ErrUnknownType, typeName) - } - - resolveManyEntities := func(ctx context.Context, typeName string, reps []map[string]interface{}, idx []int) (err error) { - // we need to do our own panic handling, because we may be called in a - // goroutine, where the usual panic handling can't catch us - defer func () { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - } - }() - - switch typeName { - {{ range $_, $entity := .Entities }} - {{ if and .Resolvers .Multi -}} - case "{{.Def.Name}}": - {{range $i, $_ := .Resolvers -}} - _reps := make([]*{{.InputType}}, len(reps)) - - for i, rep := range reps { - {{ range $i, $keyField := .KeyFields -}} - id{{$i}}, err := ec.{{.Type.UnmarshalFunc}}(ctx, rep["{{.Field.Join `"].(map[string]interface{})["`}}"]) - if err != nil { - return errors.New(fmt.Sprintf("Field %s undefined in schema.", "{{.Definition.Name}}")) - } - {{end}} - - _reps[i] = &{{.InputType}} { - {{ range $i, $keyField := .KeyFields -}} - {{$keyField.Field.ToGo}}: id{{$i}}, - {{end}} - } - } - - entities, err := ec.resolvers.Entity().{{.ResolverName | go}}(ctx, _reps) - if err != nil { - return err - } - - for i, entity := range entities { - {{- range $entity.Requires }} - entity.{{.Field.JoinGo `.`}}, err = ec.{{.Type.UnmarshalFunc}}(ctx, reps[i]["{{.Field.Join `"].(map[string]interface{})["`}}"]) - if err != nil { - return err - } - {{- end}} - list[idx[i]] = entity - } - return nil - {{ end }} - {{ end }} - {{- end }} - default: - return errors.New("unknown type: "+typeName) - } - } - - resolveEntityGroup := func(typeName string, reps []map[string]interface{}, idx []int) { - if isMulti(typeName) { - err := resolveManyEntities(ctx, typeName, reps, idx) - if err != nil { - ec.Error(ctx, err) - } - } else { - // if there are multiple entities to resolve, parallelize (similar to - // graphql.FieldSet.Dispatch) - var e sync.WaitGroup - e.Add(len(reps)) - for i, rep := range reps { - i, rep := i, rep - go func(i int, rep map[string]interface{}) { - err := resolveEntity(ctx, typeName, rep, idx, i) - if err != nil { - ec.Error(ctx, err) - } - e.Done() - }(i, rep) - } - e.Wait() - } - } - buildRepresentationGroups(representations) - - switch len(repsMap) { - case 0: - return list - case 1: - for typeName, reps := range repsMap { - resolveEntityGroup(typeName, reps.r, reps.i) - } - return list - default: - var g sync.WaitGroup - g.Add(len(repsMap)) - for typeName, reps := range repsMap { - go func(typeName string, reps []map[string]interface{}, idx []int) { - resolveEntityGroup(typeName, reps, idx) - g.Done() - }(typeName, reps.r, reps.i) - } - g.Wait() - return list - } -} - -{{- /* Make sure the required fields are in the given entity representation and return the name of the proper resolver. */ -}} - -{{ range $_, $entity := .Entities }} - {{- if .Resolvers }} - - func entityResolverNameFor{{$entity.Name}}(ctx context.Context, rep map[string]interface{}) (string, error) { - {{- range .Resolvers }} - for { - var ( - m map[string]interface{} - val interface{} - ok bool - ) - _ = val - {{- range $_, $keyField := .KeyFields }} - m = rep - {{- range $i, $field := .Field }} - if {{ if (ne $i $keyField.Field.LastIndex ) -}}val{{- else -}}_{{- end -}}, ok = m["{{.}}"]; !ok { - break - } - {{- if (ne $i $keyField.Field.LastIndex ) }} - if m, ok = val.(map[string]interface{}); !ok { - break - } - {{- end}} - {{- end}} - {{- end }} - return "{{.ResolverName}}", nil - } - {{- end }} - return "", fmt.Errorf("%w for {{$entity.Name}}", ErrTypeNotFound) - } - {{- end }} -{{- end }} - -{{end}} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/fieldset/fieldset.go b/vendor/github.com/99designs/gqlgen/plugin/federation/fieldset/fieldset.go deleted file mode 100644 index 059a3c8325..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/federation/fieldset/fieldset.go +++ /dev/null @@ -1,181 +0,0 @@ -package fieldset - -import ( - "fmt" - "strings" - - "github.com/99designs/gqlgen/codegen" - "github.com/99designs/gqlgen/codegen/templates" - "github.com/vektah/gqlparser/v2/ast" -) - -// Set represents a FieldSet that is used in federation directives @key and @requires. -// Would be happier to reuse FieldSet parsing from gqlparser, but this suits for now. -type Set []Field - -// Field represents a single field in a FieldSet -type Field []string - -// New parses a FieldSet string into a TinyFieldSet. -func New(raw string, prefix []string) Set { - if !strings.Contains(raw, "{") { - return parseUnnestedKeyFieldSet(raw, prefix) - } - - var ( - ret = Set{} - subPrefix = prefix - ) - before, during, after := extractSubs(raw) - - if before != "" { - befores := New(before, prefix) - if len(befores) > 0 { - subPrefix = befores[len(befores)-1] - ret = append(ret, befores[:len(befores)-1]...) - } - } - if during != "" { - ret = append(ret, New(during, subPrefix)...) - } - if after != "" { - ret = append(ret, New(after, prefix)...) - } - return ret -} - -// FieldDefinition looks up a field in the type. -func (f Field) FieldDefinition(schemaType *ast.Definition, schema *ast.Schema) *ast.FieldDefinition { - objType := schemaType - def := objType.Fields.ForName(f[0]) - - for _, part := range f[1:] { - if objType.Kind != ast.Object { - panic(fmt.Sprintf(`invalid sub-field reference "%s" in %v: `, objType.Name, f)) - } - x := def.Type.Name() - objType = schema.Types[x] - if objType == nil { - panic("invalid schema type: " + x) - } - def = objType.Fields.ForName(part) - } - if def == nil { - return nil - } - ret := *def // shallow copy - ret.Name = f.ToGoPrivate() - - return &ret -} - -// TypeReference looks up the type of a field. -func (f Field) TypeReference(obj *codegen.Object, objects codegen.Objects) *codegen.Field { - var def *codegen.Field - - for _, part := range f { - def = fieldByName(obj, part) - if def == nil { - panic("unable to find field " + f[0]) - } - obj = objects.ByName(def.TypeReference.Definition.Name) - } - return def -} - -// ToGo converts a (possibly nested) field into a proper public Go name. -func (f Field) ToGo() string { - var ret string - - for _, field := range f { - ret += templates.ToGo(field) - } - return ret -} - -// ToGoPrivate converts a (possibly nested) field into a proper private Go name. -func (f Field) ToGoPrivate() string { - var ret string - - for i, field := range f { - if i == 0 { - ret += templates.ToGoPrivate(field) - continue - } - ret += templates.ToGo(field) - } - return ret -} - -// Join concatenates the field parts with a string separator between. Useful in templates. -func (f Field) Join(str string) string { - return strings.Join(f, str) -} - -// JoinGo concatenates the Go name of field parts with a string separator between. Useful in templates. -func (f Field) JoinGo(str string) string { - strs := []string{} - - for _, s := range f { - strs = append(strs, templates.ToGo(s)) - } - return strings.Join(strs, str) -} - -func (f Field) LastIndex() int { - return len(f) - 1 -} - -// local functions - -// parseUnnestedKeyFieldSet // handles simple case where none of the fields are nested. -func parseUnnestedKeyFieldSet(raw string, prefix []string) Set { - ret := Set{} - - for _, s := range strings.Fields(raw) { - next := append(prefix[:], s) //nolint:gocritic // slicing out on purpose - ret = append(ret, next) - } - return ret -} - -// extractSubs splits out and trims sub-expressions from before, inside, and after "{}". -func extractSubs(str string) (string, string, string) { - start := strings.Index(str, "{") - end := matchingBracketIndex(str, start) - - if start < 0 || end < 0 { - panic("invalid key fieldSet: " + str) - } - return strings.TrimSpace(str[:start]), strings.TrimSpace(str[start+1 : end]), strings.TrimSpace(str[end+1:]) -} - -// matchingBracketIndex returns the index of the closing bracket, assuming an open bracket at start. -func matchingBracketIndex(str string, start int) int { - if start < 0 || len(str) <= start+1 { - return -1 - } - var depth int - - for i, c := range str[start+1:] { - switch c { - case '{': - depth++ - case '}': - if depth == 0 { - return start + 1 + i - } - depth-- - } - } - return -1 -} - -func fieldByName(obj *codegen.Object, name string) *codegen.Field { - for _, field := range obj.Fields { - if field.Name == name { - return field - } - } - return nil -} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/readme.md b/vendor/github.com/99designs/gqlgen/plugin/federation/readme.md deleted file mode 100644 index 4333ed4797..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/federation/readme.md +++ /dev/null @@ -1,39 +0,0 @@ -# Federation plugin - -Add support for graphql federation in your graphql Go server! - -TODO(miguel): add details. - -# Tests -There are several different tests. Some will process the configuration file directly. You can see those in the `federation_test.go`. There are also tests for entity resolvers, which will simulate requests from a federation server like Apollo Federation. - -Running entity resolver tests. -1. Go to `plugin/federation` -2. Run the command `go generate` -3. Run the tests with `go test ./...`. - -# Architecture - -TODO(miguel): add details. - -# Entity resolvers - GetMany entities - -The federation plugin implements `GetMany` semantics in which entity resolvers get the entire list of representations that need to be resolved. This functionality is currently optin tho, and to enable it you need to specify the directive `@entityResolver` in the federated entity you want this feature for. E.g. - -``` -directive @entityResolver(multi: Boolean) on OBJECT - -type MultiHello @key(fields: "name") @entityResolver(multi: true) { - name: String! -} -``` - -That allows the federation plugin to generate `GetMany` resolver function that can take a list of representations to be resolved. - -From that entity type, the resolver function would be - -``` -func (r *entityResolver) FindManyMultiHellosByName(ctx context.Context, reps []*generated.ManyMultiHellosByNameInput) ([]*generated.MultiHello, error) { - /// -} -``` diff --git a/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.go b/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.go deleted file mode 100644 index 45c32715c6..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.go +++ /dev/null @@ -1,470 +0,0 @@ -package modelgen - -import ( - _ "embed" - "fmt" - "go/types" - "sort" - "strings" - "text/template" - - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/codegen/templates" - "github.com/99designs/gqlgen/plugin" - "github.com/vektah/gqlparser/v2/ast" -) - -//go:embed models.gotpl -var modelTemplate string - -type BuildMutateHook = func(b *ModelBuild) *ModelBuild - -type FieldMutateHook = func(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) - -// defaultFieldMutateHook is the default hook for the Plugin which applies the GoTagFieldHook. -func defaultFieldMutateHook(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) { - return GoTagFieldHook(td, fd, f) -} - -func defaultBuildMutateHook(b *ModelBuild) *ModelBuild { - return b -} - -type ModelBuild struct { - PackageName string - Interfaces []*Interface - Models []*Object - Enums []*Enum - Scalars []string -} - -type Interface struct { - Description string - Name string - Fields []*Field - Implements []string -} - -type Object struct { - Description string - Name string - Fields []*Field - Implements []string -} - -type Field struct { - Description string - // Name is the field's name as it appears in the schema - Name string - // GoName is the field's name as it appears in the generated Go code - GoName string - Type types.Type - Tag string -} - -type Enum struct { - Description string - Name string - Values []*EnumValue -} - -type EnumValue struct { - Description string - Name string -} - -func New() plugin.Plugin { - return &Plugin{ - MutateHook: defaultBuildMutateHook, - FieldHook: defaultFieldMutateHook, - } -} - -type Plugin struct { - MutateHook BuildMutateHook - FieldHook FieldMutateHook -} - -var _ plugin.ConfigMutator = &Plugin{} - -func (m *Plugin) Name() string { - return "modelgen" -} - -func (m *Plugin) MutateConfig(cfg *config.Config) error { - - b := &ModelBuild{ - PackageName: cfg.Model.Package, - } - - for _, schemaType := range cfg.Schema.Types { - if cfg.Models.UserDefined(schemaType.Name) { - continue - } - switch schemaType.Kind { - case ast.Interface, ast.Union: - var fields []*Field - var err error - if !cfg.OmitGetters { - fields, err = m.generateFields(cfg, schemaType) - if err != nil { - return err - } - } - - it := &Interface{ - Description: schemaType.Description, - Name: schemaType.Name, - Implements: schemaType.Interfaces, - Fields: fields, - } - - b.Interfaces = append(b.Interfaces, it) - case ast.Object, ast.InputObject: - if schemaType == cfg.Schema.Query || schemaType == cfg.Schema.Mutation || schemaType == cfg.Schema.Subscription { - continue - } - - fields, err := m.generateFields(cfg, schemaType) - if err != nil { - return err - } - - it := &Object{ - Description: schemaType.Description, - Name: schemaType.Name, - Fields: fields, - } - - // If Interface A implements interface B, and Interface C also implements interface B - // then both A and C have methods of B. - // The reason for checking unique is to prevent the same method B from being generated twice. - uniqueMap := map[string]bool{} - for _, implementor := range cfg.Schema.GetImplements(schemaType) { - if !uniqueMap[implementor.Name] { - it.Implements = append(it.Implements, implementor.Name) - uniqueMap[implementor.Name] = true - } - // for interface implements - for _, iface := range implementor.Interfaces { - if !uniqueMap[iface] { - it.Implements = append(it.Implements, iface) - uniqueMap[iface] = true - } - } - } - - b.Models = append(b.Models, it) - case ast.Enum: - it := &Enum{ - Name: schemaType.Name, - Description: schemaType.Description, - } - - for _, v := range schemaType.EnumValues { - it.Values = append(it.Values, &EnumValue{ - Name: v.Name, - Description: v.Description, - }) - } - - b.Enums = append(b.Enums, it) - case ast.Scalar: - b.Scalars = append(b.Scalars, schemaType.Name) - } - } - sort.Slice(b.Enums, func(i, j int) bool { return b.Enums[i].Name < b.Enums[j].Name }) - sort.Slice(b.Models, func(i, j int) bool { return b.Models[i].Name < b.Models[j].Name }) - sort.Slice(b.Interfaces, func(i, j int) bool { return b.Interfaces[i].Name < b.Interfaces[j].Name }) - - // if we are not just turning all struct-type fields in generated structs into pointers, we need to at least - // check for cyclical relationships and recursive structs - if !cfg.StructFieldsAlwaysPointers { - findAndHandleCyclicalRelationships(b) - } - - for _, it := range b.Enums { - cfg.Models.Add(it.Name, cfg.Model.ImportPath()+"."+templates.ToGo(it.Name)) - } - for _, it := range b.Models { - cfg.Models.Add(it.Name, cfg.Model.ImportPath()+"."+templates.ToGo(it.Name)) - } - for _, it := range b.Interfaces { - cfg.Models.Add(it.Name, cfg.Model.ImportPath()+"."+templates.ToGo(it.Name)) - } - for _, it := range b.Scalars { - cfg.Models.Add(it, "github.com/99designs/gqlgen/graphql.String") - } - - if len(b.Models) == 0 && len(b.Enums) == 0 && len(b.Interfaces) == 0 && len(b.Scalars) == 0 { - return nil - } - - if m.MutateHook != nil { - b = m.MutateHook(b) - } - - getInterfaceByName := func(name string) *Interface { - // Allow looking up interfaces, so template can generate getters for each field - for _, i := range b.Interfaces { - if i.Name == name { - return i - } - } - - return nil - } - gettersGenerated := make(map[string]map[string]struct{}) - generateGetter := func(model *Object, field *Field) string { - if model == nil || field == nil { - return "" - } - - // Let templates check if a given getter has been generated already - typeGetters, exists := gettersGenerated[model.Name] - if !exists { - typeGetters = make(map[string]struct{}) - gettersGenerated[model.Name] = typeGetters - } - - _, exists = typeGetters[field.GoName] - typeGetters[field.GoName] = struct{}{} - if exists { - return "" - } - - _, interfaceFieldTypeIsPointer := field.Type.(*types.Pointer) - var structFieldTypeIsPointer bool - for _, f := range model.Fields { - if f.GoName == field.GoName { - _, structFieldTypeIsPointer = f.Type.(*types.Pointer) - break - } - } - goType := templates.CurrentImports.LookupType(field.Type) - if strings.HasPrefix(goType, "[]") { - getter := fmt.Sprintf("func (this %s) Get%s() %s {\n", templates.ToGo(model.Name), field.GoName, goType) - getter += fmt.Sprintf("\tif this.%s == nil { return nil }\n", field.GoName) - getter += fmt.Sprintf("\tinterfaceSlice := make(%s, 0, len(this.%s))\n", goType, field.GoName) - getter += fmt.Sprintf("\tfor _, concrete := range this.%s { interfaceSlice = append(interfaceSlice, ", field.GoName) - if interfaceFieldTypeIsPointer && !structFieldTypeIsPointer { - getter += "&" - } else if !interfaceFieldTypeIsPointer && structFieldTypeIsPointer { - getter += "*" - } - getter += "concrete) }\n" - getter += "\treturn interfaceSlice\n" - getter += "}" - return getter - } else { - getter := fmt.Sprintf("func (this %s) Get%s() %s { return ", templates.ToGo(model.Name), field.GoName, goType) - - if interfaceFieldTypeIsPointer && !structFieldTypeIsPointer { - getter += "&" - } else if !interfaceFieldTypeIsPointer && structFieldTypeIsPointer { - getter += "*" - } - - getter += fmt.Sprintf("this.%s }", field.GoName) - return getter - } - } - funcMap := template.FuncMap{ - "getInterfaceByName": getInterfaceByName, - "generateGetter": generateGetter, - } - - err := templates.Render(templates.Options{ - PackageName: cfg.Model.Package, - Filename: cfg.Model.Filename, - Data: b, - GeneratedHeader: true, - Packages: cfg.Packages, - Template: modelTemplate, - Funcs: funcMap, - }) - if err != nil { - return err - } - - // We may have generated code in a package we already loaded, so we reload all packages - // to allow packages to be compared correctly - cfg.ReloadAllPackages() - - return nil -} - -func (m *Plugin) generateFields(cfg *config.Config, schemaType *ast.Definition) ([]*Field, error) { - binder := cfg.NewBinder() - fields := make([]*Field, 0) - - for _, field := range schemaType.Fields { - var typ types.Type - fieldDef := cfg.Schema.Types[field.Type.Name()] - - if cfg.Models.UserDefined(field.Type.Name()) { - var err error - typ, err = binder.FindTypeFromName(cfg.Models[field.Type.Name()].Model[0]) - if err != nil { - return nil, err - } - } else { - switch fieldDef.Kind { - case ast.Scalar: - // no user defined model, referencing a default scalar - typ = types.NewNamed( - types.NewTypeName(0, cfg.Model.Pkg(), "string", nil), - nil, - nil, - ) - - case ast.Interface, ast.Union: - // no user defined model, referencing a generated interface type - typ = types.NewNamed( - types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), - types.NewInterfaceType([]*types.Func{}, []types.Type{}), - nil, - ) - - case ast.Enum: - // no user defined model, must reference a generated enum - typ = types.NewNamed( - types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), - nil, - nil, - ) - - case ast.Object, ast.InputObject: - // no user defined model, must reference a generated struct - typ = types.NewNamed( - types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), - types.NewStruct(nil, nil), - nil, - ) - - default: - panic(fmt.Errorf("unknown ast type %s", fieldDef.Kind)) - } - } - - name := templates.ToGo(field.Name) - if nameOveride := cfg.Models[schemaType.Name].Fields[field.Name].FieldName; nameOveride != "" { - name = nameOveride - } - - typ = binder.CopyModifiersFromAst(field.Type, typ) - - if cfg.StructFieldsAlwaysPointers { - if isStruct(typ) && (fieldDef.Kind == ast.Object || fieldDef.Kind == ast.InputObject) { - typ = types.NewPointer(typ) - } - } - - f := &Field{ - Name: field.Name, - GoName: name, - Type: typ, - Description: field.Description, - Tag: `json:"` + field.Name + `"`, - } - - if m.FieldHook != nil { - mf, err := m.FieldHook(schemaType, field, f) - if err != nil { - return nil, fmt.Errorf("generror: field %v.%v: %w", schemaType.Name, field.Name, err) - } - f = mf - } - - fields = append(fields, f) - } - - return fields, nil -} - -// GoTagFieldHook applies the goTag directive to the generated Field f. When applying the Tag to the field, the field -// name is used when no value argument is present. -func GoTagFieldHook(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) { - args := make([]string, 0) - for _, goTag := range fd.Directives.ForNames("goTag") { - key := "" - value := fd.Name - - if arg := goTag.Arguments.ForName("key"); arg != nil { - if k, err := arg.Value.Value(nil); err == nil { - key = k.(string) - } - } - - if arg := goTag.Arguments.ForName("value"); arg != nil { - if v, err := arg.Value.Value(nil); err == nil { - value = v.(string) - } - } - - args = append(args, key+":\""+value+"\"") - } - - if len(args) > 0 { - f.Tag = f.Tag + " " + strings.Join(args, " ") - } - - return f, nil -} - -func isStruct(t types.Type) bool { - _, is := t.Underlying().(*types.Struct) - return is -} - -// findAndHandleCyclicalRelationships checks for cyclical relationships between generated structs and replaces them -// with pointers. These relationships will produce compilation errors if they are not pointers. -// Also handles recursive structs. -func findAndHandleCyclicalRelationships(b *ModelBuild) { - for ii, structA := range b.Models { - for _, fieldA := range structA.Fields { - if strings.Contains(fieldA.Type.String(), "NotCyclicalA") { - fmt.Print() - } - if !isStruct(fieldA.Type) { - continue - } - - // the field Type string will be in the form "github.com/99designs/gqlgen/codegen/testserver/followschema.LoopA" - // we only want the part after the last dot: "LoopA" - // this could lead to false positives, as we are only checking the name of the struct type, but these - // should be extremely rare, if it is even possible at all. - fieldAStructNameParts := strings.Split(fieldA.Type.String(), ".") - fieldAStructName := fieldAStructNameParts[len(fieldAStructNameParts)-1] - - // find this struct type amongst the generated structs - for jj, structB := range b.Models { - if structB.Name != fieldAStructName { - continue - } - - // check if structB contains a cyclical reference back to structA - var cyclicalReferenceFound bool - for _, fieldB := range structB.Fields { - if !isStruct(fieldB.Type) { - continue - } - - fieldBStructNameParts := strings.Split(fieldB.Type.String(), ".") - fieldBStructName := fieldBStructNameParts[len(fieldBStructNameParts)-1] - if fieldBStructName == structA.Name { - cyclicalReferenceFound = true - fieldB.Type = types.NewPointer(fieldB.Type) - // keep looping in case this struct has additional fields of this type - } - } - - // if this is a recursive struct (i.e. structA == structB), ensure that we only change this field to a pointer once - if cyclicalReferenceFound && ii != jj { - fieldA.Type = types.NewPointer(fieldA.Type) - break - } - } - } - } -} diff --git a/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.gotpl b/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.gotpl deleted file mode 100644 index 7ad43bef1b..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.gotpl +++ /dev/null @@ -1,102 +0,0 @@ -{{ reserveImport "context" }} -{{ reserveImport "fmt" }} -{{ reserveImport "io" }} -{{ reserveImport "strconv" }} -{{ reserveImport "time" }} -{{ reserveImport "sync" }} -{{ reserveImport "errors" }} -{{ reserveImport "bytes" }} - -{{ reserveImport "github.com/vektah/gqlparser/v2" }} -{{ reserveImport "github.com/vektah/gqlparser/v2/ast" }} -{{ reserveImport "github.com/99designs/gqlgen/graphql" }} -{{ reserveImport "github.com/99designs/gqlgen/graphql/introspection" }} - -{{- range $model := .Interfaces }} - {{ with .Description }} {{.|prefixLines "// "}} {{ end }} - type {{ goModelName .Name }} interface { - {{- range $impl := .Implements }} - Is{{ goModelName $impl }}() - {{- end }} - Is{{ goModelName .Name }}() - {{- range $field := .Fields }} - {{- with .Description }} - {{.|prefixLines "// "}} - {{- end}} - Get{{ $field.GoName }}() {{ $field.Type | ref }} - {{- end }} - } -{{- end }} - -{{ range $model := .Models }} - {{with .Description }} {{.|prefixLines "// "}} {{end}} - type {{ goModelName .Name }} struct { - {{- range $field := .Fields }} - {{- with .Description }} - {{.|prefixLines "// "}} - {{- end}} - {{ $field.GoName }} {{$field.Type | ref}} `{{$field.Tag}}` - {{- end }} - } - - {{ range .Implements }} - func ({{ goModelName $model.Name }}) Is{{ goModelName . }}() {} - {{- with getInterfaceByName . }} - {{- range .Fields }} - {{- with .Description }} - {{.|prefixLines "// "}} - {{- end}} - {{ generateGetter $model . }} - {{- end }} - {{- end }} - {{ end }} -{{- end}} - -{{ range $enum := .Enums }} - {{ with .Description }} {{.|prefixLines "// "}} {{end}} - type {{ goModelName .Name }} string - const ( - {{- range $value := .Values}} - {{- with .Description}} - {{.|prefixLines "// "}} - {{- end}} - {{ goModelName $enum.Name .Name }} {{ goModelName $enum.Name }} = {{ .Name|quote }} - {{- end }} - ) - - var All{{ goModelName .Name }} = []{{ goModelName .Name }}{ - {{- range $value := .Values}} - {{ goModelName $enum.Name .Name }}, - {{- end }} - } - - func (e {{ goModelName .Name }}) IsValid() bool { - switch e { - case {{ range $index, $element := .Values}}{{if $index}},{{end}}{{ goModelName $enum.Name $element.Name }}{{end}}: - return true - } - return false - } - - func (e {{ goModelName .Name }}) String() string { - return string(e) - } - - func (e *{{ goModelName .Name }}) UnmarshalGQL(v interface{}) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = {{ goModelName .Name }}(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid {{ .Name }}", str) - } - return nil - } - - func (e {{ goModelName .Name }}) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) - } - -{{- end }} diff --git a/vendor/github.com/99designs/gqlgen/plugin/plugin.go b/vendor/github.com/99designs/gqlgen/plugin/plugin.go deleted file mode 100644 index 7de36bd8cd..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/plugin.go +++ /dev/null @@ -1,31 +0,0 @@ -// plugin package interfaces are EXPERIMENTAL. - -package plugin - -import ( - "github.com/99designs/gqlgen/codegen" - "github.com/99designs/gqlgen/codegen/config" - "github.com/vektah/gqlparser/v2/ast" -) - -type Plugin interface { - Name() string -} - -type ConfigMutator interface { - MutateConfig(cfg *config.Config) error -} - -type CodeGenerator interface { - GenerateCode(cfg *codegen.Data) error -} - -// EarlySourceInjector is used to inject things that are required for user schema files to compile. -type EarlySourceInjector interface { - InjectSourceEarly() *ast.Source -} - -// LateSourceInjector is used to inject more sources, after we have loaded the users schema. -type LateSourceInjector interface { - InjectSourceLate(schema *ast.Schema) *ast.Source -} diff --git a/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.go b/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.go deleted file mode 100644 index aa3be72739..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.go +++ /dev/null @@ -1,227 +0,0 @@ -package resolvergen - -import ( - _ "embed" - "errors" - "fmt" - "io/fs" - "os" - "path/filepath" - "strings" - - "github.com/99designs/gqlgen/codegen" - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/codegen/templates" - "github.com/99designs/gqlgen/internal/rewrite" - "github.com/99designs/gqlgen/plugin" - "golang.org/x/text/cases" - "golang.org/x/text/language" -) - -//go:embed resolver.gotpl -var resolverTemplate string - -func New() plugin.Plugin { - return &Plugin{} -} - -type Plugin struct{} - -var _ plugin.CodeGenerator = &Plugin{} - -func (m *Plugin) Name() string { - return "resolvergen" -} - -func (m *Plugin) GenerateCode(data *codegen.Data) error { - if !data.Config.Resolver.IsDefined() { - return nil - } - - switch data.Config.Resolver.Layout { - case config.LayoutSingleFile: - return m.generateSingleFile(data) - case config.LayoutFollowSchema: - return m.generatePerSchema(data) - } - - return nil -} - -func (m *Plugin) generateSingleFile(data *codegen.Data) error { - file := File{} - - if _, err := os.Stat(data.Config.Resolver.Filename); err == nil { - // file already exists and we dont support updating resolvers with layout = single so just return - return nil - } - - for _, o := range data.Objects { - if o.HasResolvers() { - file.Objects = append(file.Objects, o) - } - for _, f := range o.Fields { - if !f.IsResolver { - continue - } - - resolver := Resolver{o, f, "// foo", `panic("not implemented")`} - file.Resolvers = append(file.Resolvers, &resolver) - } - } - - resolverBuild := &ResolverBuild{ - File: &file, - PackageName: data.Config.Resolver.Package, - ResolverType: data.Config.Resolver.Type, - HasRoot: true, - } - - return templates.Render(templates.Options{ - PackageName: data.Config.Resolver.Package, - FileNotice: `// THIS CODE IS A STARTING POINT ONLY. IT WILL NOT BE UPDATED WITH SCHEMA CHANGES.`, - Filename: data.Config.Resolver.Filename, - Data: resolverBuild, - Packages: data.Config.Packages, - Template: resolverTemplate, - }) -} - -func (m *Plugin) generatePerSchema(data *codegen.Data) error { - rewriter, err := rewrite.New(data.Config.Resolver.Dir()) - if err != nil { - return err - } - - files := map[string]*File{} - - objects := make(codegen.Objects, len(data.Objects)+len(data.Inputs)) - copy(objects, data.Objects) - copy(objects[len(data.Objects):], data.Inputs) - - for _, o := range objects { - if o.HasResolvers() { - fn := gqlToResolverName(data.Config.Resolver.Dir(), o.Position.Src.Name, data.Config.Resolver.FilenameTemplate) - if files[fn] == nil { - files[fn] = &File{} - } - - caser := cases.Title(language.English, cases.NoLower) - rewriter.MarkStructCopied(templates.LcFirst(o.Name) + templates.UcFirst(data.Config.Resolver.Type)) - rewriter.GetMethodBody(data.Config.Resolver.Type, caser.String(o.Name)) - files[fn].Objects = append(files[fn].Objects, o) - } - for _, f := range o.Fields { - if !f.IsResolver { - continue - } - - structName := templates.LcFirst(o.Name) + templates.UcFirst(data.Config.Resolver.Type) - implementation := strings.TrimSpace(rewriter.GetMethodBody(structName, f.GoFieldName)) - comment := strings.TrimSpace(strings.TrimLeft(rewriter.GetMethodComment(structName, f.GoFieldName), `\`)) - if implementation == "" { - implementation = fmt.Sprintf("panic(fmt.Errorf(\"not implemented: %v - %v\"))", f.GoFieldName, f.Name) - } - if comment == "" { - comment = fmt.Sprintf("%v is the resolver for the %v field.", f.GoFieldName, f.Name) - } - - resolver := Resolver{o, f, comment, implementation} - fn := gqlToResolverName(data.Config.Resolver.Dir(), f.Position.Src.Name, data.Config.Resolver.FilenameTemplate) - if files[fn] == nil { - files[fn] = &File{} - } - - files[fn].Resolvers = append(files[fn].Resolvers, &resolver) - } - } - - for filename, file := range files { - file.imports = rewriter.ExistingImports(filename) - file.RemainingSource = rewriter.RemainingSource(filename) - } - - for filename, file := range files { - resolverBuild := &ResolverBuild{ - File: file, - PackageName: data.Config.Resolver.Package, - ResolverType: data.Config.Resolver.Type, - } - - err := templates.Render(templates.Options{ - PackageName: data.Config.Resolver.Package, - FileNotice: ` - // This file will be automatically regenerated based on the schema, any resolver implementations - // will be copied through when generating and any unknown code will be moved to the end.`, - Filename: filename, - Data: resolverBuild, - Packages: data.Config.Packages, - Template: resolverTemplate, - }) - if err != nil { - return err - } - } - - if _, err := os.Stat(data.Config.Resolver.Filename); errors.Is(err, fs.ErrNotExist) { - err := templates.Render(templates.Options{ - PackageName: data.Config.Resolver.Package, - FileNotice: ` - // This file will not be regenerated automatically. - // - // It serves as dependency injection for your app, add any dependencies you require here.`, - Template: `type {{.}} struct {}`, - Filename: data.Config.Resolver.Filename, - Data: data.Config.Resolver.Type, - Packages: data.Config.Packages, - }) - if err != nil { - return err - } - } - return nil -} - -type ResolverBuild struct { - *File - HasRoot bool - PackageName string - ResolverType string -} - -type File struct { - // These are separated because the type definition of the resolver object may live in a different file from the - // resolver method implementations, for example when extending a type in a different graphql schema file - Objects []*codegen.Object - Resolvers []*Resolver - imports []rewrite.Import - RemainingSource string -} - -func (f *File) Imports() string { - for _, imp := range f.imports { - if imp.Alias == "" { - _, _ = templates.CurrentImports.Reserve(imp.ImportPath) - } else { - _, _ = templates.CurrentImports.Reserve(imp.ImportPath, imp.Alias) - } - } - return "" -} - -type Resolver struct { - Object *codegen.Object - Field *codegen.Field - Comment string - Implementation string -} - -func gqlToResolverName(base string, gqlname, filenameTmpl string) string { - gqlname = filepath.Base(gqlname) - ext := filepath.Ext(gqlname) - if filenameTmpl == "" { - filenameTmpl = "{name}.resolvers.go" - } - filename := strings.ReplaceAll(filenameTmpl, "{name}", strings.TrimSuffix(gqlname, ext)) - return filepath.Join(base, filename) -} diff --git a/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.gotpl b/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.gotpl deleted file mode 100644 index c5d716ff7b..0000000000 --- a/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.gotpl +++ /dev/null @@ -1,46 +0,0 @@ -{{ reserveImport "context" }} -{{ reserveImport "fmt" }} -{{ reserveImport "io" }} -{{ reserveImport "strconv" }} -{{ reserveImport "time" }} -{{ reserveImport "sync" }} -{{ reserveImport "errors" }} -{{ reserveImport "bytes" }} - -{{ reserveImport "github.com/vektah/gqlparser/v2" }} -{{ reserveImport "github.com/vektah/gqlparser/v2/ast" }} -{{ reserveImport "github.com/99designs/gqlgen/graphql" }} -{{ reserveImport "github.com/99designs/gqlgen/graphql/introspection" }} - -{{ .Imports }} - -{{ if .HasRoot }} - type {{.ResolverType}} struct {} -{{ end }} - -{{ range $resolver := .Resolvers -}} - // {{ $resolver.Comment }} - func (r *{{lcFirst $resolver.Object.Name}}{{ucFirst $.ResolverType}}) {{$resolver.Field.GoFieldName}}{{ $resolver.Field.ShortResolverDeclaration }} { - {{ $resolver.Implementation }} - } - -{{ end }} - -{{ range $object := .Objects -}} - // {{ucFirst $object.Name}} returns {{ $object.ResolverInterface | ref }} implementation. - func (r *{{$.ResolverType}}) {{ucFirst $object.Name}}() {{ $object.ResolverInterface | ref }} { return &{{lcFirst $object.Name}}{{ucFirst $.ResolverType}}{r} } -{{ end }} - -{{ range $object := .Objects -}} - type {{lcFirst $object.Name}}{{ucFirst $.ResolverType}} struct { *{{$.ResolverType}} } -{{ end }} - -{{ if (ne .RemainingSource "") }} - // !!! WARNING !!! - // The code below was going to be deleted when updating resolvers. It has been copied here so you have - // one last chance to move it out of harms way if you want. There are two reasons this happens: - // - When renaming or deleting a resolver the old code will be put in here. You can safely delete - // it when you're done. - // - You have helper methods in this file. Move them out to keep these resolver files clean. - {{ .RemainingSource }} -{{ end }} diff --git a/vendor/github.com/Azure/go-ntlmssp/.travis.yml b/vendor/github.com/Azure/go-ntlmssp/.travis.yml deleted file mode 100644 index 23c95fe951..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -sudo: false - -language: go - -before_script: - - go get -u golang.org/x/lint/golint - -go: - - 1.10.x - - master - -script: - - test -z "$(gofmt -s -l . | tee /dev/stderr)" - - test -z "$(golint ./... | tee /dev/stderr)" - - go vet ./... - - go build -v ./... - - go test -v ./... diff --git a/vendor/github.com/Azure/go-ntlmssp/LICENSE b/vendor/github.com/Azure/go-ntlmssp/LICENSE deleted file mode 100644 index dc1cf39d13..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Microsoft - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/Azure/go-ntlmssp/README.md b/vendor/github.com/Azure/go-ntlmssp/README.md deleted file mode 100644 index 55cdcefab7..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# go-ntlmssp -Golang package that provides NTLM/Negotiate authentication over HTTP - -[![GoDoc](https://godoc.org/github.com/Azure/go-ntlmssp?status.svg)](https://godoc.org/github.com/Azure/go-ntlmssp) [![Build Status](https://travis-ci.org/Azure/go-ntlmssp.svg?branch=dev)](https://travis-ci.org/Azure/go-ntlmssp) - -Protocol details from https://msdn.microsoft.com/en-us/library/cc236621.aspx -Implementation hints from http://davenport.sourceforge.net/ntlm.html - -This package only implements authentication, no key exchange or encryption. It -only supports Unicode (UTF16LE) encoding of protocol strings, no OEM encoding. -This package implements NTLMv2. - -# Usage - -``` -url, user, password := "http://www.example.com/secrets", "robpike", "pw123" -client := &http.Client{ - Transport: ntlmssp.Negotiator{ - RoundTripper:&http.Transport{}, - }, -} - -req, _ := http.NewRequest("GET", url, nil) -req.SetBasicAuth(user, password) -res, _ := client.Do(req) -``` - ------ -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/go-ntlmssp/authenticate_message.go b/vendor/github.com/Azure/go-ntlmssp/authenticate_message.go deleted file mode 100644 index c8930680c5..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/authenticate_message.go +++ /dev/null @@ -1,183 +0,0 @@ -package ntlmssp - -import ( - "bytes" - "crypto/rand" - "encoding/binary" - "encoding/hex" - "errors" - "strings" - "time" -) - -type authenicateMessage struct { - LmChallengeResponse []byte - NtChallengeResponse []byte - - TargetName string - UserName string - - // only set if negotiateFlag_NTLMSSP_NEGOTIATE_KEY_EXCH - EncryptedRandomSessionKey []byte - - NegotiateFlags negotiateFlags - - MIC []byte -} - -type authenticateMessageFields struct { - messageHeader - LmChallengeResponse varField - NtChallengeResponse varField - TargetName varField - UserName varField - Workstation varField - _ [8]byte - NegotiateFlags negotiateFlags -} - -func (m authenicateMessage) MarshalBinary() ([]byte, error) { - if !m.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATEUNICODE) { - return nil, errors.New("Only unicode is supported") - } - - target, user := toUnicode(m.TargetName), toUnicode(m.UserName) - workstation := toUnicode("go-ntlmssp") - - ptr := binary.Size(&authenticateMessageFields{}) - f := authenticateMessageFields{ - messageHeader: newMessageHeader(3), - NegotiateFlags: m.NegotiateFlags, - LmChallengeResponse: newVarField(&ptr, len(m.LmChallengeResponse)), - NtChallengeResponse: newVarField(&ptr, len(m.NtChallengeResponse)), - TargetName: newVarField(&ptr, len(target)), - UserName: newVarField(&ptr, len(user)), - Workstation: newVarField(&ptr, len(workstation)), - } - - f.NegotiateFlags.Unset(negotiateFlagNTLMSSPNEGOTIATEVERSION) - - b := bytes.Buffer{} - if err := binary.Write(&b, binary.LittleEndian, &f); err != nil { - return nil, err - } - if err := binary.Write(&b, binary.LittleEndian, &m.LmChallengeResponse); err != nil { - return nil, err - } - if err := binary.Write(&b, binary.LittleEndian, &m.NtChallengeResponse); err != nil { - return nil, err - } - if err := binary.Write(&b, binary.LittleEndian, &target); err != nil { - return nil, err - } - if err := binary.Write(&b, binary.LittleEndian, &user); err != nil { - return nil, err - } - if err := binary.Write(&b, binary.LittleEndian, &workstation); err != nil { - return nil, err - } - - return b.Bytes(), nil -} - -//ProcessChallenge crafts an AUTHENTICATE message in response to the CHALLENGE message -//that was received from the server -func ProcessChallenge(challengeMessageData []byte, user, password string) ([]byte, error) { - if user == "" && password == "" { - return nil, errors.New("Anonymous authentication not supported") - } - - var cm challengeMessage - if err := cm.UnmarshalBinary(challengeMessageData); err != nil { - return nil, err - } - - if cm.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATELMKEY) { - return nil, errors.New("Only NTLM v2 is supported, but server requested v1 (NTLMSSP_NEGOTIATE_LM_KEY)") - } - if cm.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATEKEYEXCH) { - return nil, errors.New("Key exchange requested but not supported (NTLMSSP_NEGOTIATE_KEY_EXCH)") - } - - am := authenicateMessage{ - UserName: user, - TargetName: cm.TargetName, - NegotiateFlags: cm.NegotiateFlags, - } - - timestamp := cm.TargetInfo[avIDMsvAvTimestamp] - if timestamp == nil { // no time sent, take current time - ft := uint64(time.Now().UnixNano()) / 100 - ft += 116444736000000000 // add time between unix & windows offset - timestamp = make([]byte, 8) - binary.LittleEndian.PutUint64(timestamp, ft) - } - - clientChallenge := make([]byte, 8) - rand.Reader.Read(clientChallenge) - - ntlmV2Hash := getNtlmV2Hash(password, user, cm.TargetName) - - am.NtChallengeResponse = computeNtlmV2Response(ntlmV2Hash, - cm.ServerChallenge[:], clientChallenge, timestamp, cm.TargetInfoRaw) - - if cm.TargetInfoRaw == nil { - am.LmChallengeResponse = computeLmV2Response(ntlmV2Hash, - cm.ServerChallenge[:], clientChallenge) - } - return am.MarshalBinary() -} - -func ProcessChallengeWithHash(challengeMessageData []byte, user, hash string) ([]byte, error) { - if user == "" && hash == "" { - return nil, errors.New("Anonymous authentication not supported") - } - - var cm challengeMessage - if err := cm.UnmarshalBinary(challengeMessageData); err != nil { - return nil, err - } - - if cm.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATELMKEY) { - return nil, errors.New("Only NTLM v2 is supported, but server requested v1 (NTLMSSP_NEGOTIATE_LM_KEY)") - } - if cm.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATEKEYEXCH) { - return nil, errors.New("Key exchange requested but not supported (NTLMSSP_NEGOTIATE_KEY_EXCH)") - } - - am := authenicateMessage{ - UserName: user, - TargetName: cm.TargetName, - NegotiateFlags: cm.NegotiateFlags, - } - - timestamp := cm.TargetInfo[avIDMsvAvTimestamp] - if timestamp == nil { // no time sent, take current time - ft := uint64(time.Now().UnixNano()) / 100 - ft += 116444736000000000 // add time between unix & windows offset - timestamp = make([]byte, 8) - binary.LittleEndian.PutUint64(timestamp, ft) - } - - clientChallenge := make([]byte, 8) - rand.Reader.Read(clientChallenge) - - hashParts := strings.Split(hash, ":") - if len(hashParts) > 1 { - hash = hashParts[1] - } - hashBytes, err := hex.DecodeString(hash) - if err != nil { - return nil, err - } - ntlmV2Hash := hmacMd5(hashBytes, toUnicode(strings.ToUpper(user)+cm.TargetName)) - - am.NtChallengeResponse = computeNtlmV2Response(ntlmV2Hash, - cm.ServerChallenge[:], clientChallenge, timestamp, cm.TargetInfoRaw) - - if cm.TargetInfoRaw == nil { - am.LmChallengeResponse = computeLmV2Response(ntlmV2Hash, - cm.ServerChallenge[:], clientChallenge) - } - return am.MarshalBinary() -} diff --git a/vendor/github.com/Azure/go-ntlmssp/authheader.go b/vendor/github.com/Azure/go-ntlmssp/authheader.go deleted file mode 100644 index aac3f77d10..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/authheader.go +++ /dev/null @@ -1,37 +0,0 @@ -package ntlmssp - -import ( - "encoding/base64" - "strings" -) - -type authheader string - -func (h authheader) IsBasic() bool { - return strings.HasPrefix(string(h), "Basic ") -} - -func (h authheader) IsNegotiate() bool { - return strings.HasPrefix(string(h), "Negotiate") -} - -func (h authheader) IsNTLM() bool { - return strings.HasPrefix(string(h), "NTLM") -} - -func (h authheader) GetData() ([]byte, error) { - p := strings.Split(string(h), " ") - if len(p) < 2 { - return nil, nil - } - return base64.StdEncoding.DecodeString(string(p[1])) -} - -func (h authheader) GetBasicCreds() (username, password string, err error) { - d, err := h.GetData() - if err != nil { - return "", "", err - } - parts := strings.SplitN(string(d), ":", 2) - return parts[0], parts[1], nil -} diff --git a/vendor/github.com/Azure/go-ntlmssp/avids.go b/vendor/github.com/Azure/go-ntlmssp/avids.go deleted file mode 100644 index 196b5f1316..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/avids.go +++ /dev/null @@ -1,17 +0,0 @@ -package ntlmssp - -type avID uint16 - -const ( - avIDMsvAvEOL avID = iota - avIDMsvAvNbComputerName - avIDMsvAvNbDomainName - avIDMsvAvDNSComputerName - avIDMsvAvDNSDomainName - avIDMsvAvDNSTreeName - avIDMsvAvFlags - avIDMsvAvTimestamp - avIDMsvAvSingleHost - avIDMsvAvTargetName - avIDMsvChannelBindings -) diff --git a/vendor/github.com/Azure/go-ntlmssp/challenge_message.go b/vendor/github.com/Azure/go-ntlmssp/challenge_message.go deleted file mode 100644 index 053b55e4ad..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/challenge_message.go +++ /dev/null @@ -1,82 +0,0 @@ -package ntlmssp - -import ( - "bytes" - "encoding/binary" - "fmt" -) - -type challengeMessageFields struct { - messageHeader - TargetName varField - NegotiateFlags negotiateFlags - ServerChallenge [8]byte - _ [8]byte - TargetInfo varField -} - -func (m challengeMessageFields) IsValid() bool { - return m.messageHeader.IsValid() && m.MessageType == 2 -} - -type challengeMessage struct { - challengeMessageFields - TargetName string - TargetInfo map[avID][]byte - TargetInfoRaw []byte -} - -func (m *challengeMessage) UnmarshalBinary(data []byte) error { - r := bytes.NewReader(data) - err := binary.Read(r, binary.LittleEndian, &m.challengeMessageFields) - if err != nil { - return err - } - if !m.challengeMessageFields.IsValid() { - return fmt.Errorf("Message is not a valid challenge message: %+v", m.challengeMessageFields.messageHeader) - } - - if m.challengeMessageFields.TargetName.Len > 0 { - m.TargetName, err = m.challengeMessageFields.TargetName.ReadStringFrom(data, m.NegotiateFlags.Has(negotiateFlagNTLMSSPNEGOTIATEUNICODE)) - if err != nil { - return err - } - } - - if m.challengeMessageFields.TargetInfo.Len > 0 { - d, err := m.challengeMessageFields.TargetInfo.ReadFrom(data) - m.TargetInfoRaw = d - if err != nil { - return err - } - m.TargetInfo = make(map[avID][]byte) - r := bytes.NewReader(d) - for { - var id avID - var l uint16 - err = binary.Read(r, binary.LittleEndian, &id) - if err != nil { - return err - } - if id == avIDMsvAvEOL { - break - } - - err = binary.Read(r, binary.LittleEndian, &l) - if err != nil { - return err - } - value := make([]byte, l) - n, err := r.Read(value) - if err != nil { - return err - } - if n != int(l) { - return fmt.Errorf("Expected to read %d bytes, got only %d", l, n) - } - m.TargetInfo[id] = value - } - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ntlmssp/messageheader.go b/vendor/github.com/Azure/go-ntlmssp/messageheader.go deleted file mode 100644 index 247e284652..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/messageheader.go +++ /dev/null @@ -1,21 +0,0 @@ -package ntlmssp - -import ( - "bytes" -) - -var signature = [8]byte{'N', 'T', 'L', 'M', 'S', 'S', 'P', 0} - -type messageHeader struct { - Signature [8]byte - MessageType uint32 -} - -func (h messageHeader) IsValid() bool { - return bytes.Equal(h.Signature[:], signature[:]) && - h.MessageType > 0 && h.MessageType < 4 -} - -func newMessageHeader(messageType uint32) messageHeader { - return messageHeader{signature, messageType} -} diff --git a/vendor/github.com/Azure/go-ntlmssp/negotiate_flags.go b/vendor/github.com/Azure/go-ntlmssp/negotiate_flags.go deleted file mode 100644 index 5905c023d6..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/negotiate_flags.go +++ /dev/null @@ -1,52 +0,0 @@ -package ntlmssp - -type negotiateFlags uint32 - -const ( - /*A*/ negotiateFlagNTLMSSPNEGOTIATEUNICODE negotiateFlags = 1 << 0 - /*B*/ negotiateFlagNTLMNEGOTIATEOEM = 1 << 1 - /*C*/ negotiateFlagNTLMSSPREQUESTTARGET = 1 << 2 - - /*D*/ - negotiateFlagNTLMSSPNEGOTIATESIGN = 1 << 4 - /*E*/ negotiateFlagNTLMSSPNEGOTIATESEAL = 1 << 5 - /*F*/ negotiateFlagNTLMSSPNEGOTIATEDATAGRAM = 1 << 6 - /*G*/ negotiateFlagNTLMSSPNEGOTIATELMKEY = 1 << 7 - - /*H*/ - negotiateFlagNTLMSSPNEGOTIATENTLM = 1 << 9 - - /*J*/ - negotiateFlagANONYMOUS = 1 << 11 - /*K*/ negotiateFlagNTLMSSPNEGOTIATEOEMDOMAINSUPPLIED = 1 << 12 - /*L*/ negotiateFlagNTLMSSPNEGOTIATEOEMWORKSTATIONSUPPLIED = 1 << 13 - - /*M*/ - negotiateFlagNTLMSSPNEGOTIATEALWAYSSIGN = 1 << 15 - /*N*/ negotiateFlagNTLMSSPTARGETTYPEDOMAIN = 1 << 16 - /*O*/ negotiateFlagNTLMSSPTARGETTYPESERVER = 1 << 17 - - /*P*/ - negotiateFlagNTLMSSPNEGOTIATEEXTENDEDSESSIONSECURITY = 1 << 19 - /*Q*/ negotiateFlagNTLMSSPNEGOTIATEIDENTIFY = 1 << 20 - - /*R*/ - negotiateFlagNTLMSSPREQUESTNONNTSESSIONKEY = 1 << 22 - /*S*/ negotiateFlagNTLMSSPNEGOTIATETARGETINFO = 1 << 23 - - /*T*/ - negotiateFlagNTLMSSPNEGOTIATEVERSION = 1 << 25 - - /*U*/ - negotiateFlagNTLMSSPNEGOTIATE128 = 1 << 29 - /*V*/ negotiateFlagNTLMSSPNEGOTIATEKEYEXCH = 1 << 30 - /*W*/ negotiateFlagNTLMSSPNEGOTIATE56 = 1 << 31 -) - -func (field negotiateFlags) Has(flags negotiateFlags) bool { - return field&flags == flags -} - -func (field *negotiateFlags) Unset(flags negotiateFlags) { - *field = *field ^ (*field & flags) -} diff --git a/vendor/github.com/Azure/go-ntlmssp/negotiate_message.go b/vendor/github.com/Azure/go-ntlmssp/negotiate_message.go deleted file mode 100644 index e466a9861d..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/negotiate_message.go +++ /dev/null @@ -1,64 +0,0 @@ -package ntlmssp - -import ( - "bytes" - "encoding/binary" - "errors" - "strings" -) - -const expMsgBodyLen = 40 - -type negotiateMessageFields struct { - messageHeader - NegotiateFlags negotiateFlags - - Domain varField - Workstation varField - - Version -} - -var defaultFlags = negotiateFlagNTLMSSPNEGOTIATETARGETINFO | - negotiateFlagNTLMSSPNEGOTIATE56 | - negotiateFlagNTLMSSPNEGOTIATE128 | - negotiateFlagNTLMSSPNEGOTIATEUNICODE | - negotiateFlagNTLMSSPNEGOTIATEEXTENDEDSESSIONSECURITY - -//NewNegotiateMessage creates a new NEGOTIATE message with the -//flags that this package supports. -func NewNegotiateMessage(domainName, workstationName string) ([]byte, error) { - payloadOffset := expMsgBodyLen - flags := defaultFlags - - if domainName != "" { - flags |= negotiateFlagNTLMSSPNEGOTIATEOEMDOMAINSUPPLIED - } - - if workstationName != "" { - flags |= negotiateFlagNTLMSSPNEGOTIATEOEMWORKSTATIONSUPPLIED - } - - msg := negotiateMessageFields{ - messageHeader: newMessageHeader(1), - NegotiateFlags: flags, - Domain: newVarField(&payloadOffset, len(domainName)), - Workstation: newVarField(&payloadOffset, len(workstationName)), - Version: DefaultVersion(), - } - - b := bytes.Buffer{} - if err := binary.Write(&b, binary.LittleEndian, &msg); err != nil { - return nil, err - } - if b.Len() != expMsgBodyLen { - return nil, errors.New("incorrect body length") - } - - payload := strings.ToUpper(domainName + workstationName) - if _, err := b.WriteString(payload); err != nil { - return nil, err - } - - return b.Bytes(), nil -} diff --git a/vendor/github.com/Azure/go-ntlmssp/negotiator.go b/vendor/github.com/Azure/go-ntlmssp/negotiator.go deleted file mode 100644 index 7705eae4f8..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/negotiator.go +++ /dev/null @@ -1,144 +0,0 @@ -package ntlmssp - -import ( - "bytes" - "encoding/base64" - "io" - "io/ioutil" - "net/http" - "strings" -) - -// GetDomain : parse domain name from based on slashes in the input -func GetDomain(user string) (string, string) { - domain := "" - - if strings.Contains(user, "\\") { - ucomponents := strings.SplitN(user, "\\", 2) - domain = ucomponents[0] - user = ucomponents[1] - } - return user, domain -} - -//Negotiator is a http.Roundtripper decorator that automatically -//converts basic authentication to NTLM/Negotiate authentication when appropriate. -type Negotiator struct{ http.RoundTripper } - -//RoundTrip sends the request to the server, handling any authentication -//re-sends as needed. -func (l Negotiator) RoundTrip(req *http.Request) (res *http.Response, err error) { - // Use default round tripper if not provided - rt := l.RoundTripper - if rt == nil { - rt = http.DefaultTransport - } - // If it is not basic auth, just round trip the request as usual - reqauth := authheader(req.Header.Get("Authorization")) - if !reqauth.IsBasic() { - return rt.RoundTrip(req) - } - // Save request body - body := bytes.Buffer{} - if req.Body != nil { - _, err = body.ReadFrom(req.Body) - if err != nil { - return nil, err - } - - req.Body.Close() - req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes())) - } - // first try anonymous, in case the server still finds us - // authenticated from previous traffic - req.Header.Del("Authorization") - res, err = rt.RoundTrip(req) - if err != nil { - return nil, err - } - if res.StatusCode != http.StatusUnauthorized { - return res, err - } - - resauth := authheader(res.Header.Get("Www-Authenticate")) - if !resauth.IsNegotiate() && !resauth.IsNTLM() { - // Unauthorized, Negotiate not requested, let's try with basic auth - req.Header.Set("Authorization", string(reqauth)) - io.Copy(ioutil.Discard, res.Body) - res.Body.Close() - req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes())) - - res, err = rt.RoundTrip(req) - if err != nil { - return nil, err - } - if res.StatusCode != http.StatusUnauthorized { - return res, err - } - resauth = authheader(res.Header.Get("Www-Authenticate")) - } - - if resauth.IsNegotiate() || resauth.IsNTLM() { - // 401 with request:Basic and response:Negotiate - io.Copy(ioutil.Discard, res.Body) - res.Body.Close() - - // recycle credentials - u, p, err := reqauth.GetBasicCreds() - if err != nil { - return nil, err - } - - // get domain from username - domain := "" - u, domain = GetDomain(u) - - // send negotiate - negotiateMessage, err := NewNegotiateMessage(domain, "") - if err != nil { - return nil, err - } - if resauth.IsNTLM() { - req.Header.Set("Authorization", "NTLM "+base64.StdEncoding.EncodeToString(negotiateMessage)) - } else { - req.Header.Set("Authorization", "Negotiate "+base64.StdEncoding.EncodeToString(negotiateMessage)) - } - - req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes())) - - res, err = rt.RoundTrip(req) - if err != nil { - return nil, err - } - - // receive challenge? - resauth = authheader(res.Header.Get("Www-Authenticate")) - challengeMessage, err := resauth.GetData() - if err != nil { - return nil, err - } - if !(resauth.IsNegotiate() || resauth.IsNTLM()) || len(challengeMessage) == 0 { - // Negotiation failed, let client deal with response - return res, nil - } - io.Copy(ioutil.Discard, res.Body) - res.Body.Close() - - // send authenticate - authenticateMessage, err := ProcessChallenge(challengeMessage, u, p) - if err != nil { - return nil, err - } - if resauth.IsNTLM() { - req.Header.Set("Authorization", "NTLM "+base64.StdEncoding.EncodeToString(authenticateMessage)) - } else { - req.Header.Set("Authorization", "Negotiate "+base64.StdEncoding.EncodeToString(authenticateMessage)) - } - - req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes())) - - return rt.RoundTrip(req) - } - - return res, err -} diff --git a/vendor/github.com/Azure/go-ntlmssp/nlmp.go b/vendor/github.com/Azure/go-ntlmssp/nlmp.go deleted file mode 100644 index 1e65abe8b5..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/nlmp.go +++ /dev/null @@ -1,51 +0,0 @@ -// Package ntlmssp provides NTLM/Negotiate authentication over HTTP -// -// Protocol details from https://msdn.microsoft.com/en-us/library/cc236621.aspx, -// implementation hints from http://davenport.sourceforge.net/ntlm.html . -// This package only implements authentication, no key exchange or encryption. It -// only supports Unicode (UTF16LE) encoding of protocol strings, no OEM encoding. -// This package implements NTLMv2. -package ntlmssp - -import ( - "crypto/hmac" - "crypto/md5" - "golang.org/x/crypto/md4" - "strings" -) - -func getNtlmV2Hash(password, username, target string) []byte { - return hmacMd5(getNtlmHash(password), toUnicode(strings.ToUpper(username)+target)) -} - -func getNtlmHash(password string) []byte { - hash := md4.New() - hash.Write(toUnicode(password)) - return hash.Sum(nil) -} - -func computeNtlmV2Response(ntlmV2Hash, serverChallenge, clientChallenge, - timestamp, targetInfo []byte) []byte { - - temp := []byte{1, 1, 0, 0, 0, 0, 0, 0} - temp = append(temp, timestamp...) - temp = append(temp, clientChallenge...) - temp = append(temp, 0, 0, 0, 0) - temp = append(temp, targetInfo...) - temp = append(temp, 0, 0, 0, 0) - - NTProofStr := hmacMd5(ntlmV2Hash, serverChallenge, temp) - return append(NTProofStr, temp...) -} - -func computeLmV2Response(ntlmV2Hash, serverChallenge, clientChallenge []byte) []byte { - return append(hmacMd5(ntlmV2Hash, serverChallenge, clientChallenge), clientChallenge...) -} - -func hmacMd5(key []byte, data ...[]byte) []byte { - mac := hmac.New(md5.New, key) - for _, d := range data { - mac.Write(d) - } - return mac.Sum(nil) -} diff --git a/vendor/github.com/Azure/go-ntlmssp/unicode.go b/vendor/github.com/Azure/go-ntlmssp/unicode.go deleted file mode 100644 index 7b4f47163d..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/unicode.go +++ /dev/null @@ -1,29 +0,0 @@ -package ntlmssp - -import ( - "bytes" - "encoding/binary" - "errors" - "unicode/utf16" -) - -// helper func's for dealing with Windows Unicode (UTF16LE) - -func fromUnicode(d []byte) (string, error) { - if len(d)%2 > 0 { - return "", errors.New("Unicode (UTF 16 LE) specified, but uneven data length") - } - s := make([]uint16, len(d)/2) - err := binary.Read(bytes.NewReader(d), binary.LittleEndian, &s) - if err != nil { - return "", err - } - return string(utf16.Decode(s)), nil -} - -func toUnicode(s string) []byte { - uints := utf16.Encode([]rune(s)) - b := bytes.Buffer{} - binary.Write(&b, binary.LittleEndian, &uints) - return b.Bytes() -} diff --git a/vendor/github.com/Azure/go-ntlmssp/varfield.go b/vendor/github.com/Azure/go-ntlmssp/varfield.go deleted file mode 100644 index 15f9aa113d..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/varfield.go +++ /dev/null @@ -1,40 +0,0 @@ -package ntlmssp - -import ( - "errors" -) - -type varField struct { - Len uint16 - MaxLen uint16 - BufferOffset uint32 -} - -func (f varField) ReadFrom(buffer []byte) ([]byte, error) { - if len(buffer) < int(f.BufferOffset+uint32(f.Len)) { - return nil, errors.New("Error reading data, varField extends beyond buffer") - } - return buffer[f.BufferOffset : f.BufferOffset+uint32(f.Len)], nil -} - -func (f varField) ReadStringFrom(buffer []byte, unicode bool) (string, error) { - d, err := f.ReadFrom(buffer) - if err != nil { - return "", err - } - if unicode { // UTF-16LE encoding scheme - return fromUnicode(d) - } - // OEM encoding, close enough to ASCII, since no code page is specified - return string(d), err -} - -func newVarField(ptr *int, fieldsize int) varField { - f := varField{ - Len: uint16(fieldsize), - MaxLen: uint16(fieldsize), - BufferOffset: uint32(*ptr), - } - *ptr += fieldsize - return f -} diff --git a/vendor/github.com/Azure/go-ntlmssp/version.go b/vendor/github.com/Azure/go-ntlmssp/version.go deleted file mode 100644 index 6d84892124..0000000000 --- a/vendor/github.com/Azure/go-ntlmssp/version.go +++ /dev/null @@ -1,20 +0,0 @@ -package ntlmssp - -// Version is a struct representing https://msdn.microsoft.com/en-us/library/cc236654.aspx -type Version struct { - ProductMajorVersion uint8 - ProductMinorVersion uint8 - ProductBuild uint16 - _ [3]byte - NTLMRevisionCurrent uint8 -} - -// DefaultVersion returns a Version with "sensible" defaults (Windows 7) -func DefaultVersion() Version { - return Version{ - ProductMajorVersion: 6, - ProductMinorVersion: 1, - ProductBuild: 7601, - NTLMRevisionCurrent: 15, - } -} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/base/v1/base.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/base/v1/base.go new file mode 100644 index 0000000000..5ac09000f1 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/base/v1/base.go @@ -0,0 +1,23 @@ +package v1 + +// GenericResp defines the return code and msg +// swagger:response GenericResp +type GenericResp struct { + // code + Code int `json:"code"` + // message + Message string `json:"message"` +} + +func (r *GenericResp) SetCode(code int) { + r.Code = code +} + +func (r *GenericResp) SetMsg(msg string) { + r.Message = msg +} + +type GenericResper interface { + SetCode(code int) + SetMsg(msg string) +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/db_service.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/db_service.go new file mode 100644 index 0000000000..743feaf9bd --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/db_service.go @@ -0,0 +1,161 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +type CheckDbConnectable struct { + // DB Service type + // Required: true + // example: MySQL + DBType string `json:"db_type" example:"mysql" validate:"required"` + // DB Service admin user + // Required: true + // example: root + User string `json:"user" example:"root" valid:"required"` + // DB Service host + // Required: true + // example: 127.0.0.1 + Host string `json:"host" example:"10.10.10.10" valid:"required,ip_addr|uri|hostname|hostname_rfc1123"` + // DB Service port + // Required: true + // example: 3306 + Port string `json:"port" example:"3306" valid:"required,port"` + // DB Service admin password + // Required: true + // example: 123456 + Password string `json:"password" example:"123456"` + // DB Service Custom connection parameters + // Required: false + AdditionalParams []*AdditionalParam `json:"additional_params" from:"additional_params"` +} + +type AdditionalParam struct { + Name string `json:"name"` + Value string `json:"value"` + Description string `json:"description" example:"参数项中文名" form:"description"` + Type string `json:"type" example:"int" form:"type"` +} + +// swagger:parameters ListDBServices +type ListDBServiceReq struct { + // the maximum count of db service to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of users to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy DBServiceOrderByField `query:"order_by" json:"order_by"` + // the db service business name + // in:query + FilterByBusiness string `query:"filter_by_business" json:"filter_by_business"` + // the db service host + // in:query + FilterByHost string `query:"filter_by_host" json:"filter_by_host"` + // the db service uid + // in:query + FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` + // the db service name + // in:query + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // the db service port + // in:query + FilterByPort string `query:"filter_by_port" json:"filter_by_port"` + // the db service db type + // in:query + FilterByDBType string `query:"filter_by_db_type" json:"filter_by_db_type"` + // project id + // in:path + ProjectUid string `param:"project_uid" json:"project_uid"` + // the db service fuzzy keyword,include host/port + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` +} + +// swagger:enum DBServiceOrderByField +type DBServiceOrderByField string + +const ( + DBServiceOrderByName DBServiceOrderByField = "name" +) + +type MaintenanceTime struct { + MaintenanceStartTime *Time `json:"maintenance_start_time"` + MaintenanceStopTime *Time `json:"maintenance_stop_time"` +} + +type Time struct { + Hour int `json:"hour"` + Minute int `json:"minute"` +} + +// A dms db Service +type ListDBService struct { + // db service uid + DBServiceUid string `json:"uid"` + // db service name + Name string `json:"name"` + // db service DB type + DBType string `json:"db_type"` + // db service host + Host string `json:"host"` + // db service port + Port string `json:"port"` + // db service admin user + User string `json:"user"` + // db service admin encrypted password + Password string `json:"password"` + // the db service business name + Business string `json:"business"` + // DB Service maintenance time + MaintenanceTimes []*MaintenanceTime `json:"maintenance_times"` + // DB desc + Desc string `json:"desc"` + // DB source + Source string `json:"source"` + // DB project uid + ProjectUID string `json:"project_uid"` + // sqle config + SQLEConfig *SQLEConfig `json:"sqle_config"` + // DB Service Custom connection parameters + AdditionalParams []*AdditionalParam `json:"additional_params"` +} + +type SQLEConfig struct { + // DB Service rule template name + RuleTemplateName string `json:"rule_template_name"` + // DB Service rule template id + RuleTemplateID string `json:"rule_template_id"` + // DB Service SQL query config + SQLQueryConfig *SQLQueryConfig `json:"sql_query_config"` +} + +// swagger:enum SQLAllowQueryAuditLevel +type SQLAllowQueryAuditLevel string + +const ( + AuditLevelNormal SQLAllowQueryAuditLevel = "normal" + AuditLevelNotice SQLAllowQueryAuditLevel = "notice" + AuditLevelWarn SQLAllowQueryAuditLevel = "warn" + AuditLevelError SQLAllowQueryAuditLevel = "error" +) + +type SQLQueryConfig struct { + MaxPreQueryRows int `json:"max_pre_query_rows" example:"100"` + QueryTimeoutSecond int `json:"query_timeout_second" example:"10"` + AuditEnabled bool `json:"audit_enabled" example:"false"` + AllowQueryWhenLessThanAuditLevel SQLAllowQueryAuditLevel `json:"allow_query_when_less_than_audit_level" enums:"normal,notice,warn,error" valid:"omitempty,oneof=normal notice warn error " example:"error"` +} + +// swagger:model ListDBServiceReply +type ListDBServiceReply struct { + // List db service reply + Data []*ListDBService `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/member.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/member.go new file mode 100644 index 0000000000..82bd382d9c --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/member.go @@ -0,0 +1,45 @@ +package v1 + +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + +// swagger:parameters ListMembersForInternal +type ListMembersForInternalReq struct { + // the maximum count of member to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of members to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +// swagger:enum MemberForInternalOrderByField +type MemberForInternalOrderByField string + +const ( + MemberForInternalOrderByUserUid MemberForInternalOrderByField = "user_uid" +) + +// A dms member for internal +type ListMembersForInternalItem struct { + // member user + User UidWithName `json:"user"` + // is member project admin, admin has all permissions + IsAdmin bool `json:"is_admin"` + // member op permissions + MemberOpPermissionList []OpPermissionItem `json:"member_op_permission_list"` +} + +// swagger:model ListMembersForInternalReply +type ListMembersForInternalReply struct { + // List member reply + Data []*ListMembersForInternalItem `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/notify.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/notify.go new file mode 100644 index 0000000000..3b3e6cd98a --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/notify.go @@ -0,0 +1,22 @@ +package v1 + +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + +// swagger:parameters Notification +type NotificationReq struct { + // notification + // in:body + Notification *Notification `json:"notification" validate:"required"` +} + +type Notification struct { + NotificationSubject string `json:"notification_subject"` + NotificationBody string `json:"notification_body"` + UserUids []string `json:"user_uids"` +} + +// swagger:model NotificationReply +type NotificationReply struct { + // Generic reply + base.GenericResp +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/plugin.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/plugin.go new file mode 100644 index 0000000000..0863638b31 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/plugin.go @@ -0,0 +1,195 @@ +package v1 + +import ( + "fmt" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +// swagger:enum IPluginDBType +type IPluginDBType string + +const ( + IPluginDBTypeDBTypeMySQL IPluginDBType = "MySQL" + IPluginDBTypeDBTypeOceanBaseMySQL IPluginDBType = "OceanBaseMySQL" +) + +func ParseIPluginDBType(s string) (IPluginDBType, error) { + switch s { + case string(IPluginDBTypeDBTypeMySQL): + return IPluginDBTypeDBTypeMySQL, nil + case string(IPluginDBTypeDBTypeOceanBaseMySQL): + return IPluginDBTypeDBTypeOceanBaseMySQL, nil + default: + return "", fmt.Errorf("invalid db type: %s", s) + } +} + +type IPluginDBService struct { + Name string + DBType string + Host string + Port string + User string + Business string + SQLERuleTemplateName string + SQLERuleTemplateId string + // TODO: more +} + +type Plugin struct { + // 插件名称 + Name string `json:"name" validate:"required"` + // 添加数据源预检查接口地址, 如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/services/precheck/add + AddDBServicePreCheckUrl string `json:"add_db_service_pre_check_url"` + // 删除数据源预检查接口地址, 如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/services/precheck/del + DelDBServicePreCheckUrl string `json:"del_db_service_pre_check_url"` + // 删除用户预检查接口地址,如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/users/precheck/del + DelUserPreCheckUrl string `json:"del_user_pre_check_url"` + // 删除用户组预检查接口地址,如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/usergroups/precheck/del + DelUserGroupPreCheckUrl string `json:"del_user_group_pre_check_url"` + // 操作资源处理接口地址,如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/data_resource_operate/handle + OperateDataResourceHandleUrl string `json:"operate_data_resource_handle_url"` +} + +// swagger:parameters RegisterDMSPlugin +type RegisterDMSPluginReq struct { + // Register dms plugin + // in:body + Plugin *Plugin `json:"plugin" validate:"required"` +} + +func (u *RegisterDMSPluginReq) String() string { + if u == nil { + return "RegisterDMSPluginReq{nil}" + } + return fmt.Sprintf("RegisterDMSPluginReq{Name:%s}", u.Plugin.Name) +} + +// swagger:model RegisterDMSPluginReply +type RegisterDMSPluginReply struct { + // Generic reply + base.GenericResp +} + +// swagger:parameters AddDBServicePreCheck +type AddDBServicePreCheckReq struct { + // Check if dms can add db service + // in:body + DBService *IPluginDBService `json:"db_service" validate:"required"` +} + +func (u *AddDBServicePreCheckReq) String() string { + if u == nil { + return "AddDBServicePreCheckReq{nil}" + } + return fmt.Sprintf("AddDBServicePreCheckReq{Name:%s,DBType:%s Host:%s}", u.DBService.Name, u.DBService.DBType, u.DBService.Host) +} + +// swagger:model AddDBServicePreCheckReply +type AddDBServicePreCheckReply struct { + // Generic reply + base.GenericResp +} + +// swagger:parameters DelDBServicePreCheck +type DelDBServicePreCheckReq struct { + // Check if dms can del db service + // in:body + DBServiceUid string `json:"db_service_uid" validate:"required"` +} + +func (u *DelDBServicePreCheckReq) String() string { + if u == nil { + return "DelDBServicePreCheckReq{nil}" + } + return fmt.Sprintf("DelDBServicePreCheckReq{Uid:%s}", u.DBServiceUid) +} + +// swagger:model DelDBServicePreCheckReply +type DelDBServicePreCheckReply struct { + // Generic reply + base.GenericResp +} + +// swagger:parameters DelUserPreCheck +type DelUserPreCheckReq struct { + // Check if dms can del db service + // in:body + UserUid string `json:"user_uid" validate:"required"` +} + +func (u *DelUserPreCheckReq) String() string { + if u == nil { + return "DelUserPreCheckReq{nil}" + } + return fmt.Sprintf("DelUserPreCheckReq{Uid:%s}", u.UserUid) +} + +// swagger:model DelUserPreCheckReply +type DelUserPreCheckReply struct { + // Generic reply + base.GenericResp +} + +// swagger:parameters DelUserGroupPreCheck +type DelUserGroupPreCheckReq struct { + // Check if dms can del db service + // in:body + UserGroupUid string `json:"user_group_uid" validate:"required"` +} + +func (u *DelUserGroupPreCheckReq) String() string { + if u == nil { + return "DelUserGroupPreCheckReq{nil}" + } + return fmt.Sprintf("DelUserGroupPreCheckReq{Uid:%s}", u.UserGroupUid) +} + +// swagger:model DelUserGroupPreCheckReply +type DelUserGroupPreCheckReply struct { + // Generic reply + base.GenericResp +} + +// swagger:enum DataResourceType +type DataResourceType string + +const ( + DataResourceTypeDBService DataResourceType = "db_service" + DataResourceTypeProject DataResourceType = "project" + DataResourceTypeUser DataResourceType = "user" + DataResourceTypeUserGroup DataResourceType = "user_group" +) + +// swagger:enum OperationType +type OperationType string + +const ( + OperationTypeCreate OperationType = "create" + OperationTypeUpdate OperationType = "update" + OperationTypeDelete OperationType = "delete" +) + +// swagger:enum OperationTimingType +type OperationTimingType string + +const ( + OperationTimingTypeBefore OperationTimingType = "before" + OperationTimingAfter OperationTimingType = "after" +) + +// swagger:parameters OperateDataResourceHandle +type OperateDataResourceHandleReq struct { + DataResourceUid string `json:"data_resource_uid"` + DataResourceType DataResourceType `json:"data_resource_type"` + OperationType OperationType `json:"operation_type"` + OperationTiming OperationTimingType `json:"operation_timing"` + // TODO ExtraParams need extra params for pre check? +} + +// swagger:model OperateDataResourceHandleReply +type OperateDataResourceHandleReply struct { + // Generic reply + base.GenericResp +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/project.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/project.go new file mode 100644 index 0000000000..50bc89baf2 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/project.go @@ -0,0 +1,58 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + + "github.com/go-openapi/strfmt" +) + +// swagger:parameters ListProjects +type ListProjectReq struct { + // the maximum count of Project to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of Projects to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy ProjectOrderByField `query:"order_by" json:"order_by"` + // filter the Project name + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // filter the Project UID + FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` +} + +// swagger:enum ProjectOrderByField +type ProjectOrderByField string + +const ( + ProjectOrderByName ProjectOrderByField = "name" +) + +// A dms Project +type ListProject struct { + // Project uid + ProjectUid string `json:"uid"` + // Project name + Name string `json:"name"` + // Project is archived + Archived bool `json:"archived"` + // Project desc + Desc string `json:"desc"` + // create user + CreateUser UidWithName `json:"create_user"` + // create time + CreateTime strfmt.DateTime `json:"create_time"` +} + +// swagger:model ListProjectReply +type ListProjectReply struct { + // List project reply + Data []*ListProject `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/proxy.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/proxy.go new file mode 100644 index 0000000000..c43eac183c --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/proxy.go @@ -0,0 +1,32 @@ +package v1 + +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + +// swagger:parameters RegisterDMSProxyTarget +type RegisterDMSProxyTargetReq struct { + // register dms proxy + // in:body + DMSProxyTarget *DMSProxyTarget `json:"dms_proxy_target" validate:"required"` +} + +// A dms proxy target +type DMSProxyTarget struct { + // target name + // Required: true + Name string `json:"name" validate:"required"` + // target addr, eg: http://10.1.2.1:5432 + // Required: true + Addr string `json:"addr" validate:"required,url"` + // version number + // Required: true + Version string `json:"version" validate:"required"` + // url prefix that need to be proxy, eg: /v1/user + // Required: true + ProxyUrlPrefixs []string `json:"proxy_url_prefixs" validate:"required"` +} + +// swagger:model RegisterDMSProxyTargetReply +type RegisterDMSProxyTargetReply struct { + // Generic reply + base.GenericResp +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/router.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/router.go new file mode 100644 index 0000000000..4dcfa8fe17 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/router.go @@ -0,0 +1,87 @@ +package v1 + +import ( + "fmt" + "strings" +) + +// login config +var ( + JwtSigningKey = []byte("secret") +) + +// router +var ( + SessionRouterGroup = "/dms/sessions" + UserRouterGroup = "/dms/users" + DBServiceRouterGroup = "/dms/projects/:project_uid/db_services" + ProxyRouterGroup = "/dms/proxys" + PluginRouterGroup = "/dms/plugins" + MemberRouterGroup = "/dms/projects/:project_uid/members" + ProjectRouterGroup = "/dms/projects" + NotificationRouterGroup = "/dms/notifications" + WebHookRouterGroup = "/dms/webhooks" + MemberForInternalRouterSuffix = "/internal" + InternalDBServiceRouterGroup = "/internal/db_services" +) + +// api group +var ( + GroupV1 = "/v1" + CurrentGroupVersion = GroupV1 +) + +func ResetJWTSigningKey(val string) { + if val != "" { + JwtSigningKey = []byte(val) + } +} + +func GetUserOpPermissionRouter(userUid string) string { + return fmt.Sprintf("%s%s/%s/op_permission", CurrentGroupVersion, UserRouterGroup, userUid) +} + +func GetUserOpPermissionRouterWithoutPrefix(userUid string) string { + router := GetUserOpPermissionRouter(userUid) + return strings.TrimPrefix(strings.TrimPrefix(router, CurrentGroupVersion), UserRouterGroup) +} + +func GetDBServiceRouter(projectUid string) string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, strings.Replace(DBServiceRouterGroup, ":project_uid", projectUid, 1)) +} + +func GetUserRouter(userUid string) string { + return fmt.Sprintf("%s%s/%s", CurrentGroupVersion, UserRouterGroup, userUid) +} + +func GetUsersRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, UserRouterGroup) +} + +func GetListMembersForInternalRouter(projectUid string) string { + return fmt.Sprintf("%s%s%s", CurrentGroupVersion, strings.Replace(MemberRouterGroup, ":project_uid", projectUid, 1), MemberForInternalRouterSuffix) +} + +func GetProxyRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, ProxyRouterGroup) +} + +func GetPluginRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, PluginRouterGroup) +} + +func GetProjectsRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, ProjectRouterGroup) +} + +func GetNotificationRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, NotificationRouterGroup) +} + +func GetWebHooksRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, WebHookRouterGroup) +} + +func GetDBConnectionAbleRouter() string { + return fmt.Sprintf("%s%s/connection", CurrentGroupVersion, InternalDBServiceRouterGroup) +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/user.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/user.go new file mode 100644 index 0000000000..4ce3ac378c --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/user.go @@ -0,0 +1,289 @@ +package v1 + +import ( + "fmt" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +// swagger:parameters GetUser +type GetUserReq struct { + // user uid + // in:path + UserUid string `param:"user_uid" json:"user_uid" validate:"required"` +} + +// A dms user +type GetUser struct { + // user uid + UserUid string `json:"uid"` + // user name + Name string `json:"name"` + // user email + Email string `json:"email"` + // user phone + Phone string `json:"phone"` + // user wxid + WxID string `json:"wxid"` + // user stat + Stat Stat `json:"stat"` + // user authentication type + AuthenticationType UserAuthenticationType `json:"authentication_type"` + // user groups + UserGroups []UidWithName `json:"user_groups"` + // user operation permissions + OpPermissions []UidWithName `json:"op_permissions"` + // is admin + IsAdmin bool `json:"is_admin"` + // user bind name space + UserBindProjects []UserBindProject `json:"user_bind_projects"` +} + +type UserBindProject struct { + ProjectID string `json:"project_id"` + ProjectName string `json:"project_name"` + IsManager bool `json:"is_manager"` +} + +// swagger:enum Stat +type Stat string + +const ( + StatOK Stat = "正常" + StatDisable Stat = "被禁用" + StatUnknown Stat = "未知" +) + +type UidWithName struct { + Uid string `json:"uid"` + Name string `json:"name"` +} + +// swagger:enum UserAuthenticationType +type UserAuthenticationType string + +const ( + UserAuthenticationTypeLDAP UserAuthenticationType = "ldap" // user verify through ldap + UserAuthenticationTypeDMS UserAuthenticationType = "dms" // user verify through dms + UserAuthenticationTypeOAUTH2 UserAuthenticationType = "oauth2" // user verify through oauth2 + UserAuthenticationTypeUnknown UserAuthenticationType = "unknown" +) + +// swagger:model GetUserReply +type GetUserReply struct { + // Get user reply + Data *GetUser `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:parameters GetUserOpPermission +type GetUserOpPermissionReq struct { + // user uid + // in:path + UserUid string `param:"user_uid" json:"user_uid" validate:"required"` + // user op permission info + // in:body + UserOpPermission *UserOpPermission `json:"user_op_permission" validate:"required"` +} + +type UserOpPermission struct { + // uesr project uid + ProjectUid string `json:"project_uid" validate:"required"` +} + +// swagger:model GetUserOpPermissionReply +type GetUserOpPermissionReply struct { + // user op permission reply + // is user admin, admin has all permissions + Data struct { + IsAdmin bool `json:"is_admin"` + // user op permissions + OpPermissionList []OpPermissionItem `json:"op_permission_list"` + } `json:"data"` + // Generic reply + base.GenericResp +} + +type OpPermissionItem struct { + // object uids, object type is defined by RangeType + RangeUids []string `json:"range_uids"` + // object type of RangeUids + RangeType OpRangeType `json:"range_type"` + // op permission type + OpPermissionType OpPermissionType `json:"op_permission_type"` +} + +// swagger:enum OpRangeType +type OpRangeType string + +const ( + OpRangeTypeUnknown OpRangeType = "unknown" + // 全局权限: 该权限只能被用户使用 + OpRangeTypeGlobal OpRangeType = "global" + // 项目权限: 该权限只能被成员使用 + OpRangeTypeProject OpRangeType = "project" + // 项目内的数据源权限: 该权限只能被成员使用 + OpRangeTypeDBService OpRangeType = "db_service" +) + +func ParseOpRangeType(typ string) (OpRangeType, error) { + switch typ { + case string(OpRangeTypeDBService): + return OpRangeTypeDBService, nil + case string(OpRangeTypeProject): + return OpRangeTypeProject, nil + case string(OpRangeTypeGlobal): + return OpRangeTypeGlobal, nil + default: + return "", fmt.Errorf("invalid op range type: %s", typ) + } +} + +// swagger:enum OpPermissionType +type OpPermissionType string + +const ( + OpPermissionTypeUnknown OpPermissionType = "unknown" + // 创建项目;创建项目的用户自动拥有该项目管理权限 + OpPermissionTypeCreateProject OpPermissionType = "create_project" + // 项目管理;拥有该权限的用户可以管理项目下的所有资源 + OpPermissionTypeProjectAdmin OpPermissionType = "project_admin" + // 创建/编辑工单;拥有该权限的用户可以创建/编辑工单 + OpPermissionTypeCreateWorkflow OpPermissionType = "create_workflow" + // 审核/驳回工单;拥有该权限的用户可以审核/驳回工单 + OpPermissionTypeAuditWorkflow OpPermissionType = "audit_workflow" + // 授权数据源数据权限;拥有该权限的用户可以授权数据源数据权限 + OpPermissionTypeAuthDBServiceData OpPermissionType = "auth_db_service_data" + // 查看其他工单权限 + OpPermissionTypeViewOthersWorkflow OpPermissionType = "view_others_workflow" + // 上线工单;拥有该权限的用户可以上线工单 + OpPermissionTypeExecuteWorkflow OpPermissionType = "execute_workflow" + // 查看其他扫描任务权限 + OpPermissionTypeViewOtherAuditPlan OpPermissionType = "view_other_audit_plan" + // 创建扫描任务权限;拥有该权限的用户可以创建/更新扫描任务 + OpPermissionTypeSaveAuditPlan OpPermissionType = "save_audit_plan" + //SQL查询;SQL查询权限 + OpPermissionTypeSQLQuery OpPermissionType = "sql_query" +) + +func ParseOpPermissionType(typ string) (OpPermissionType, error) { + switch typ { + case string(OpPermissionTypeCreateProject): + return OpPermissionTypeCreateProject, nil + case string(OpPermissionTypeProjectAdmin): + return OpPermissionTypeProjectAdmin, nil + case string(OpPermissionTypeCreateWorkflow): + return OpPermissionTypeCreateWorkflow, nil + case string(OpPermissionTypeAuditWorkflow): + return OpPermissionTypeAuditWorkflow, nil + case string(OpPermissionTypeAuthDBServiceData): + return OpPermissionTypeAuthDBServiceData, nil + case string(OpPermissionTypeViewOthersWorkflow): + return OpPermissionTypeViewOthersWorkflow, nil + case string(OpPermissionTypeExecuteWorkflow): + return OpPermissionTypeExecuteWorkflow, nil + case string(OpPermissionTypeViewOtherAuditPlan): + return OpPermissionTypeViewOtherAuditPlan, nil + case string(OpPermissionTypeSaveAuditPlan): + return OpPermissionTypeSaveAuditPlan, nil + case string(OpPermissionTypeSQLQuery): + return OpPermissionTypeSQLQuery, nil + default: + return "", fmt.Errorf("invalid op permission type: %s", typ) + } +} + +func GetOperationTypeDesc(opType OpPermissionType) string { + switch opType { + case OpPermissionTypeUnknown: + return "未知操作类型" + case OpPermissionTypeCreateProject: + return "创建项目" + case OpPermissionTypeProjectAdmin: + return "项目管理" + case OpPermissionTypeCreateWorkflow: + return "创建/编辑工单" + case OpPermissionTypeAuditWorkflow: + return "审核/驳回工单;拥有该权限的用户可以审核/驳回工单" + case OpPermissionTypeAuthDBServiceData: + return "授权数据源数据权限" + case OpPermissionTypeViewOthersWorkflow: + return "查看其他工单权限" + case OpPermissionTypeExecuteWorkflow: + return "上线工单" + case OpPermissionTypeViewOtherAuditPlan: + return "查看其他扫描任务权限" + case OpPermissionTypeSaveAuditPlan: + return "创建扫描任务权限" + case OpPermissionTypeSQLQuery: + return "SQL查询" + default: + return "不支持的操作类型" + } +} + +// swagger:parameters ListUsers +type ListUserReq struct { + // the maximum count of user to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of users to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy UserOrderByField `query:"order_by" json:"order_by"` + // filter the user name + // in:query + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // filter the user uids + // in:query + FilterByUids string `query:"filter_by_uids" json:"filter_by_uids"` + // filter deleted user to be return ,default is false + // in:query + FilterDeletedUser bool `query:"filter_del_user" json:"filter_del_user"` +} + +// swagger:enum UserOrderByField +type UserOrderByField string + +const ( + UserOrderByName UserOrderByField = "name" +) + +// A dms user +type ListUser struct { + // user uid + UserUid string `json:"uid"` + // user name + Name string `json:"name"` + // user email + Email string `json:"email"` + // user phone + Phone string `json:"phone"` + // user wxid + WxID string `json:"wxid"` + // user stat + Stat Stat `json:"stat"` + // user authentication type + AuthenticationType UserAuthenticationType `json:"authentication_type"` + // user groups + UserGroups []UidWithName `json:"user_groups"` + // user operation permissions + OpPermissions []UidWithName `json:"op_permissions"` + // user is deleted + IsDeleted bool `json:"is_deleted"` +} + +// swagger:model ListUserReply +type ListUserReply struct { + // List user reply + Data []*ListUser `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/webhooks.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/webhooks.go new file mode 100644 index 0000000000..ae8ccc2d5b --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/dms/v1/webhooks.go @@ -0,0 +1,27 @@ +package v1 + +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + +type TriggerEventType string + +const ( + TriggerEventTypeWorkflow TriggerEventType = "workflow" +) + +// swagger:parameters WebHookSendMessage +type WebHookSendMessageReq struct { + // webhooks + // in:body + WebHookMessage *WebHooksMessage `json:"webhook_message" validate:"required"` +} + +type WebHooksMessage struct { + Message string `json:"message"` + TriggerEventType TriggerEventType `json:"trigger_event_type"` +} + +// swagger:model WebHookSendMessageReply +type WebHooksSendMessageReply struct { + // Generic reply + base.GenericResp +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/api/jwt/jwt.go b/vendor/github.com/actiontech/dms/pkg/dms-common/api/jwt/jwt.go new file mode 100644 index 0000000000..a05836d47b --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/api/jwt/jwt.go @@ -0,0 +1,199 @@ +package jwt + +import ( + "fmt" + "strconv" + "time" + + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + + jwtOld "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v4" +) + +type EchoContextGetter interface { + // Get retrieves data from the context. + Get(key string) interface{} +} + +type CustomClaimFunc func(claims jwt.MapClaims) + +const ( + JWTUserId = "uid" + JWTUsername = "name" + JWTExpiredTime = "exp" + JWTAuditPlanName = "apn" +) + +func GenJwtToken(customClaims ...CustomClaimFunc) (tokenStr string, err error) { + var mapClaims = jwt.MapClaims{ + "iss": "actiontech dms", + JWTExpiredTime: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), + } + + for _, claimFunc := range customClaims { + claimFunc(mapClaims) + } + // Create token with claims + token := jwt.NewWithClaims(jwt.SigningMethodHS256, mapClaims) + + // Generate encoded token and send it as response. + tokenStr, err = token.SignedString(dmsCommonV1.JwtSigningKey) + if err != nil { + return "", fmt.Errorf("failed to sign the token: %v", err) + } + return tokenStr, nil +} + +func WithUserId(userId string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTUserId] = userId + } +} + +func WithUserName(name string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTUsername] = name + } +} + +func WithAuditPlanName(name string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTAuditPlanName] = name + } +} + +func WithExpiredTime(duration time.Duration) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTExpiredTime] = jwt.NewNumericDate(time.Now().Add(duration)) + } +} + +func ParseUidFromJwtTokenStr(tokenStr string) (uid string, err error) { + token, err := parseJwtTokenStr(tokenStr) + if err != nil { + return "", err + } + + userId, err := ParseUserUidStrFromToken(token) + if err != nil { + return "", fmt.Errorf("get user id from token failed, err: %v", err) + } + + return userId, nil +} + +func parseJwtTokenStr(tokenStr string) (*jwt.Token, error) { + token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) { + if signMethod256, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, jwt.ErrSignatureInvalid + } else if signMethod256 != jwt.SigningMethodHS256 { + return nil, jwt.ErrSignatureInvalid + } + + return dmsCommonV1.JwtSigningKey, nil + }) + + if err != nil { + return nil, fmt.Errorf("parse token failed: %v", err) + } + + return token, nil +} + +// ParseAuditPlanName used by echo middleware which only verify api request to audit plan related. +func ParseAuditPlanName(tokenStr string) (string, error) { + token, err := parseJwtTokenStr(tokenStr) + if err != nil { + return "", err + } + + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + return "", fmt.Errorf("failed to convert token claims to jwt") + } + + auditPlanName, ok := claims[JWTAuditPlanName] + if !ok { + return "", jwt.NewValidationError("unknown token", jwt.ValidationErrorClaimsInvalid) + } + + return fmt.Sprintf("%v", auditPlanName), nil +} + +func GetUserFromContext(c EchoContextGetter) (uid int64, err error) { + if c.Get("user") == nil { + return 0, fmt.Errorf("user not found in context") + } + + // Gets user token from the context. + u, ok := c.Get("user").(*jwt.Token) + if !ok { + return 0, fmt.Errorf("failed to convert user from jwt token") + } + return ParseUserFromToken(u) +} + +func GetUserUidStrFromContext(c EchoContextGetter) (uid string, err error) { + if c.Get("user") == nil { + return "", fmt.Errorf("user not found in context") + } + + // Gets user token from the context. + u, ok := c.Get("user").(*jwt.Token) + if !ok { + return "", fmt.Errorf("failed to convert user from jwt token") + } + return ParseUserUidStrFromToken(u) +} + +// 由于sqle的go版本为1.16,无法使用github.com/golang-jwt/jwt/v4,本方法为sqle兼容 +func GetUserUidStrFromContextWithOldJwt(c EchoContextGetter) (uid string, err error) { + if c.Get("user") == nil { + return "", fmt.Errorf("user not found in context") + } + + // Gets user token from the context. + u, ok := c.Get("user").(*jwtOld.Token) + if !ok { + return "", fmt.Errorf("failed to convert user from jwt token") + } + return ParseUserUidStrFromTokenWithOldJwt(u) +} + +func ParseUserFromToken(token *jwt.Token) (uid int64, err error) { + uidStr, err := ParseUserUidStrFromToken(token) + if err != nil { + return 0, err + } + uid, err = strconv.ParseInt(uidStr, 10, 64) + if err != nil { + return 0, fmt.Errorf("failed to parse user id: %v", err) + } + return uid, nil +} + +func ParseUserUidStrFromToken(token *jwt.Token) (uid string, err error) { + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + return "", fmt.Errorf("failed to convert token claims to jwt") + } + + uidStr := fmt.Sprintf("%v", claims[JWTUserId]) + if uidStr == "" { + return "", fmt.Errorf("failed to parse user id: empty uid") + } + return uidStr, nil +} + +func ParseUserUidStrFromTokenWithOldJwt(token *jwtOld.Token) (uid string, err error) { + claims, ok := token.Claims.(jwtOld.MapClaims) + if !ok { + return "", fmt.Errorf("failed to convert token claims to jwt") + } + uidStr := fmt.Sprintf("%v", claims[JWTUserId]) + if uidStr == "" { + return "", fmt.Errorf("failed to parse user id: empty uid") + } + return uidStr, nil +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/conf/options.go b/vendor/github.com/actiontech/dms/pkg/dms-common/conf/options.go new file mode 100644 index 0000000000..998f3adc54 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/conf/options.go @@ -0,0 +1,25 @@ +package conf + +import "fmt" + +type BaseOptions struct { + ID int64 `yaml:"id" validate:"required"` + APIServiceOpts *APIServerOpts `yaml:"api"` + SecretKey string `yaml:"secret_key"` +} + +type APIServerOpts struct { + Addr string `yaml:"addr" validate:"required"` + Port int `yaml:"port" validate:"required"` + EnableHttps bool `yaml:"enable_https"` + CertFilePath string `yaml:"cert_file_path"` + KeyFilePath string `yaml:"key_file_path"` +} + +func (o *BaseOptions) GetAPIServer() *APIServerOpts { + return o.APIServiceOpts +} + +func (api *APIServerOpts) GetHTTPAddr() string { + return fmt.Sprintf("%v:%v", api.Addr, api.Port) +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/db_service.go b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/db_service.go new file mode 100644 index 0000000000..e28207a76e --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/db_service.go @@ -0,0 +1,29 @@ +package dmsobject + +import ( + "context" + "fmt" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +func ListDbServices(ctx context.Context, dmsAddr string, req dmsV1.ListDBServiceReq) ([]*dmsV1.ListDBService, int64, error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + placeholder := "%s%s?page_size=%d&page_index=%d&order_by=%v&filter_by_business=%s&filter_by_host=%s&filter_by_uid=%s&filter_by_port=%s&filter_by_db_type=%s&filter_by_name=%s" + url := fmt.Sprintf(placeholder, dmsAddr, dmsV1.GetDBServiceRouter(req.ProjectUid), req.PageSize, req.PageIndex, req.OrderBy, req.FilterByBusiness, req.FilterByHost, req.FilterByUID, req.FilterByPort, req.FilterByDBType, req.FilterByName) + + reply := &dmsV1.ListDBServiceReply{} + + if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { + return nil, 0, err + } + if reply.Code != 0 { + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, reply.Total, nil +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/notify.go b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/notify.go new file mode 100644 index 0000000000..9dbe2e9b3c --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/notify.go @@ -0,0 +1,27 @@ +package dmsobject + +import ( + "context" + "fmt" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +func Notify(ctx context.Context, dmsAddr string, req dmsV1.NotificationReq) (err error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reply := &dmsV1.NotificationReply{} + url := fmt.Sprintf("%v%v", dmsAddr, dmsV1.GetNotificationRouter()) + + if err := pkgHttp.POST(ctx, url, header, req, reply); err != nil { + return fmt.Errorf("failed to notify by %v: %v", url, err) + } + if reply.Code != 0 { + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return nil +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/plugin.go b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/plugin.go new file mode 100644 index 0000000000..e1a179ee29 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/plugin.go @@ -0,0 +1,39 @@ +package dmsobject + +import ( + "context" + "reflect" + + "github.com/iancoleman/strcase" +) + +var operateHandlers map[string]OperationHandler = make(map[string]OperationHandler) + +// OperationHandler NOTE: +// The implemented structure must be named[CamelCase] by the combination of DataResourceType, OperationType, and OperationTimingType +type OperationHandler interface { + Handle(ctx context.Context, currentUserId string, objId string) error +} + +type DefaultOperateHandle struct { +} + +func (f DefaultOperateHandle) Handle(ctx context.Context, currentUserId string, objId string) error { + return nil +} + +func InitOperateHandlers(operationHandlers []OperationHandler) { + for _, v := range operationHandlers { + structName := strcase.ToSnake(reflect.TypeOf(v).Name()) + operateHandlers[structName] = v + } +} + +func GetOperateHandle(name string) OperationHandler { + handle, ok := operateHandlers[name] + if ok { + return handle + } + + return DefaultOperateHandle{} +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/project.go b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/project.go new file mode 100644 index 0000000000..2e7d4e8b11 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/project.go @@ -0,0 +1,28 @@ +package dmsobject + +import ( + "context" + "fmt" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +func ListProjects(ctx context.Context, dmsAddr string, req dmsV1.ListProjectReq) (ret []*dmsV1.ListProject, total int64, err error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reply := &dmsV1.ListProjectReply{} + + url := fmt.Sprintf("%v%v?page_size=%v&page_index=%v&filter_by_name=%v&filter_by_uid=%v", dmsAddr, dmsV1.GetProjectsRouter(), req.PageSize, req.PageIndex, req.FilterByName, req.FilterByUID) + + if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { + return nil, 0, fmt.Errorf("failed to list project from %v: %v", url, err) + } + if reply.Code != 0 { + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, reply.Total, nil +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/user.go b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/user.go new file mode 100644 index 0000000000..8325ac1370 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/user.go @@ -0,0 +1,93 @@ +package dmsobject + +import ( + "context" + "fmt" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +func GetUser(ctx context.Context, userUid string, dmsAddr string) (*dmsV1.GetUser, error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reply := &dmsV1.GetUserReply{} + + url := fmt.Sprintf("%v%v", dmsAddr, dmsV1.GetUserRouter(userUid)) + + if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { + return nil, fmt.Errorf("failed to get user from %v: %v", url, err) + } + if reply.Code != 0 { + return nil, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, nil +} + +func GetUserOpPermission(ctx context.Context, projectUid, userUid, dmsAddr string) (ret []dmsV1.OpPermissionItem, isAdmin bool, err error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reqBody := struct { + UserOpPermission *dmsV1.UserOpPermission `json:"user_op_permission"` + }{ + UserOpPermission: &dmsV1.UserOpPermission{ProjectUid: projectUid}, + } + + reply := &dmsV1.GetUserOpPermissionReply{} + + url := fmt.Sprintf("%v%v", dmsAddr, dmsV1.GetUserOpPermissionRouter(userUid)) + + if err := pkgHttp.Get(ctx, url, header, reqBody, reply); err != nil { + return nil, false, fmt.Errorf("failed to get user op permission from %v: %v", url, err) + } + if reply.Code != 0 { + return nil, false, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data.OpPermissionList, reply.Data.IsAdmin, nil + +} + +func ListMembersInProject(ctx context.Context, dmsAddr string, req dmsV1.ListMembersForInternalReq) ([]*dmsV1.ListMembersForInternalItem, int64, error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reply := &dmsV1.ListMembersForInternalReply{} + + url := fmt.Sprintf("%v%v?page_size=%v&page_index=%v", dmsAddr, dmsV1.GetListMembersForInternalRouter(req.ProjectUid), req.PageSize, req.PageIndex) + + if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { + return nil, 0, fmt.Errorf("failed to get member from %v: %v", url, err) + } + if reply.Code != 0 { + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, reply.Total, nil +} + +func ListUsers(ctx context.Context, dmsAddr string, req dmsV1.ListUserReq) (ret []*dmsV1.ListUser, total int64, err error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reply := &dmsV1.ListUserReply{} + + url := fmt.Sprintf("%v%v?page_size=%v&page_index=%v&filter_del_user=%v&filter_by_uids=%v", dmsAddr, dmsV1.GetUsersRouter(), req.PageSize, req.PageIndex, req.FilterDeletedUser, req.FilterByUids) + + if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { + return nil, 0, fmt.Errorf("failed to list users from %v: %v", url, err) + } + if reply.Code != 0 { + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, reply.Total, nil + +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/webhooks.go b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/webhooks.go new file mode 100644 index 0000000000..e8631b2bb4 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/dmsobject/webhooks.go @@ -0,0 +1,27 @@ +package dmsobject + +import ( + "context" + "fmt" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +func WebHookSendMessage(ctx context.Context, dmsAddr string, req *dmsV1.WebHookSendMessageReq) (err error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reply := &dmsV1.NotificationReply{} + url := fmt.Sprintf("%v%v", dmsAddr, dmsV1.GetWebHooksRouter()) + + if err := pkgHttp.POST(ctx, url, header, req, reply); err != nil { + return fmt.Errorf("failed to notify by %v: %v", url, err) + } + if reply.Code != 0 { + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return nil +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/pkg/aes/aes.go b/vendor/github.com/actiontech/dms/pkg/dms-common/pkg/aes/aes.go new file mode 100644 index 0000000000..34ad7e36e7 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/pkg/aes/aes.go @@ -0,0 +1,154 @@ +package aes + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/md5" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "sync" +) + +var SecretKey = []byte("471F77D078C5994BD06B65B8B5B1935B") + +type encryptor struct { + SecretKey []byte + mutex *sync.RWMutex +} + +var std = &encryptor{ + SecretKey: SecretKey, + mutex: &sync.RWMutex{}, +} + +func NewEncryptor(key []byte) *encryptor { + return &encryptor{ + SecretKey: key, + mutex: &sync.RWMutex{}, + } +} + +func ResetAesSecretKey(secret string) error { + if secret == "" { + return nil + } + + return std.SetAesSecretKey([]byte(secret)) +} + +func (e *encryptor) SetAesSecretKey(key []byte) (err error) { + origKey := e.SecretKey + e.SecretKey = key + origData := "test" + var secretData string + defer func() { + if err != nil { + e.SecretKey = origKey + } + }() + if secretData, err = e.AesEncrypt(origData); err != nil { + return + } + if _, err = e.AesDecrypt(secretData); err != nil { + return + } + return +} + +func (e *encryptor) aesEncrypt(origData []byte) ([]byte, error) { + e.mutex.RLock() + key := e.SecretKey + e.mutex.RUnlock() + + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + blockSize := block.BlockSize() + origData = pKCS7Padding(origData, blockSize) + blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) + crypted := make([]byte, len(origData)) + blockMode.CryptBlocks(crypted, origData) + return crypted, nil +} + +func (e *encryptor) aesDecrypt(crypted []byte) ([]byte, error) { + e.mutex.RLock() + key := e.SecretKey + e.mutex.RUnlock() + + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + blockSize := block.BlockSize() + blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) + origData := make([]byte, len(crypted)) + blockMode.CryptBlocks(origData, crypted) + origData = pKCS7UnPadding(origData) + return origData, nil +} + +func (e *encryptor) AesEncrypt(origData string) (string, error) { + crypted, err := e.aesEncrypt([]byte(origData)) + if err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(crypted), nil +} + +func (e *encryptor) AesDecrypt(encrypted string) (string, error) { + encryptedByte, err := base64.StdEncoding.DecodeString(encrypted) + if err != nil { + return "", err + } + origByte, err := e.aesDecrypt(encryptedByte) + return string(origByte), err +} + +func pKCS7Padding(cipherText []byte, blockSize int) []byte { + padding := blockSize - len(cipherText)%blockSize + padText := bytes.Repeat([]byte{byte(padding)}, padding) + return append(cipherText, padText...) +} + +func pKCS7UnPadding(origData []byte) []byte { + length := len(origData) + // if origData is empty, get byte by index length -1 will panic before go 11 + if length <= 0 { + return origData + } + unpadding := int(origData[length-1]) + return origData[:(length - unpadding)] +} + +func AesEncrypt(origData string) (string, error) { + return std.AesEncrypt(origData) +} + +func AesDecrypt(encrypted string) (string, error) { + return std.AesDecrypt(encrypted) +} + +type Password string + +func (p *Password) MarshalJSON() ([]byte, error) { + if *p == "" { + return json.Marshal([]byte(*p)) + } + value, err := AesEncrypt(string(*p)) + if nil != err { + return nil, fmt.Errorf("encrypt error: %v", err) + } + return json.Marshal(value) +} + +func Md5(src string) string { + m := md5.New() + m.Write([]byte(src)) + res := hex.EncodeToString(m.Sum(nil)) + return res +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/pkg/http/http.go b/vendor/github.com/actiontech/dms/pkg/dms-common/pkg/http/http.go new file mode 100644 index 0000000000..380399efdd --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/pkg/http/http.go @@ -0,0 +1,102 @@ +package http + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "time" + + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/api/jwt" +) + +// sys用户长有效期token,有限期至2073年 + +var defaultDMSToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjMyNzI0MjEzNTMsImlzcyI6ImFjdGlvbnRlY2ggZG1zIiwidWlkIjoiNzAwMjAxIn0.45o27vHjHWslarkbovAim6oir3QlrvSDDuzfpGTn6Dk" +var DefaultDMSToken = fmt.Sprintf("Bearer %s", defaultDMSToken) + +func ResetJWTSigningKeyAndDefaultToken(val string) error { + if val == "" { + return nil + } + + uid, err := jwt.ParseUidFromJwtTokenStr(defaultDMSToken) + if err != nil { + return err + } + + // reset jwt singing key + v1.ResetJWTSigningKey(val) + + // expire time: 50 years later + token, err := jwt.GenJwtToken(jwt.WithUserId(uid), jwt.WithExpiredTime(time.Hour*24*365*50)) + if err != nil { + return err + } + + // reset default dms token + resetDefaultDMSToken(token) + + return nil +} + +func resetDefaultDMSToken(token string) { + if token != "" { + DefaultDMSToken = fmt.Sprintf("Bearer %s", token) + } +} + +func Get(ctx context.Context, url string, headers map[string]string, body, out interface{}) error { + return Call(ctx, http.MethodGet, url, headers, body, out) +} + +func POST(ctx context.Context, url string, headers map[string]string, body, out interface{}) error { + return Call(ctx, http.MethodPost, url, headers, body, out) +} + +func Call(ctx context.Context, method, url string, headers map[string]string, body, out interface{}) error { + var bodyReader io.Reader + if body != nil { + bodyJson, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("marshal error: %v", err) + } + bodyReader = bytes.NewReader(bodyJson) + } + + req, err := http.NewRequestWithContext(ctx, method, url, bodyReader) + if err != nil { + return fmt.Errorf("new request error: %v", err) + } + for k, v := range headers { + req.Header.Add(k, v) + } + req.Header.Set("Content-Type", "application/json") + + client := http.Client{ + Timeout: time.Second * 15, + } + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("query data error: %v", err) + } + defer resp.Body.Close() + + result, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("read data error: %v", err) + } + + if resp.StatusCode != 200 { + return fmt.Errorf("query data error: %v;%v", resp.Status, string(result)) + } + + err = json.Unmarshal(result, &out) + if err != nil { + return fmt.Errorf("unmarshal error: %v", err) + } + return nil +} diff --git a/vendor/github.com/actiontech/dms/pkg/dms-common/register/register.go b/vendor/github.com/actiontech/dms/pkg/dms-common/register/register.go new file mode 100644 index 0000000000..c84889b0b2 --- /dev/null +++ b/vendor/github.com/actiontech/dms/pkg/dms-common/register/register.go @@ -0,0 +1,65 @@ +package register + +import ( + "context" + "fmt" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +// RegisterDMSProxyTarget 向DMS注册反向代理,将proxyPrefix开头的请求转发到自身服务 +// eg: name = sqle; url = http://10.1.2.1:5432; proxyPrefix = /v1/sqle 表示要求DMS将/v1/sqle开头的请求转发到sqle服务所在地址 http://10.1.2.1:5432 +func RegisterDMSProxyTarget(ctx context.Context, dmsAddr, targetName, targetAddr, version string, proxyUrlPrefixs []string) error { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + reqBody := struct { + DMSProxyTarget *dmsV1.DMSProxyTarget `json:"dms_proxy_target"` + }{ + DMSProxyTarget: &dmsV1.DMSProxyTarget{ + Name: targetName, + Addr: targetAddr, + Version: version, + ProxyUrlPrefixs: proxyUrlPrefixs, + }, + } + + reply := &dmsV1.RegisterDMSProxyTargetReply{} + + dmsUrl := fmt.Sprintf("%s%s", dmsAddr, dmsV1.GetProxyRouter()) + + if err := pkgHttp.POST(ctx, dmsUrl, header, reqBody, reply); err != nil { + return fmt.Errorf("failed to register dms proxy target %v: %v", dmsUrl, err) + } + if reply.Code != 0 { + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return nil +} + +// RegisterDMSPlugin 向DMS注册校验插件,DMS会在对应操作时调用插件进行校验。注意:注册的插件接口需要服务自己实现 +func RegisterDMSPlugin(ctx context.Context, dmsAddr string, plugin *dmsV1.Plugin) error { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + reqBody := struct { + Plugin *dmsV1.Plugin `json:"plugin"` + }{ + Plugin: plugin, + } + + reply := &dmsV1.RegisterDMSPluginReply{} + + dmsUrl := fmt.Sprintf("%s%s", dmsAddr, dmsV1.GetPluginRouter()) + + if err := pkgHttp.POST(ctx, dmsUrl, header, reqBody, reply); err != nil { + return fmt.Errorf("failed to register dms plugin %v: %v", dmsUrl, err) + } + if reply.Code != 0 { + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return nil +} diff --git a/vendor/github.com/agnivade/levenshtein/.gitignore b/vendor/github.com/agnivade/levenshtein/.gitignore deleted file mode 100644 index 345780a444..0000000000 --- a/vendor/github.com/agnivade/levenshtein/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -coverage.txt -fuzz/fuzz-fuzz.zip -fuzz/corpus/corpus/* -fuzz/corpus/suppressions/* -fuzz/corpus/crashes/* diff --git a/vendor/github.com/agnivade/levenshtein/.travis.yml b/vendor/github.com/agnivade/levenshtein/.travis.yml deleted file mode 100644 index 0873fa983f..0000000000 --- a/vendor/github.com/agnivade/levenshtein/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -language: go - -# See https://travis-ci.community/t/goos-js-goarch-wasm-go-run-fails-panic-newosproc-not-implemented/1651 -#addons: -# chrome: stable - -before_install: -- export GO111MODULE=on - -#install: -#- go get github.com/agnivade/wasmbrowsertest -#- mv $GOPATH/bin/wasmbrowsertest $GOPATH/bin/go_js_wasm_exec -#- export PATH=$GOPATH/bin:$PATH - -go: -- 1.13.x -- 1.14.x -- 1.15.x -- tip - -script: -#- GOOS=js GOARCH=wasm go test -v -- go test -v diff --git a/vendor/github.com/agnivade/levenshtein/License.txt b/vendor/github.com/agnivade/levenshtein/License.txt deleted file mode 100644 index 54b51f4993..0000000000 --- a/vendor/github.com/agnivade/levenshtein/License.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Agniva De Sarker - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/agnivade/levenshtein/Makefile b/vendor/github.com/agnivade/levenshtein/Makefile deleted file mode 100644 index 5f6890d613..0000000000 --- a/vendor/github.com/agnivade/levenshtein/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -all: test install - -install: - go install - -lint: - gofmt -l -s -w . && go vet . && golint -set_exit_status=1 . - -test: # The first 2 go gets are to support older Go versions - go get github.com/arbovm/levenshtein - go get github.com/dgryski/trifles/leven - GO111MODULE=on go test -race -v -coverprofile=coverage.txt -covermode=atomic - -bench: - go test -run=XXX -bench=. -benchmem -count=5 diff --git a/vendor/github.com/agnivade/levenshtein/README.md b/vendor/github.com/agnivade/levenshtein/README.md deleted file mode 100644 index 13c52a2101..0000000000 --- a/vendor/github.com/agnivade/levenshtein/README.md +++ /dev/null @@ -1,80 +0,0 @@ -levenshtein [![Build Status](https://travis-ci.org/agnivade/levenshtein.svg?branch=master)](https://travis-ci.org/agnivade/levenshtein) [![Go Report Card](https://goreportcard.com/badge/github.com/agnivade/levenshtein)](https://goreportcard.com/report/github.com/agnivade/levenshtein) [![PkgGoDev](https://pkg.go.dev/badge/github.com/agnivade/levenshtein)](https://pkg.go.dev/github.com/agnivade/levenshtein) -=========== - -[Go](http://golang.org) package to calculate the [Levenshtein Distance](http://en.wikipedia.org/wiki/Levenshtein_distance) - -The library is fully capable of working with non-ascii strings. But the strings are not normalized. That is left as a user-dependant use case. Please normalize the strings before passing it to the library if you have such a requirement. -- https://blog.golang.org/normalization - -#### Limitation - -As a performance optimization, the library can handle strings only up to 65536 characters (runes). If you need to handle strings larger than that, please pin to version 1.0.3. - -Install -------- - - go get github.com/agnivade/levenshtein - -Example -------- - -```go -package main - -import ( - "fmt" - "github.com/agnivade/levenshtein" -) - -func main() { - s1 := "kitten" - s2 := "sitting" - distance := levenshtein.ComputeDistance(s1, s2) - fmt.Printf("The distance between %s and %s is %d.\n", s1, s2, distance) - // Output: - // The distance between kitten and sitting is 3. -} - -``` - -Benchmarks ----------- - -``` -name time/op -Simple/ASCII-4 330ns ± 2% -Simple/French-4 617ns ± 2% -Simple/Nordic-4 1.16µs ± 4% -Simple/Tibetan-4 1.05µs ± 1% - -name alloc/op -Simple/ASCII-4 96.0B ± 0% -Simple/French-4 128B ± 0% -Simple/Nordic-4 192B ± 0% -Simple/Tibetan-4 144B ± 0% - -name allocs/op -Simple/ASCII-4 1.00 ± 0% -Simple/French-4 1.00 ± 0% -Simple/Nordic-4 1.00 ± 0% -Simple/Tibetan-4 1.00 ± 0% -``` - -Comparisons with other libraries --------------------------------- - -``` -name time/op -Leven/ASCII/agniva-4 353ns ± 1% -Leven/ASCII/arbovm-4 485ns ± 1% -Leven/ASCII/dgryski-4 395ns ± 0% -Leven/French/agniva-4 648ns ± 1% -Leven/French/arbovm-4 791ns ± 0% -Leven/French/dgryski-4 682ns ± 0% -Leven/Nordic/agniva-4 1.28µs ± 1% -Leven/Nordic/arbovm-4 1.52µs ± 1% -Leven/Nordic/dgryski-4 1.32µs ± 1% -Leven/Tibetan/agniva-4 1.12µs ± 1% -Leven/Tibetan/arbovm-4 1.31µs ± 0% -Leven/Tibetan/dgryski-4 1.16µs ± 0% -``` diff --git a/vendor/github.com/agnivade/levenshtein/levenshtein.go b/vendor/github.com/agnivade/levenshtein/levenshtein.go deleted file mode 100644 index f727a66fe7..0000000000 --- a/vendor/github.com/agnivade/levenshtein/levenshtein.go +++ /dev/null @@ -1,89 +0,0 @@ -// Package levenshtein is a Go implementation to calculate Levenshtein Distance. -// -// Implementation taken from -// https://gist.github.com/andrei-m/982927#gistcomment-1931258 -package levenshtein - -import "unicode/utf8" - -// minLengthThreshold is the length of the string beyond which -// an allocation will be made. Strings smaller than this will be -// zero alloc. -const minLengthThreshold = 32 - -// ComputeDistance computes the levenshtein distance between the two -// strings passed as an argument. The return value is the levenshtein distance -// -// Works on runes (Unicode code points) but does not normalize -// the input strings. See https://blog.golang.org/normalization -// and the golang.org/x/text/unicode/norm package. -func ComputeDistance(a, b string) int { - if len(a) == 0 { - return utf8.RuneCountInString(b) - } - - if len(b) == 0 { - return utf8.RuneCountInString(a) - } - - if a == b { - return 0 - } - - // We need to convert to []rune if the strings are non-ASCII. - // This could be avoided by using utf8.RuneCountInString - // and then doing some juggling with rune indices, - // but leads to far more bounds checks. It is a reasonable trade-off. - s1 := []rune(a) - s2 := []rune(b) - - // swap to save some memory O(min(a,b)) instead of O(a) - if len(s1) > len(s2) { - s1, s2 = s2, s1 - } - lenS1 := len(s1) - lenS2 := len(s2) - - // Init the row. - var x []uint16 - if lenS1+1 > minLengthThreshold { - x = make([]uint16, lenS1+1) - } else { - // We make a small optimization here for small strings. - // Because a slice of constant length is effectively an array, - // it does not allocate. So we can re-slice it to the right length - // as long as it is below a desired threshold. - x = make([]uint16, minLengthThreshold) - x = x[:lenS1+1] - } - - // we start from 1 because index 0 is already 0. - for i := 1; i < len(x); i++ { - x[i] = uint16(i) - } - - // make a dummy bounds check to prevent the 2 bounds check down below. - // The one inside the loop is particularly costly. - _ = x[lenS1] - // fill in the rest - for i := 1; i <= lenS2; i++ { - prev := uint16(i) - for j := 1; j <= lenS1; j++ { - current := x[j-1] // match - if s2[i-1] != s1[j-1] { - current = min(min(x[j-1]+1, prev+1), x[j]+1) - } - x[j-1] = prev - prev = current - } - x[lenS1] = prev - } - return int(x[lenS1]) -} - -func min(a, b uint16) uint16 { - if a < b { - return a - } - return b -} diff --git a/vendor/github.com/asaskevich/govalidator/.gitignore b/vendor/github.com/asaskevich/govalidator/.gitignore new file mode 100644 index 0000000000..8d69a9418a --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/.gitignore @@ -0,0 +1,15 @@ +bin/ +.idea/ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + diff --git a/vendor/github.com/asaskevich/govalidator/.travis.yml b/vendor/github.com/asaskevich/govalidator/.travis.yml new file mode 100644 index 0000000000..bb83c6670d --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/.travis.yml @@ -0,0 +1,12 @@ +language: go +dist: xenial +go: + - '1.10' + - '1.11' + - '1.12' + - '1.13' + - 'tip' + +script: + - go test -coverpkg=./... -coverprofile=coverage.info -timeout=5s + - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md b/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..4b462b0d81 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md @@ -0,0 +1,43 @@ +# Contributor Code of Conduct + +This project adheres to [The Code Manifesto](http://codemanifesto.com) +as its guidelines for contributor interactions. + +## The Code Manifesto + +We want to work in an ecosystem that empowers developers to reach their +potential — one that encourages growth and effective collaboration. A space +that is safe for all. + +A space such as this benefits everyone that participates in it. It encourages +new developers to enter our field. It is through discussion and collaboration +that we grow, and through growth that we improve. + +In the effort to create such a place, we hold to these values: + +1. **Discrimination limits us.** This includes discrimination on the basis of + race, gender, sexual orientation, gender identity, age, nationality, + technology and any other arbitrary exclusion of a group of people. +2. **Boundaries honor us.** Your comfort levels are not everyone’s comfort + levels. Remember that, and if brought to your attention, heed it. +3. **We are our biggest assets.** None of us were born masters of our trade. + Each of us has been helped along the way. Return that favor, when and where + you can. +4. **We are resources for the future.** As an extension of #3, share what you + know. Make yourself a resource to help those that come after you. +5. **Respect defines us.** Treat others as you wish to be treated. Make your + discussions, criticisms and debates from a position of respectfulness. Ask + yourself, is it true? Is it necessary? Is it constructive? Anything less is + unacceptable. +6. **Reactions require grace.** Angry responses are valid, but abusive language + and vindictive actions are toxic. When something happens that offends you, + handle it assertively, but be respectful. Escalate reasonably, and try to + allow the offender an opportunity to explain themselves, and possibly + correct the issue. +7. **Opinions are just that: opinions.** Each and every one of us, due to our + background and upbringing, have varying opinions. That is perfectly + acceptable. Remember this: if you respect your own opinions, you should + respect the opinions of others. +8. **To err is human.** You might not intend it, but mistakes do happen and + contribute to build experience. Tolerate honest mistakes, and don't + hesitate to apologize if you make one yourself. diff --git a/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md b/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md new file mode 100644 index 0000000000..7ed268a1ed --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md @@ -0,0 +1,63 @@ +#### Support +If you do have a contribution to the package, feel free to create a Pull Request or an Issue. + +#### What to contribute +If you don't know what to do, there are some features and functions that need to be done + +- [ ] Refactor code +- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check +- [ ] Create actual list of contributors and projects that currently using this package +- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues) +- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions) +- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new +- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc +- [x] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224) +- [ ] Implement fuzzing testing +- [ ] Implement some struct/map/array utilities +- [ ] Implement map/array validation +- [ ] Implement benchmarking +- [ ] Implement batch of examples +- [ ] Look at forks for new features and fixes + +#### Advice +Feel free to create what you want, but keep in mind when you implement new features: +- Code must be clear and readable, names of variables/constants clearly describes what they are doing +- Public functions must be documented and described in source file and added to README.md to the list of available functions +- There are must be unit-tests for any new functions and improvements + +## Financial contributions + +We also welcome financial contributions in full transparency on our [open collective](https://opencollective.com/govalidator). +Anyone can file an expense. If the expense makes sense for the development of the community, it will be "merged" in the ledger of our open collective by the core contributors and the person who filed the expense will be reimbursed. + + +## Credits + + +### Contributors + +Thank you to all the people who have already contributed to govalidator! + + + +### Backers + +Thank you to all our backers! [[Become a backer](https://opencollective.com/govalidator#backer)] + + + + +### Sponsors + +Thank you to all our sponsors! (please ask your company to also support this open source project by [becoming a sponsor](https://opencollective.com/govalidator#sponsor)) + + + + + + + + + + + \ No newline at end of file diff --git a/vendor/github.com/asaskevich/govalidator/LICENSE b/vendor/github.com/asaskevich/govalidator/LICENSE new file mode 100644 index 0000000000..cacba91024 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2020 Alex Saskevich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/asaskevich/govalidator/README.md b/vendor/github.com/asaskevich/govalidator/README.md new file mode 100644 index 0000000000..2c3fc35eb6 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/README.md @@ -0,0 +1,622 @@ +govalidator +=========== +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/asaskevich/govalidator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![GoDoc](https://godoc.org/github.com/asaskevich/govalidator?status.png)](https://godoc.org/github.com/asaskevich/govalidator) +[![Build Status](https://travis-ci.org/asaskevich/govalidator.svg?branch=master)](https://travis-ci.org/asaskevich/govalidator) +[![Coverage](https://codecov.io/gh/asaskevich/govalidator/branch/master/graph/badge.svg)](https://codecov.io/gh/asaskevich/govalidator) [![Go Report Card](https://goreportcard.com/badge/github.com/asaskevich/govalidator)](https://goreportcard.com/report/github.com/asaskevich/govalidator) [![GoSearch](http://go-search.org/badge?id=github.com%2Fasaskevich%2Fgovalidator)](http://go-search.org/view?id=github.com%2Fasaskevich%2Fgovalidator) [![Backers on Open Collective](https://opencollective.com/govalidator/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/govalidator/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_shield) + +A package of validators and sanitizers for strings, structs and collections. Based on [validator.js](https://github.com/chriso/validator.js). + +#### Installation +Make sure that Go is installed on your computer. +Type the following command in your terminal: + + go get github.com/asaskevich/govalidator + +or you can get specified release of the package with `gopkg.in`: + + go get gopkg.in/asaskevich/govalidator.v10 + +After it the package is ready to use. + + +#### Import package in your project +Add following line in your `*.go` file: +```go +import "github.com/asaskevich/govalidator" +``` +If you are unhappy to use long `govalidator`, you can do something like this: +```go +import ( + valid "github.com/asaskevich/govalidator" +) +``` + +#### Activate behavior to require all fields have a validation tag by default +`SetFieldsRequiredByDefault` causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). A good place to activate this is a package init function or the main() function. + +`SetNilPtrAllowedByRequired` causes validation to pass when struct fields marked by `required` are set to nil. This is disabled by default for consistency, but some packages that need to be able to determine between `nil` and `zero value` state can use this. If disabled, both `nil` and `zero` values cause validation errors. + +```go +import "github.com/asaskevich/govalidator" + +func init() { + govalidator.SetFieldsRequiredByDefault(true) +} +``` + +Here's some code to explain it: +```go +// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): +type exampleStruct struct { + Name string `` + Email string `valid:"email"` +} + +// this, however, will only fail when Email is empty or an invalid email address: +type exampleStruct2 struct { + Name string `valid:"-"` + Email string `valid:"email"` +} + +// lastly, this will only fail when Email is an invalid email address but not when it's empty: +type exampleStruct2 struct { + Name string `valid:"-"` + Email string `valid:"email,optional"` +} +``` + +#### Recent breaking changes (see [#123](https://github.com/asaskevich/govalidator/pull/123)) +##### Custom validator function signature +A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible. +```go +import "github.com/asaskevich/govalidator" + +// old signature +func(i interface{}) bool + +// new signature +func(i interface{}, o interface{}) bool +``` + +##### Adding a custom validator +This was changed to prevent data races when accessing custom validators. +```go +import "github.com/asaskevich/govalidator" + +// before +govalidator.CustomTypeTagMap["customByteArrayValidator"] = func(i interface{}, o interface{}) bool { + // ... +} + +// after +govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, o interface{}) bool { + // ... +}) +``` + +#### List of functions: +```go +func Abs(value float64) float64 +func BlackList(str, chars string) string +func ByteLength(str string, params ...string) bool +func CamelCaseToUnderscore(str string) string +func Contains(str, substring string) bool +func Count(array []interface{}, iterator ConditionIterator) int +func Each(array []interface{}, iterator Iterator) +func ErrorByField(e error, field string) string +func ErrorsByField(e error) map[string]string +func Filter(array []interface{}, iterator ConditionIterator) []interface{} +func Find(array []interface{}, iterator ConditionIterator) interface{} +func GetLine(s string, index int) (string, error) +func GetLines(s string) []string +func HasLowerCase(str string) bool +func HasUpperCase(str string) bool +func HasWhitespace(str string) bool +func HasWhitespaceOnly(str string) bool +func InRange(value interface{}, left interface{}, right interface{}) bool +func InRangeFloat32(value, left, right float32) bool +func InRangeFloat64(value, left, right float64) bool +func InRangeInt(value, left, right interface{}) bool +func IsASCII(str string) bool +func IsAlpha(str string) bool +func IsAlphanumeric(str string) bool +func IsBase64(str string) bool +func IsByteLength(str string, min, max int) bool +func IsCIDR(str string) bool +func IsCRC32(str string) bool +func IsCRC32b(str string) bool +func IsCreditCard(str string) bool +func IsDNSName(str string) bool +func IsDataURI(str string) bool +func IsDialString(str string) bool +func IsDivisibleBy(str, num string) bool +func IsEmail(str string) bool +func IsExistingEmail(email string) bool +func IsFilePath(str string) (bool, int) +func IsFloat(str string) bool +func IsFullWidth(str string) bool +func IsHalfWidth(str string) bool +func IsHash(str string, algorithm string) bool +func IsHexadecimal(str string) bool +func IsHexcolor(str string) bool +func IsHost(str string) bool +func IsIP(str string) bool +func IsIPv4(str string) bool +func IsIPv6(str string) bool +func IsISBN(str string, version int) bool +func IsISBN10(str string) bool +func IsISBN13(str string) bool +func IsISO3166Alpha2(str string) bool +func IsISO3166Alpha3(str string) bool +func IsISO4217(str string) bool +func IsISO693Alpha2(str string) bool +func IsISO693Alpha3b(str string) bool +func IsIn(str string, params ...string) bool +func IsInRaw(str string, params ...string) bool +func IsInt(str string) bool +func IsJSON(str string) bool +func IsLatitude(str string) bool +func IsLongitude(str string) bool +func IsLowerCase(str string) bool +func IsMAC(str string) bool +func IsMD4(str string) bool +func IsMD5(str string) bool +func IsMagnetURI(str string) bool +func IsMongoID(str string) bool +func IsMultibyte(str string) bool +func IsNatural(value float64) bool +func IsNegative(value float64) bool +func IsNonNegative(value float64) bool +func IsNonPositive(value float64) bool +func IsNotNull(str string) bool +func IsNull(str string) bool +func IsNumeric(str string) bool +func IsPort(str string) bool +func IsPositive(value float64) bool +func IsPrintableASCII(str string) bool +func IsRFC3339(str string) bool +func IsRFC3339WithoutZone(str string) bool +func IsRGBcolor(str string) bool +func IsRegex(str string) bool +func IsRequestURI(rawurl string) bool +func IsRequestURL(rawurl string) bool +func IsRipeMD128(str string) bool +func IsRipeMD160(str string) bool +func IsRsaPub(str string, params ...string) bool +func IsRsaPublicKey(str string, keylen int) bool +func IsSHA1(str string) bool +func IsSHA256(str string) bool +func IsSHA384(str string) bool +func IsSHA512(str string) bool +func IsSSN(str string) bool +func IsSemver(str string) bool +func IsTiger128(str string) bool +func IsTiger160(str string) bool +func IsTiger192(str string) bool +func IsTime(str string, format string) bool +func IsType(v interface{}, params ...string) bool +func IsURL(str string) bool +func IsUTFDigit(str string) bool +func IsUTFLetter(str string) bool +func IsUTFLetterNumeric(str string) bool +func IsUTFNumeric(str string) bool +func IsUUID(str string) bool +func IsUUIDv3(str string) bool +func IsUUIDv4(str string) bool +func IsUUIDv5(str string) bool +func IsULID(str string) bool +func IsUnixTime(str string) bool +func IsUpperCase(str string) bool +func IsVariableWidth(str string) bool +func IsWhole(value float64) bool +func LeftTrim(str, chars string) string +func Map(array []interface{}, iterator ResultIterator) []interface{} +func Matches(str, pattern string) bool +func MaxStringLength(str string, params ...string) bool +func MinStringLength(str string, params ...string) bool +func NormalizeEmail(str string) (string, error) +func PadBoth(str string, padStr string, padLen int) string +func PadLeft(str string, padStr string, padLen int) string +func PadRight(str string, padStr string, padLen int) string +func PrependPathToErrors(err error, path string) error +func Range(str string, params ...string) bool +func RemoveTags(s string) string +func ReplacePattern(str, pattern, replace string) string +func Reverse(s string) string +func RightTrim(str, chars string) string +func RuneLength(str string, params ...string) bool +func SafeFileName(str string) string +func SetFieldsRequiredByDefault(value bool) +func SetNilPtrAllowedByRequired(value bool) +func Sign(value float64) float64 +func StringLength(str string, params ...string) bool +func StringMatches(s string, params ...string) bool +func StripLow(str string, keepNewLines bool) string +func ToBoolean(str string) (bool, error) +func ToFloat(str string) (float64, error) +func ToInt(value interface{}) (res int64, err error) +func ToJSON(obj interface{}) (string, error) +func ToString(obj interface{}) string +func Trim(str, chars string) string +func Truncate(str string, length int, ending string) string +func TruncatingErrorf(str string, args ...interface{}) error +func UnderscoreToCamelCase(s string) string +func ValidateMap(inputMap map[string]interface{}, validationMap map[string]interface{}) (bool, error) +func ValidateStruct(s interface{}) (bool, error) +func WhiteList(str, chars string) string +type ConditionIterator +type CustomTypeValidator +type Error +func (e Error) Error() string +type Errors +func (es Errors) Error() string +func (es Errors) Errors() []error +type ISO3166Entry +type ISO693Entry +type InterfaceParamValidator +type Iterator +type ParamValidator +type ResultIterator +type UnsupportedTypeError +func (e *UnsupportedTypeError) Error() string +type Validator +``` + +#### Examples +###### IsURL +```go +println(govalidator.IsURL(`http://user@pass:domain.com/path/page`)) +``` +###### IsType +```go +println(govalidator.IsType("Bob", "string")) +println(govalidator.IsType(1, "int")) +i := 1 +println(govalidator.IsType(&i, "*int")) +``` + +IsType can be used through the tag `type` which is essential for map validation: +```go +type User struct { + Name string `valid:"type(string)"` + Age int `valid:"type(int)"` + Meta interface{} `valid:"type(string)"` +} +result, err := govalidator.ValidateStruct(User{"Bob", 20, "meta"}) +if err != nil { + println("error: " + err.Error()) +} +println(result) +``` +###### ToString +```go +type User struct { + FirstName string + LastName string +} + +str := govalidator.ToString(&User{"John", "Juan"}) +println(str) +``` +###### Each, Map, Filter, Count for slices +Each iterates over the slice/array and calls Iterator for every item +```go +data := []interface{}{1, 2, 3, 4, 5} +var fn govalidator.Iterator = func(value interface{}, index int) { + println(value.(int)) +} +govalidator.Each(data, fn) +``` +```go +data := []interface{}{1, 2, 3, 4, 5} +var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} { + return value.(int) * 3 +} +_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15} +``` +```go +data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +var fn govalidator.ConditionIterator = func(value interface{}, index int) bool { + return value.(int)%2 == 0 +} +_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10} +_ = govalidator.Count(data, fn) // result = 5 +``` +###### ValidateStruct [#2](https://github.com/asaskevich/govalidator/pull/2) +If you want to validate structs, you can use tag `valid` for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place `-` in your tag. If you need a validator that is not on the list below, you can add it like this: +```go +govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { + return str == "duck" +}) +``` +For completely custom validators (interface-based), see below. + +Here is a list of available validators for struct fields (validator - used function): +```go +"email": IsEmail, +"url": IsURL, +"dialstring": IsDialString, +"requrl": IsRequestURL, +"requri": IsRequestURI, +"alpha": IsAlpha, +"utfletter": IsUTFLetter, +"alphanum": IsAlphanumeric, +"utfletternum": IsUTFLetterNumeric, +"numeric": IsNumeric, +"utfnumeric": IsUTFNumeric, +"utfdigit": IsUTFDigit, +"hexadecimal": IsHexadecimal, +"hexcolor": IsHexcolor, +"rgbcolor": IsRGBcolor, +"lowercase": IsLowerCase, +"uppercase": IsUpperCase, +"int": IsInt, +"float": IsFloat, +"null": IsNull, +"uuid": IsUUID, +"uuidv3": IsUUIDv3, +"uuidv4": IsUUIDv4, +"uuidv5": IsUUIDv5, +"creditcard": IsCreditCard, +"isbn10": IsISBN10, +"isbn13": IsISBN13, +"json": IsJSON, +"multibyte": IsMultibyte, +"ascii": IsASCII, +"printableascii": IsPrintableASCII, +"fullwidth": IsFullWidth, +"halfwidth": IsHalfWidth, +"variablewidth": IsVariableWidth, +"base64": IsBase64, +"datauri": IsDataURI, +"ip": IsIP, +"port": IsPort, +"ipv4": IsIPv4, +"ipv6": IsIPv6, +"dns": IsDNSName, +"host": IsHost, +"mac": IsMAC, +"latitude": IsLatitude, +"longitude": IsLongitude, +"ssn": IsSSN, +"semver": IsSemver, +"rfc3339": IsRFC3339, +"rfc3339WithoutZone": IsRFC3339WithoutZone, +"ISO3166Alpha2": IsISO3166Alpha2, +"ISO3166Alpha3": IsISO3166Alpha3, +"ulid": IsULID, +``` +Validators with parameters + +```go +"range(min|max)": Range, +"length(min|max)": ByteLength, +"runelength(min|max)": RuneLength, +"stringlength(min|max)": StringLength, +"matches(pattern)": StringMatches, +"in(string1|string2|...|stringN)": IsIn, +"rsapub(keylength)" : IsRsaPub, +"minstringlength(int): MinStringLength, +"maxstringlength(int): MaxStringLength, +``` +Validators with parameters for any type + +```go +"type(type)": IsType, +``` + +And here is small example of usage: +```go +type Post struct { + Title string `valid:"alphanum,required"` + Message string `valid:"duck,ascii"` + Message2 string `valid:"animal(dog)"` + AuthorIP string `valid:"ipv4"` + Date string `valid:"-"` +} +post := &Post{ + Title: "My Example Post", + Message: "duck", + Message2: "dog", + AuthorIP: "123.234.54.3", +} + +// Add your own struct validation tags +govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { + return str == "duck" +}) + +// Add your own struct validation tags with parameter +govalidator.ParamTagMap["animal"] = govalidator.ParamValidator(func(str string, params ...string) bool { + species := params[0] + return str == species +}) +govalidator.ParamTagRegexMap["animal"] = regexp.MustCompile("^animal\\((\\w+)\\)$") + +result, err := govalidator.ValidateStruct(post) +if err != nil { + println("error: " + err.Error()) +} +println(result) +``` +###### ValidateMap [#2](https://github.com/asaskevich/govalidator/pull/338) +If you want to validate maps, you can use the map to be validated and a validation map that contain the same tags used in ValidateStruct, both maps have to be in the form `map[string]interface{}` + +So here is small example of usage: +```go +var mapTemplate = map[string]interface{}{ + "name":"required,alpha", + "family":"required,alpha", + "email":"required,email", + "cell-phone":"numeric", + "address":map[string]interface{}{ + "line1":"required,alphanum", + "line2":"alphanum", + "postal-code":"numeric", + }, +} + +var inputMap = map[string]interface{}{ + "name":"Bob", + "family":"Smith", + "email":"foo@bar.baz", + "address":map[string]interface{}{ + "line1":"", + "line2":"", + "postal-code":"", + }, +} + +result, err := govalidator.ValidateMap(inputMap, mapTemplate) +if err != nil { + println("error: " + err.Error()) +} +println(result) +``` + +###### WhiteList +```go +// Remove all characters from string ignoring characters between "a" and "z" +println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa") +``` + +###### Custom validation functions +Custom validation using your own domain specific validators is also available - here's an example of how to use it: +```go +import "github.com/asaskevich/govalidator" + +type CustomByteArray [6]byte // custom types are supported and can be validated + +type StructWithCustomByteArray struct { + ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence + Email string `valid:"email"` + CustomMinLength int `valid:"-"` +} + +govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, context interface{}) bool { + switch v := context.(type) { // you can type switch on the context interface being validated + case StructWithCustomByteArray: + // you can check and validate against some other field in the context, + // return early or not validate against the context at all – your choice + case SomeOtherType: + // ... + default: + // expecting some other type? Throw/panic here or continue + } + + switch v := i.(type) { // type switch on the struct field being validated + case CustomByteArray: + for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes + if e != 0 { + return true + } + } + } + return false +}) +govalidator.CustomTypeTagMap.Set("customMinLengthValidator", func(i interface{}, context interface{}) bool { + switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation + case StructWithCustomByteArray: + return len(v.ID) >= v.CustomMinLength + } + return false +}) +``` + +###### Loop over Error() +By default .Error() returns all errors in a single String. To access each error you can do this: +```go + if err != nil { + errs := err.(govalidator.Errors).Errors() + for _, e := range errs { + fmt.Println(e.Error()) + } + } +``` + +###### Custom error messages +Custom error messages are supported via annotations by adding the `~` separator - here's an example of how to use it: +```go +type Ticket struct { + Id int64 `json:"id"` + FirstName string `json:"firstname" valid:"required~First name is blank"` +} +``` + +#### Notes +Documentation is available here: [godoc.org](https://godoc.org/github.com/asaskevich/govalidator). +Full information about code coverage is also available here: [govalidator on gocover.io](http://gocover.io/github.com/asaskevich/govalidator). + +#### Support +If you do have a contribution to the package, feel free to create a Pull Request or an Issue. + +#### What to contribute +If you don't know what to do, there are some features and functions that need to be done + +- [ ] Refactor code +- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check +- [ ] Create actual list of contributors and projects that currently using this package +- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues) +- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions) +- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new +- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc +- [x] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224) +- [ ] Implement fuzzing testing +- [ ] Implement some struct/map/array utilities +- [ ] Implement map/array validation +- [ ] Implement benchmarking +- [ ] Implement batch of examples +- [ ] Look at forks for new features and fixes + +#### Advice +Feel free to create what you want, but keep in mind when you implement new features: +- Code must be clear and readable, names of variables/constants clearly describes what they are doing +- Public functions must be documented and described in source file and added to README.md to the list of available functions +- There are must be unit-tests for any new functions and improvements + +## Credits +### Contributors + +This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. + +#### Special thanks to [contributors](https://github.com/asaskevich/govalidator/graphs/contributors) +* [Daniel Lohse](https://github.com/annismckenzie) +* [Attila Oláh](https://github.com/attilaolah) +* [Daniel Korner](https://github.com/Dadie) +* [Steven Wilkin](https://github.com/stevenwilkin) +* [Deiwin Sarjas](https://github.com/deiwin) +* [Noah Shibley](https://github.com/slugmobile) +* [Nathan Davies](https://github.com/nathj07) +* [Matt Sanford](https://github.com/mzsanford) +* [Simon ccl1115](https://github.com/ccl1115) + + + + +### Backers + +Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/govalidator#backer)] + + + + +### Sponsors + +Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/govalidator#sponsor)] + + + + + + + + + + + + + + + +## License +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_large) diff --git a/vendor/github.com/asaskevich/govalidator/arrays.go b/vendor/github.com/asaskevich/govalidator/arrays.go new file mode 100644 index 0000000000..3e1da7cb48 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/arrays.go @@ -0,0 +1,87 @@ +package govalidator + +// Iterator is the function that accepts element of slice/array and its index +type Iterator func(interface{}, int) + +// ResultIterator is the function that accepts element of slice/array and its index and returns any result +type ResultIterator func(interface{}, int) interface{} + +// ConditionIterator is the function that accepts element of slice/array and its index and returns boolean +type ConditionIterator func(interface{}, int) bool + +// ReduceIterator is the function that accepts two element of slice/array and returns result of merging those values +type ReduceIterator func(interface{}, interface{}) interface{} + +// Some validates that any item of array corresponds to ConditionIterator. Returns boolean. +func Some(array []interface{}, iterator ConditionIterator) bool { + res := false + for index, data := range array { + res = res || iterator(data, index) + } + return res +} + +// Every validates that every item of array corresponds to ConditionIterator. Returns boolean. +func Every(array []interface{}, iterator ConditionIterator) bool { + res := true + for index, data := range array { + res = res && iterator(data, index) + } + return res +} + +// Reduce boils down a list of values into a single value by ReduceIterator +func Reduce(array []interface{}, iterator ReduceIterator, initialValue interface{}) interface{} { + for _, data := range array { + initialValue = iterator(initialValue, data) + } + return initialValue +} + +// Each iterates over the slice and apply Iterator to every item +func Each(array []interface{}, iterator Iterator) { + for index, data := range array { + iterator(data, index) + } +} + +// Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result. +func Map(array []interface{}, iterator ResultIterator) []interface{} { + var result = make([]interface{}, len(array)) + for index, data := range array { + result[index] = iterator(data, index) + } + return result +} + +// Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise. +func Find(array []interface{}, iterator ConditionIterator) interface{} { + for index, data := range array { + if iterator(data, index) { + return data + } + } + return nil +} + +// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice. +func Filter(array []interface{}, iterator ConditionIterator) []interface{} { + var result = make([]interface{}, 0) + for index, data := range array { + if iterator(data, index) { + result = append(result, data) + } + } + return result +} + +// Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator. +func Count(array []interface{}, iterator ConditionIterator) int { + count := 0 + for index, data := range array { + if iterator(data, index) { + count = count + 1 + } + } + return count +} diff --git a/vendor/github.com/asaskevich/govalidator/converter.go b/vendor/github.com/asaskevich/govalidator/converter.go new file mode 100644 index 0000000000..d68e990fc2 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/converter.go @@ -0,0 +1,81 @@ +package govalidator + +import ( + "encoding/json" + "fmt" + "reflect" + "strconv" +) + +// ToString convert the input to a string. +func ToString(obj interface{}) string { + res := fmt.Sprintf("%v", obj) + return res +} + +// ToJSON convert the input to a valid JSON string +func ToJSON(obj interface{}) (string, error) { + res, err := json.Marshal(obj) + if err != nil { + res = []byte("") + } + return string(res), err +} + +// ToFloat convert the input string to a float, or 0.0 if the input is not a float. +func ToFloat(value interface{}) (res float64, err error) { + val := reflect.ValueOf(value) + + switch value.(type) { + case int, int8, int16, int32, int64: + res = float64(val.Int()) + case uint, uint8, uint16, uint32, uint64: + res = float64(val.Uint()) + case float32, float64: + res = val.Float() + case string: + res, err = strconv.ParseFloat(val.String(), 64) + if err != nil { + res = 0 + } + default: + err = fmt.Errorf("ToInt: unknown interface type %T", value) + res = 0 + } + + return +} + +// ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. +func ToInt(value interface{}) (res int64, err error) { + val := reflect.ValueOf(value) + + switch value.(type) { + case int, int8, int16, int32, int64: + res = val.Int() + case uint, uint8, uint16, uint32, uint64: + res = int64(val.Uint()) + case float32, float64: + res = int64(val.Float()) + case string: + if IsInt(val.String()) { + res, err = strconv.ParseInt(val.String(), 0, 64) + if err != nil { + res = 0 + } + } else { + err = fmt.Errorf("ToInt: invalid numeric format %g", value) + res = 0 + } + default: + err = fmt.Errorf("ToInt: unknown interface type %T", value) + res = 0 + } + + return +} + +// ToBoolean convert the input string to a boolean. +func ToBoolean(str string) (bool, error) { + return strconv.ParseBool(str) +} diff --git a/vendor/github.com/asaskevich/govalidator/doc.go b/vendor/github.com/asaskevich/govalidator/doc.go new file mode 100644 index 0000000000..55dce62dc8 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/doc.go @@ -0,0 +1,3 @@ +package govalidator + +// A package of validators and sanitizers for strings, structures and collections. diff --git a/vendor/github.com/asaskevich/govalidator/error.go b/vendor/github.com/asaskevich/govalidator/error.go new file mode 100644 index 0000000000..1da2336f47 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/error.go @@ -0,0 +1,47 @@ +package govalidator + +import ( + "sort" + "strings" +) + +// Errors is an array of multiple errors and conforms to the error interface. +type Errors []error + +// Errors returns itself. +func (es Errors) Errors() []error { + return es +} + +func (es Errors) Error() string { + var errs []string + for _, e := range es { + errs = append(errs, e.Error()) + } + sort.Strings(errs) + return strings.Join(errs, ";") +} + +// Error encapsulates a name, an error and whether there's a custom error message or not. +type Error struct { + Name string + Err error + CustomErrorMessageExists bool + + // Validator indicates the name of the validator that failed + Validator string + Path []string +} + +func (e Error) Error() string { + if e.CustomErrorMessageExists { + return e.Err.Error() + } + + errName := e.Name + if len(e.Path) > 0 { + errName = strings.Join(append(e.Path, e.Name), ".") + } + + return errName + ": " + e.Err.Error() +} diff --git a/vendor/github.com/asaskevich/govalidator/numerics.go b/vendor/github.com/asaskevich/govalidator/numerics.go new file mode 100644 index 0000000000..5041d9e868 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/numerics.go @@ -0,0 +1,100 @@ +package govalidator + +import ( + "math" +) + +// Abs returns absolute value of number +func Abs(value float64) float64 { + return math.Abs(value) +} + +// Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise +func Sign(value float64) float64 { + if value > 0 { + return 1 + } else if value < 0 { + return -1 + } else { + return 0 + } +} + +// IsNegative returns true if value < 0 +func IsNegative(value float64) bool { + return value < 0 +} + +// IsPositive returns true if value > 0 +func IsPositive(value float64) bool { + return value > 0 +} + +// IsNonNegative returns true if value >= 0 +func IsNonNegative(value float64) bool { + return value >= 0 +} + +// IsNonPositive returns true if value <= 0 +func IsNonPositive(value float64) bool { + return value <= 0 +} + +// InRangeInt returns true if value lies between left and right border +func InRangeInt(value, left, right interface{}) bool { + value64, _ := ToInt(value) + left64, _ := ToInt(left) + right64, _ := ToInt(right) + if left64 > right64 { + left64, right64 = right64, left64 + } + return value64 >= left64 && value64 <= right64 +} + +// InRangeFloat32 returns true if value lies between left and right border +func InRangeFloat32(value, left, right float32) bool { + if left > right { + left, right = right, left + } + return value >= left && value <= right +} + +// InRangeFloat64 returns true if value lies between left and right border +func InRangeFloat64(value, left, right float64) bool { + if left > right { + left, right = right, left + } + return value >= left && value <= right +} + +// InRange returns true if value lies between left and right border, generic type to handle int, float32, float64 and string. +// All types must the same type. +// False if value doesn't lie in range or if it incompatible or not comparable +func InRange(value interface{}, left interface{}, right interface{}) bool { + switch value.(type) { + case int: + intValue, _ := ToInt(value) + intLeft, _ := ToInt(left) + intRight, _ := ToInt(right) + return InRangeInt(intValue, intLeft, intRight) + case float32, float64: + intValue, _ := ToFloat(value) + intLeft, _ := ToFloat(left) + intRight, _ := ToFloat(right) + return InRangeFloat64(intValue, intLeft, intRight) + case string: + return value.(string) >= left.(string) && value.(string) <= right.(string) + default: + return false + } +} + +// IsWhole returns true if value is whole number +func IsWhole(value float64) bool { + return math.Remainder(value, 1) == 0 +} + +// IsNatural returns true if value is natural number (positive and whole) +func IsNatural(value float64) bool { + return IsWhole(value) && IsPositive(value) +} diff --git a/vendor/github.com/asaskevich/govalidator/patterns.go b/vendor/github.com/asaskevich/govalidator/patterns.go new file mode 100644 index 0000000000..bafc3765ea --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/patterns.go @@ -0,0 +1,113 @@ +package govalidator + +import "regexp" + +// Basic regular expressions for validating strings +const ( + Email string = "^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$" + CreditCard string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$" + ISBN10 string = "^(?:[0-9]{9}X|[0-9]{10})$" + ISBN13 string = "^(?:[0-9]{13})$" + UUID3 string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" + UUID4 string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" + UUID5 string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" + UUID string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + Alpha string = "^[a-zA-Z]+$" + Alphanumeric string = "^[a-zA-Z0-9]+$" + Numeric string = "^[0-9]+$" + Int string = "^(?:[-+]?(?:0|[1-9][0-9]*))$" + Float string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$" + Hexadecimal string = "^[0-9a-fA-F]+$" + Hexcolor string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + RGBcolor string = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$" + ASCII string = "^[\x00-\x7F]+$" + Multibyte string = "[^\x00-\x7F]" + FullWidth string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" + HalfWidth string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" + Base64 string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" + PrintableASCII string = "^[\x20-\x7E]+$" + DataURI string = "^data:.+\\/(.+);base64$" + MagnetURI string = "^magnet:\\?xt=urn:[a-zA-Z0-9]+:[a-zA-Z0-9]{32,40}&dn=.+&tr=.+$" + Latitude string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" + Longitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" + DNSName string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$` + IP string = `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))` + URLSchema string = `((ftp|tcp|udp|wss?|https?):\/\/)` + URLUsername string = `(\S+(:\S*)?@)` + URLPath string = `((\/|\?|#)[^\s]*)` + URLPort string = `(:(\d{1,5}))` + URLIP string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3]|24\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-5]))` + URLSubdomain string = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))` + URL = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$` + SSN string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` + WinPath string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$` + UnixPath string = `^(/[^/\x00]*)+/?$` + WinARPath string = `^(?:(?:[a-zA-Z]:|\\\\[a-z0-9_.$●-]+\\[a-z0-9_.$●-]+)\\|\\?[^\\/:*?"<>|\r\n]+\\?)(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$` + UnixARPath string = `^((\.{0,2}/)?([^/\x00]*))+/?$` + Semver string = "^v?(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$" + tagName string = "valid" + hasLowerCase string = ".*[[:lower:]]" + hasUpperCase string = ".*[[:upper:]]" + hasWhitespace string = ".*[[:space:]]" + hasWhitespaceOnly string = "^[[:space:]]+$" + IMEI string = "^[0-9a-f]{14}$|^\\d{15}$|^\\d{18}$" + IMSI string = "^\\d{14,15}$" + E164 string = `^\+?[1-9]\d{1,14}$` +) + +// Used by IsFilePath func +const ( + // Unknown is unresolved OS type + Unknown = iota + // Win is Windows type + Win + // Unix is *nix OS types + Unix +) + +var ( + userRegexp = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$") + hostRegexp = regexp.MustCompile("^[^\\s]+\\.[^\\s]+$") + userDotRegexp = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})") + rxEmail = regexp.MustCompile(Email) + rxCreditCard = regexp.MustCompile(CreditCard) + rxISBN10 = regexp.MustCompile(ISBN10) + rxISBN13 = regexp.MustCompile(ISBN13) + rxUUID3 = regexp.MustCompile(UUID3) + rxUUID4 = regexp.MustCompile(UUID4) + rxUUID5 = regexp.MustCompile(UUID5) + rxUUID = regexp.MustCompile(UUID) + rxAlpha = regexp.MustCompile(Alpha) + rxAlphanumeric = regexp.MustCompile(Alphanumeric) + rxNumeric = regexp.MustCompile(Numeric) + rxInt = regexp.MustCompile(Int) + rxFloat = regexp.MustCompile(Float) + rxHexadecimal = regexp.MustCompile(Hexadecimal) + rxHexcolor = regexp.MustCompile(Hexcolor) + rxRGBcolor = regexp.MustCompile(RGBcolor) + rxASCII = regexp.MustCompile(ASCII) + rxPrintableASCII = regexp.MustCompile(PrintableASCII) + rxMultibyte = regexp.MustCompile(Multibyte) + rxFullWidth = regexp.MustCompile(FullWidth) + rxHalfWidth = regexp.MustCompile(HalfWidth) + rxBase64 = regexp.MustCompile(Base64) + rxDataURI = regexp.MustCompile(DataURI) + rxMagnetURI = regexp.MustCompile(MagnetURI) + rxLatitude = regexp.MustCompile(Latitude) + rxLongitude = regexp.MustCompile(Longitude) + rxDNSName = regexp.MustCompile(DNSName) + rxURL = regexp.MustCompile(URL) + rxSSN = regexp.MustCompile(SSN) + rxWinPath = regexp.MustCompile(WinPath) + rxUnixPath = regexp.MustCompile(UnixPath) + rxARWinPath = regexp.MustCompile(WinARPath) + rxARUnixPath = regexp.MustCompile(UnixARPath) + rxSemver = regexp.MustCompile(Semver) + rxHasLowerCase = regexp.MustCompile(hasLowerCase) + rxHasUpperCase = regexp.MustCompile(hasUpperCase) + rxHasWhitespace = regexp.MustCompile(hasWhitespace) + rxHasWhitespaceOnly = regexp.MustCompile(hasWhitespaceOnly) + rxIMEI = regexp.MustCompile(IMEI) + rxIMSI = regexp.MustCompile(IMSI) + rxE164 = regexp.MustCompile(E164) +) diff --git a/vendor/github.com/asaskevich/govalidator/types.go b/vendor/github.com/asaskevich/govalidator/types.go new file mode 100644 index 0000000000..c573abb51a --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/types.go @@ -0,0 +1,656 @@ +package govalidator + +import ( + "reflect" + "regexp" + "sort" + "sync" +) + +// Validator is a wrapper for a validator function that returns bool and accepts string. +type Validator func(str string) bool + +// CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type. +// The second parameter should be the context (in the case of validating a struct: the whole object being validated). +type CustomTypeValidator func(i interface{}, o interface{}) bool + +// ParamValidator is a wrapper for validator functions that accept additional parameters. +type ParamValidator func(str string, params ...string) bool + +// InterfaceParamValidator is a wrapper for functions that accept variants parameters for an interface value +type InterfaceParamValidator func(in interface{}, params ...string) bool +type tagOptionsMap map[string]tagOption + +func (t tagOptionsMap) orderedKeys() []string { + var keys []string + for k := range t { + keys = append(keys, k) + } + + sort.Slice(keys, func(a, b int) bool { + return t[keys[a]].order < t[keys[b]].order + }) + + return keys +} + +type tagOption struct { + name string + customErrorMessage string + order int +} + +// UnsupportedTypeError is a wrapper for reflect.Type +type UnsupportedTypeError struct { + Type reflect.Type +} + +// stringValues is a slice of reflect.Value holding *reflect.StringValue. +// It implements the methods to sort by string. +type stringValues []reflect.Value + +// InterfaceParamTagMap is a map of functions accept variants parameters for an interface value +var InterfaceParamTagMap = map[string]InterfaceParamValidator{ + "type": IsType, +} + +// InterfaceParamTagRegexMap maps interface param tags to their respective regexes. +var InterfaceParamTagRegexMap = map[string]*regexp.Regexp{ + "type": regexp.MustCompile(`^type\((.*)\)$`), +} + +// ParamTagMap is a map of functions accept variants parameters +var ParamTagMap = map[string]ParamValidator{ + "length": ByteLength, + "range": Range, + "runelength": RuneLength, + "stringlength": StringLength, + "matches": StringMatches, + "in": IsInRaw, + "rsapub": IsRsaPub, + "minstringlength": MinStringLength, + "maxstringlength": MaxStringLength, +} + +// ParamTagRegexMap maps param tags to their respective regexes. +var ParamTagRegexMap = map[string]*regexp.Regexp{ + "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"), + "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"), + "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"), + "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"), + "in": regexp.MustCompile(`^in\((.*)\)`), + "matches": regexp.MustCompile(`^matches\((.+)\)$`), + "rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"), + "minstringlength": regexp.MustCompile("^minstringlength\\((\\d+)\\)$"), + "maxstringlength": regexp.MustCompile("^maxstringlength\\((\\d+)\\)$"), +} + +type customTypeTagMap struct { + validators map[string]CustomTypeValidator + + sync.RWMutex +} + +func (tm *customTypeTagMap) Get(name string) (CustomTypeValidator, bool) { + tm.RLock() + defer tm.RUnlock() + v, ok := tm.validators[name] + return v, ok +} + +func (tm *customTypeTagMap) Set(name string, ctv CustomTypeValidator) { + tm.Lock() + defer tm.Unlock() + tm.validators[name] = ctv +} + +// CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function. +// Use this to validate compound or custom types that need to be handled as a whole, e.g. +// `type UUID [16]byte` (this would be handled as an array of bytes). +var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)} + +// TagMap is a map of functions, that can be used as tags for ValidateStruct function. +var TagMap = map[string]Validator{ + "email": IsEmail, + "url": IsURL, + "dialstring": IsDialString, + "requrl": IsRequestURL, + "requri": IsRequestURI, + "alpha": IsAlpha, + "utfletter": IsUTFLetter, + "alphanum": IsAlphanumeric, + "utfletternum": IsUTFLetterNumeric, + "numeric": IsNumeric, + "utfnumeric": IsUTFNumeric, + "utfdigit": IsUTFDigit, + "hexadecimal": IsHexadecimal, + "hexcolor": IsHexcolor, + "rgbcolor": IsRGBcolor, + "lowercase": IsLowerCase, + "uppercase": IsUpperCase, + "int": IsInt, + "float": IsFloat, + "null": IsNull, + "notnull": IsNotNull, + "uuid": IsUUID, + "uuidv3": IsUUIDv3, + "uuidv4": IsUUIDv4, + "uuidv5": IsUUIDv5, + "creditcard": IsCreditCard, + "isbn10": IsISBN10, + "isbn13": IsISBN13, + "json": IsJSON, + "multibyte": IsMultibyte, + "ascii": IsASCII, + "printableascii": IsPrintableASCII, + "fullwidth": IsFullWidth, + "halfwidth": IsHalfWidth, + "variablewidth": IsVariableWidth, + "base64": IsBase64, + "datauri": IsDataURI, + "ip": IsIP, + "port": IsPort, + "ipv4": IsIPv4, + "ipv6": IsIPv6, + "dns": IsDNSName, + "host": IsHost, + "mac": IsMAC, + "latitude": IsLatitude, + "longitude": IsLongitude, + "ssn": IsSSN, + "semver": IsSemver, + "rfc3339": IsRFC3339, + "rfc3339WithoutZone": IsRFC3339WithoutZone, + "ISO3166Alpha2": IsISO3166Alpha2, + "ISO3166Alpha3": IsISO3166Alpha3, + "ISO4217": IsISO4217, + "IMEI": IsIMEI, + "ulid": IsULID, +} + +// ISO3166Entry stores country codes +type ISO3166Entry struct { + EnglishShortName string + FrenchShortName string + Alpha2Code string + Alpha3Code string + Numeric string +} + +//ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes" +var ISO3166List = []ISO3166Entry{ + {"Afghanistan", "Afghanistan (l')", "AF", "AFG", "004"}, + {"Albania", "Albanie (l')", "AL", "ALB", "008"}, + {"Antarctica", "Antarctique (l')", "AQ", "ATA", "010"}, + {"Algeria", "Algérie (l')", "DZ", "DZA", "012"}, + {"American Samoa", "Samoa américaines (les)", "AS", "ASM", "016"}, + {"Andorra", "Andorre (l')", "AD", "AND", "020"}, + {"Angola", "Angola (l')", "AO", "AGO", "024"}, + {"Antigua and Barbuda", "Antigua-et-Barbuda", "AG", "ATG", "028"}, + {"Azerbaijan", "Azerbaïdjan (l')", "AZ", "AZE", "031"}, + {"Argentina", "Argentine (l')", "AR", "ARG", "032"}, + {"Australia", "Australie (l')", "AU", "AUS", "036"}, + {"Austria", "Autriche (l')", "AT", "AUT", "040"}, + {"Bahamas (the)", "Bahamas (les)", "BS", "BHS", "044"}, + {"Bahrain", "Bahreïn", "BH", "BHR", "048"}, + {"Bangladesh", "Bangladesh (le)", "BD", "BGD", "050"}, + {"Armenia", "Arménie (l')", "AM", "ARM", "051"}, + {"Barbados", "Barbade (la)", "BB", "BRB", "052"}, + {"Belgium", "Belgique (la)", "BE", "BEL", "056"}, + {"Bermuda", "Bermudes (les)", "BM", "BMU", "060"}, + {"Bhutan", "Bhoutan (le)", "BT", "BTN", "064"}, + {"Bolivia (Plurinational State of)", "Bolivie (État plurinational de)", "BO", "BOL", "068"}, + {"Bosnia and Herzegovina", "Bosnie-Herzégovine (la)", "BA", "BIH", "070"}, + {"Botswana", "Botswana (le)", "BW", "BWA", "072"}, + {"Bouvet Island", "Bouvet (l'Île)", "BV", "BVT", "074"}, + {"Brazil", "Brésil (le)", "BR", "BRA", "076"}, + {"Belize", "Belize (le)", "BZ", "BLZ", "084"}, + {"British Indian Ocean Territory (the)", "Indien (le Territoire britannique de l'océan)", "IO", "IOT", "086"}, + {"Solomon Islands", "Salomon (Îles)", "SB", "SLB", "090"}, + {"Virgin Islands (British)", "Vierges britanniques (les Îles)", "VG", "VGB", "092"}, + {"Brunei Darussalam", "Brunéi Darussalam (le)", "BN", "BRN", "096"}, + {"Bulgaria", "Bulgarie (la)", "BG", "BGR", "100"}, + {"Myanmar", "Myanmar (le)", "MM", "MMR", "104"}, + {"Burundi", "Burundi (le)", "BI", "BDI", "108"}, + {"Belarus", "Bélarus (le)", "BY", "BLR", "112"}, + {"Cambodia", "Cambodge (le)", "KH", "KHM", "116"}, + {"Cameroon", "Cameroun (le)", "CM", "CMR", "120"}, + {"Canada", "Canada (le)", "CA", "CAN", "124"}, + {"Cabo Verde", "Cabo Verde", "CV", "CPV", "132"}, + {"Cayman Islands (the)", "Caïmans (les Îles)", "KY", "CYM", "136"}, + {"Central African Republic (the)", "République centrafricaine (la)", "CF", "CAF", "140"}, + {"Sri Lanka", "Sri Lanka", "LK", "LKA", "144"}, + {"Chad", "Tchad (le)", "TD", "TCD", "148"}, + {"Chile", "Chili (le)", "CL", "CHL", "152"}, + {"China", "Chine (la)", "CN", "CHN", "156"}, + {"Taiwan (Province of China)", "Taïwan (Province de Chine)", "TW", "TWN", "158"}, + {"Christmas Island", "Christmas (l'Île)", "CX", "CXR", "162"}, + {"Cocos (Keeling) Islands (the)", "Cocos (les Îles)/ Keeling (les Îles)", "CC", "CCK", "166"}, + {"Colombia", "Colombie (la)", "CO", "COL", "170"}, + {"Comoros (the)", "Comores (les)", "KM", "COM", "174"}, + {"Mayotte", "Mayotte", "YT", "MYT", "175"}, + {"Congo (the)", "Congo (le)", "CG", "COG", "178"}, + {"Congo (the Democratic Republic of the)", "Congo (la République démocratique du)", "CD", "COD", "180"}, + {"Cook Islands (the)", "Cook (les Îles)", "CK", "COK", "184"}, + {"Costa Rica", "Costa Rica (le)", "CR", "CRI", "188"}, + {"Croatia", "Croatie (la)", "HR", "HRV", "191"}, + {"Cuba", "Cuba", "CU", "CUB", "192"}, + {"Cyprus", "Chypre", "CY", "CYP", "196"}, + {"Czech Republic (the)", "tchèque (la République)", "CZ", "CZE", "203"}, + {"Benin", "Bénin (le)", "BJ", "BEN", "204"}, + {"Denmark", "Danemark (le)", "DK", "DNK", "208"}, + {"Dominica", "Dominique (la)", "DM", "DMA", "212"}, + {"Dominican Republic (the)", "dominicaine (la République)", "DO", "DOM", "214"}, + {"Ecuador", "Équateur (l')", "EC", "ECU", "218"}, + {"El Salvador", "El Salvador", "SV", "SLV", "222"}, + {"Equatorial Guinea", "Guinée équatoriale (la)", "GQ", "GNQ", "226"}, + {"Ethiopia", "Éthiopie (l')", "ET", "ETH", "231"}, + {"Eritrea", "Érythrée (l')", "ER", "ERI", "232"}, + {"Estonia", "Estonie (l')", "EE", "EST", "233"}, + {"Faroe Islands (the)", "Féroé (les Îles)", "FO", "FRO", "234"}, + {"Falkland Islands (the) [Malvinas]", "Falkland (les Îles)/Malouines (les Îles)", "FK", "FLK", "238"}, + {"South Georgia and the South Sandwich Islands", "Géorgie du Sud-et-les Îles Sandwich du Sud (la)", "GS", "SGS", "239"}, + {"Fiji", "Fidji (les)", "FJ", "FJI", "242"}, + {"Finland", "Finlande (la)", "FI", "FIN", "246"}, + {"Åland Islands", "Åland(les Îles)", "AX", "ALA", "248"}, + {"France", "France (la)", "FR", "FRA", "250"}, + {"French Guiana", "Guyane française (la )", "GF", "GUF", "254"}, + {"French Polynesia", "Polynésie française (la)", "PF", "PYF", "258"}, + {"French Southern Territories (the)", "Terres australes françaises (les)", "TF", "ATF", "260"}, + {"Djibouti", "Djibouti", "DJ", "DJI", "262"}, + {"Gabon", "Gabon (le)", "GA", "GAB", "266"}, + {"Georgia", "Géorgie (la)", "GE", "GEO", "268"}, + {"Gambia (the)", "Gambie (la)", "GM", "GMB", "270"}, + {"Palestine, State of", "Palestine, État de", "PS", "PSE", "275"}, + {"Germany", "Allemagne (l')", "DE", "DEU", "276"}, + {"Ghana", "Ghana (le)", "GH", "GHA", "288"}, + {"Gibraltar", "Gibraltar", "GI", "GIB", "292"}, + {"Kiribati", "Kiribati", "KI", "KIR", "296"}, + {"Greece", "Grèce (la)", "GR", "GRC", "300"}, + {"Greenland", "Groenland (le)", "GL", "GRL", "304"}, + {"Grenada", "Grenade (la)", "GD", "GRD", "308"}, + {"Guadeloupe", "Guadeloupe (la)", "GP", "GLP", "312"}, + {"Guam", "Guam", "GU", "GUM", "316"}, + {"Guatemala", "Guatemala (le)", "GT", "GTM", "320"}, + {"Guinea", "Guinée (la)", "GN", "GIN", "324"}, + {"Guyana", "Guyana (le)", "GY", "GUY", "328"}, + {"Haiti", "Haïti", "HT", "HTI", "332"}, + {"Heard Island and McDonald Islands", "Heard-et-Îles MacDonald (l'Île)", "HM", "HMD", "334"}, + {"Holy See (the)", "Saint-Siège (le)", "VA", "VAT", "336"}, + {"Honduras", "Honduras (le)", "HN", "HND", "340"}, + {"Hong Kong", "Hong Kong", "HK", "HKG", "344"}, + {"Hungary", "Hongrie (la)", "HU", "HUN", "348"}, + {"Iceland", "Islande (l')", "IS", "ISL", "352"}, + {"India", "Inde (l')", "IN", "IND", "356"}, + {"Indonesia", "Indonésie (l')", "ID", "IDN", "360"}, + {"Iran (Islamic Republic of)", "Iran (République Islamique d')", "IR", "IRN", "364"}, + {"Iraq", "Iraq (l')", "IQ", "IRQ", "368"}, + {"Ireland", "Irlande (l')", "IE", "IRL", "372"}, + {"Israel", "Israël", "IL", "ISR", "376"}, + {"Italy", "Italie (l')", "IT", "ITA", "380"}, + {"Côte d'Ivoire", "Côte d'Ivoire (la)", "CI", "CIV", "384"}, + {"Jamaica", "Jamaïque (la)", "JM", "JAM", "388"}, + {"Japan", "Japon (le)", "JP", "JPN", "392"}, + {"Kazakhstan", "Kazakhstan (le)", "KZ", "KAZ", "398"}, + {"Jordan", "Jordanie (la)", "JO", "JOR", "400"}, + {"Kenya", "Kenya (le)", "KE", "KEN", "404"}, + {"Korea (the Democratic People's Republic of)", "Corée (la République populaire démocratique de)", "KP", "PRK", "408"}, + {"Korea (the Republic of)", "Corée (la République de)", "KR", "KOR", "410"}, + {"Kuwait", "Koweït (le)", "KW", "KWT", "414"}, + {"Kyrgyzstan", "Kirghizistan (le)", "KG", "KGZ", "417"}, + {"Lao People's Democratic Republic (the)", "Lao, République démocratique populaire", "LA", "LAO", "418"}, + {"Lebanon", "Liban (le)", "LB", "LBN", "422"}, + {"Lesotho", "Lesotho (le)", "LS", "LSO", "426"}, + {"Latvia", "Lettonie (la)", "LV", "LVA", "428"}, + {"Liberia", "Libéria (le)", "LR", "LBR", "430"}, + {"Libya", "Libye (la)", "LY", "LBY", "434"}, + {"Liechtenstein", "Liechtenstein (le)", "LI", "LIE", "438"}, + {"Lithuania", "Lituanie (la)", "LT", "LTU", "440"}, + {"Luxembourg", "Luxembourg (le)", "LU", "LUX", "442"}, + {"Macao", "Macao", "MO", "MAC", "446"}, + {"Madagascar", "Madagascar", "MG", "MDG", "450"}, + {"Malawi", "Malawi (le)", "MW", "MWI", "454"}, + {"Malaysia", "Malaisie (la)", "MY", "MYS", "458"}, + {"Maldives", "Maldives (les)", "MV", "MDV", "462"}, + {"Mali", "Mali (le)", "ML", "MLI", "466"}, + {"Malta", "Malte", "MT", "MLT", "470"}, + {"Martinique", "Martinique (la)", "MQ", "MTQ", "474"}, + {"Mauritania", "Mauritanie (la)", "MR", "MRT", "478"}, + {"Mauritius", "Maurice", "MU", "MUS", "480"}, + {"Mexico", "Mexique (le)", "MX", "MEX", "484"}, + {"Monaco", "Monaco", "MC", "MCO", "492"}, + {"Mongolia", "Mongolie (la)", "MN", "MNG", "496"}, + {"Moldova (the Republic of)", "Moldova , République de", "MD", "MDA", "498"}, + {"Montenegro", "Monténégro (le)", "ME", "MNE", "499"}, + {"Montserrat", "Montserrat", "MS", "MSR", "500"}, + {"Morocco", "Maroc (le)", "MA", "MAR", "504"}, + {"Mozambique", "Mozambique (le)", "MZ", "MOZ", "508"}, + {"Oman", "Oman", "OM", "OMN", "512"}, + {"Namibia", "Namibie (la)", "NA", "NAM", "516"}, + {"Nauru", "Nauru", "NR", "NRU", "520"}, + {"Nepal", "Népal (le)", "NP", "NPL", "524"}, + {"Netherlands (the)", "Pays-Bas (les)", "NL", "NLD", "528"}, + {"Curaçao", "Curaçao", "CW", "CUW", "531"}, + {"Aruba", "Aruba", "AW", "ABW", "533"}, + {"Sint Maarten (Dutch part)", "Saint-Martin (partie néerlandaise)", "SX", "SXM", "534"}, + {"Bonaire, Sint Eustatius and Saba", "Bonaire, Saint-Eustache et Saba", "BQ", "BES", "535"}, + {"New Caledonia", "Nouvelle-Calédonie (la)", "NC", "NCL", "540"}, + {"Vanuatu", "Vanuatu (le)", "VU", "VUT", "548"}, + {"New Zealand", "Nouvelle-Zélande (la)", "NZ", "NZL", "554"}, + {"Nicaragua", "Nicaragua (le)", "NI", "NIC", "558"}, + {"Niger (the)", "Niger (le)", "NE", "NER", "562"}, + {"Nigeria", "Nigéria (le)", "NG", "NGA", "566"}, + {"Niue", "Niue", "NU", "NIU", "570"}, + {"Norfolk Island", "Norfolk (l'Île)", "NF", "NFK", "574"}, + {"Norway", "Norvège (la)", "NO", "NOR", "578"}, + {"Northern Mariana Islands (the)", "Mariannes du Nord (les Îles)", "MP", "MNP", "580"}, + {"United States Minor Outlying Islands (the)", "Îles mineures éloignées des États-Unis (les)", "UM", "UMI", "581"}, + {"Micronesia (Federated States of)", "Micronésie (États fédérés de)", "FM", "FSM", "583"}, + {"Marshall Islands (the)", "Marshall (Îles)", "MH", "MHL", "584"}, + {"Palau", "Palaos (les)", "PW", "PLW", "585"}, + {"Pakistan", "Pakistan (le)", "PK", "PAK", "586"}, + {"Panama", "Panama (le)", "PA", "PAN", "591"}, + {"Papua New Guinea", "Papouasie-Nouvelle-Guinée (la)", "PG", "PNG", "598"}, + {"Paraguay", "Paraguay (le)", "PY", "PRY", "600"}, + {"Peru", "Pérou (le)", "PE", "PER", "604"}, + {"Philippines (the)", "Philippines (les)", "PH", "PHL", "608"}, + {"Pitcairn", "Pitcairn", "PN", "PCN", "612"}, + {"Poland", "Pologne (la)", "PL", "POL", "616"}, + {"Portugal", "Portugal (le)", "PT", "PRT", "620"}, + {"Guinea-Bissau", "Guinée-Bissau (la)", "GW", "GNB", "624"}, + {"Timor-Leste", "Timor-Leste (le)", "TL", "TLS", "626"}, + {"Puerto Rico", "Porto Rico", "PR", "PRI", "630"}, + {"Qatar", "Qatar (le)", "QA", "QAT", "634"}, + {"Réunion", "Réunion (La)", "RE", "REU", "638"}, + {"Romania", "Roumanie (la)", "RO", "ROU", "642"}, + {"Russian Federation (the)", "Russie (la Fédération de)", "RU", "RUS", "643"}, + {"Rwanda", "Rwanda (le)", "RW", "RWA", "646"}, + {"Saint Barthélemy", "Saint-Barthélemy", "BL", "BLM", "652"}, + {"Saint Helena, Ascension and Tristan da Cunha", "Sainte-Hélène, Ascension et Tristan da Cunha", "SH", "SHN", "654"}, + {"Saint Kitts and Nevis", "Saint-Kitts-et-Nevis", "KN", "KNA", "659"}, + {"Anguilla", "Anguilla", "AI", "AIA", "660"}, + {"Saint Lucia", "Sainte-Lucie", "LC", "LCA", "662"}, + {"Saint Martin (French part)", "Saint-Martin (partie française)", "MF", "MAF", "663"}, + {"Saint Pierre and Miquelon", "Saint-Pierre-et-Miquelon", "PM", "SPM", "666"}, + {"Saint Vincent and the Grenadines", "Saint-Vincent-et-les Grenadines", "VC", "VCT", "670"}, + {"San Marino", "Saint-Marin", "SM", "SMR", "674"}, + {"Sao Tome and Principe", "Sao Tomé-et-Principe", "ST", "STP", "678"}, + {"Saudi Arabia", "Arabie saoudite (l')", "SA", "SAU", "682"}, + {"Senegal", "Sénégal (le)", "SN", "SEN", "686"}, + {"Serbia", "Serbie (la)", "RS", "SRB", "688"}, + {"Seychelles", "Seychelles (les)", "SC", "SYC", "690"}, + {"Sierra Leone", "Sierra Leone (la)", "SL", "SLE", "694"}, + {"Singapore", "Singapour", "SG", "SGP", "702"}, + {"Slovakia", "Slovaquie (la)", "SK", "SVK", "703"}, + {"Viet Nam", "Viet Nam (le)", "VN", "VNM", "704"}, + {"Slovenia", "Slovénie (la)", "SI", "SVN", "705"}, + {"Somalia", "Somalie (la)", "SO", "SOM", "706"}, + {"South Africa", "Afrique du Sud (l')", "ZA", "ZAF", "710"}, + {"Zimbabwe", "Zimbabwe (le)", "ZW", "ZWE", "716"}, + {"Spain", "Espagne (l')", "ES", "ESP", "724"}, + {"South Sudan", "Soudan du Sud (le)", "SS", "SSD", "728"}, + {"Sudan (the)", "Soudan (le)", "SD", "SDN", "729"}, + {"Western Sahara*", "Sahara occidental (le)*", "EH", "ESH", "732"}, + {"Suriname", "Suriname (le)", "SR", "SUR", "740"}, + {"Svalbard and Jan Mayen", "Svalbard et l'Île Jan Mayen (le)", "SJ", "SJM", "744"}, + {"Swaziland", "Swaziland (le)", "SZ", "SWZ", "748"}, + {"Sweden", "Suède (la)", "SE", "SWE", "752"}, + {"Switzerland", "Suisse (la)", "CH", "CHE", "756"}, + {"Syrian Arab Republic", "République arabe syrienne (la)", "SY", "SYR", "760"}, + {"Tajikistan", "Tadjikistan (le)", "TJ", "TJK", "762"}, + {"Thailand", "Thaïlande (la)", "TH", "THA", "764"}, + {"Togo", "Togo (le)", "TG", "TGO", "768"}, + {"Tokelau", "Tokelau (les)", "TK", "TKL", "772"}, + {"Tonga", "Tonga (les)", "TO", "TON", "776"}, + {"Trinidad and Tobago", "Trinité-et-Tobago (la)", "TT", "TTO", "780"}, + {"United Arab Emirates (the)", "Émirats arabes unis (les)", "AE", "ARE", "784"}, + {"Tunisia", "Tunisie (la)", "TN", "TUN", "788"}, + {"Turkey", "Turquie (la)", "TR", "TUR", "792"}, + {"Turkmenistan", "Turkménistan (le)", "TM", "TKM", "795"}, + {"Turks and Caicos Islands (the)", "Turks-et-Caïcos (les Îles)", "TC", "TCA", "796"}, + {"Tuvalu", "Tuvalu (les)", "TV", "TUV", "798"}, + {"Uganda", "Ouganda (l')", "UG", "UGA", "800"}, + {"Ukraine", "Ukraine (l')", "UA", "UKR", "804"}, + {"Macedonia (the former Yugoslav Republic of)", "Macédoine (l'ex‑République yougoslave de)", "MK", "MKD", "807"}, + {"Egypt", "Égypte (l')", "EG", "EGY", "818"}, + {"United Kingdom of Great Britain and Northern Ireland (the)", "Royaume-Uni de Grande-Bretagne et d'Irlande du Nord (le)", "GB", "GBR", "826"}, + {"Guernsey", "Guernesey", "GG", "GGY", "831"}, + {"Jersey", "Jersey", "JE", "JEY", "832"}, + {"Isle of Man", "Île de Man", "IM", "IMN", "833"}, + {"Tanzania, United Republic of", "Tanzanie, République-Unie de", "TZ", "TZA", "834"}, + {"United States of America (the)", "États-Unis d'Amérique (les)", "US", "USA", "840"}, + {"Virgin Islands (U.S.)", "Vierges des États-Unis (les Îles)", "VI", "VIR", "850"}, + {"Burkina Faso", "Burkina Faso (le)", "BF", "BFA", "854"}, + {"Uruguay", "Uruguay (l')", "UY", "URY", "858"}, + {"Uzbekistan", "Ouzbékistan (l')", "UZ", "UZB", "860"}, + {"Venezuela (Bolivarian Republic of)", "Venezuela (République bolivarienne du)", "VE", "VEN", "862"}, + {"Wallis and Futuna", "Wallis-et-Futuna", "WF", "WLF", "876"}, + {"Samoa", "Samoa (le)", "WS", "WSM", "882"}, + {"Yemen", "Yémen (le)", "YE", "YEM", "887"}, + {"Zambia", "Zambie (la)", "ZM", "ZMB", "894"}, +} + +// ISO4217List is the list of ISO currency codes +var ISO4217List = []string{ + "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", + "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", + "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", + "DJF", "DKK", "DOP", "DZD", + "EGP", "ERN", "ETB", "EUR", + "FJD", "FKP", + "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", + "HKD", "HNL", "HRK", "HTG", "HUF", + "IDR", "ILS", "INR", "IQD", "IRR", "ISK", + "JMD", "JOD", "JPY", + "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", + "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", + "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", + "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", + "OMR", + "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", + "QAR", + "RON", "RSD", "RUB", "RWF", + "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "STN", "SVC", "SYP", "SZL", + "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", + "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UYW", "UZS", + "VEF", "VES", "VND", "VUV", + "WST", + "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA", "XXX", + "YER", + "ZAR", "ZMW", "ZWL", +} + +// ISO693Entry stores ISO language codes +type ISO693Entry struct { + Alpha3bCode string + Alpha2Code string + English string +} + +//ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json +var ISO693List = []ISO693Entry{ + {Alpha3bCode: "aar", Alpha2Code: "aa", English: "Afar"}, + {Alpha3bCode: "abk", Alpha2Code: "ab", English: "Abkhazian"}, + {Alpha3bCode: "afr", Alpha2Code: "af", English: "Afrikaans"}, + {Alpha3bCode: "aka", Alpha2Code: "ak", English: "Akan"}, + {Alpha3bCode: "alb", Alpha2Code: "sq", English: "Albanian"}, + {Alpha3bCode: "amh", Alpha2Code: "am", English: "Amharic"}, + {Alpha3bCode: "ara", Alpha2Code: "ar", English: "Arabic"}, + {Alpha3bCode: "arg", Alpha2Code: "an", English: "Aragonese"}, + {Alpha3bCode: "arm", Alpha2Code: "hy", English: "Armenian"}, + {Alpha3bCode: "asm", Alpha2Code: "as", English: "Assamese"}, + {Alpha3bCode: "ava", Alpha2Code: "av", English: "Avaric"}, + {Alpha3bCode: "ave", Alpha2Code: "ae", English: "Avestan"}, + {Alpha3bCode: "aym", Alpha2Code: "ay", English: "Aymara"}, + {Alpha3bCode: "aze", Alpha2Code: "az", English: "Azerbaijani"}, + {Alpha3bCode: "bak", Alpha2Code: "ba", English: "Bashkir"}, + {Alpha3bCode: "bam", Alpha2Code: "bm", English: "Bambara"}, + {Alpha3bCode: "baq", Alpha2Code: "eu", English: "Basque"}, + {Alpha3bCode: "bel", Alpha2Code: "be", English: "Belarusian"}, + {Alpha3bCode: "ben", Alpha2Code: "bn", English: "Bengali"}, + {Alpha3bCode: "bih", Alpha2Code: "bh", English: "Bihari languages"}, + {Alpha3bCode: "bis", Alpha2Code: "bi", English: "Bislama"}, + {Alpha3bCode: "bos", Alpha2Code: "bs", English: "Bosnian"}, + {Alpha3bCode: "bre", Alpha2Code: "br", English: "Breton"}, + {Alpha3bCode: "bul", Alpha2Code: "bg", English: "Bulgarian"}, + {Alpha3bCode: "bur", Alpha2Code: "my", English: "Burmese"}, + {Alpha3bCode: "cat", Alpha2Code: "ca", English: "Catalan; Valencian"}, + {Alpha3bCode: "cha", Alpha2Code: "ch", English: "Chamorro"}, + {Alpha3bCode: "che", Alpha2Code: "ce", English: "Chechen"}, + {Alpha3bCode: "chi", Alpha2Code: "zh", English: "Chinese"}, + {Alpha3bCode: "chu", Alpha2Code: "cu", English: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"}, + {Alpha3bCode: "chv", Alpha2Code: "cv", English: "Chuvash"}, + {Alpha3bCode: "cor", Alpha2Code: "kw", English: "Cornish"}, + {Alpha3bCode: "cos", Alpha2Code: "co", English: "Corsican"}, + {Alpha3bCode: "cre", Alpha2Code: "cr", English: "Cree"}, + {Alpha3bCode: "cze", Alpha2Code: "cs", English: "Czech"}, + {Alpha3bCode: "dan", Alpha2Code: "da", English: "Danish"}, + {Alpha3bCode: "div", Alpha2Code: "dv", English: "Divehi; Dhivehi; Maldivian"}, + {Alpha3bCode: "dut", Alpha2Code: "nl", English: "Dutch; Flemish"}, + {Alpha3bCode: "dzo", Alpha2Code: "dz", English: "Dzongkha"}, + {Alpha3bCode: "eng", Alpha2Code: "en", English: "English"}, + {Alpha3bCode: "epo", Alpha2Code: "eo", English: "Esperanto"}, + {Alpha3bCode: "est", Alpha2Code: "et", English: "Estonian"}, + {Alpha3bCode: "ewe", Alpha2Code: "ee", English: "Ewe"}, + {Alpha3bCode: "fao", Alpha2Code: "fo", English: "Faroese"}, + {Alpha3bCode: "fij", Alpha2Code: "fj", English: "Fijian"}, + {Alpha3bCode: "fin", Alpha2Code: "fi", English: "Finnish"}, + {Alpha3bCode: "fre", Alpha2Code: "fr", English: "French"}, + {Alpha3bCode: "fry", Alpha2Code: "fy", English: "Western Frisian"}, + {Alpha3bCode: "ful", Alpha2Code: "ff", English: "Fulah"}, + {Alpha3bCode: "geo", Alpha2Code: "ka", English: "Georgian"}, + {Alpha3bCode: "ger", Alpha2Code: "de", English: "German"}, + {Alpha3bCode: "gla", Alpha2Code: "gd", English: "Gaelic; Scottish Gaelic"}, + {Alpha3bCode: "gle", Alpha2Code: "ga", English: "Irish"}, + {Alpha3bCode: "glg", Alpha2Code: "gl", English: "Galician"}, + {Alpha3bCode: "glv", Alpha2Code: "gv", English: "Manx"}, + {Alpha3bCode: "gre", Alpha2Code: "el", English: "Greek, Modern (1453-)"}, + {Alpha3bCode: "grn", Alpha2Code: "gn", English: "Guarani"}, + {Alpha3bCode: "guj", Alpha2Code: "gu", English: "Gujarati"}, + {Alpha3bCode: "hat", Alpha2Code: "ht", English: "Haitian; Haitian Creole"}, + {Alpha3bCode: "hau", Alpha2Code: "ha", English: "Hausa"}, + {Alpha3bCode: "heb", Alpha2Code: "he", English: "Hebrew"}, + {Alpha3bCode: "her", Alpha2Code: "hz", English: "Herero"}, + {Alpha3bCode: "hin", Alpha2Code: "hi", English: "Hindi"}, + {Alpha3bCode: "hmo", Alpha2Code: "ho", English: "Hiri Motu"}, + {Alpha3bCode: "hrv", Alpha2Code: "hr", English: "Croatian"}, + {Alpha3bCode: "hun", Alpha2Code: "hu", English: "Hungarian"}, + {Alpha3bCode: "ibo", Alpha2Code: "ig", English: "Igbo"}, + {Alpha3bCode: "ice", Alpha2Code: "is", English: "Icelandic"}, + {Alpha3bCode: "ido", Alpha2Code: "io", English: "Ido"}, + {Alpha3bCode: "iii", Alpha2Code: "ii", English: "Sichuan Yi; Nuosu"}, + {Alpha3bCode: "iku", Alpha2Code: "iu", English: "Inuktitut"}, + {Alpha3bCode: "ile", Alpha2Code: "ie", English: "Interlingue; Occidental"}, + {Alpha3bCode: "ina", Alpha2Code: "ia", English: "Interlingua (International Auxiliary Language Association)"}, + {Alpha3bCode: "ind", Alpha2Code: "id", English: "Indonesian"}, + {Alpha3bCode: "ipk", Alpha2Code: "ik", English: "Inupiaq"}, + {Alpha3bCode: "ita", Alpha2Code: "it", English: "Italian"}, + {Alpha3bCode: "jav", Alpha2Code: "jv", English: "Javanese"}, + {Alpha3bCode: "jpn", Alpha2Code: "ja", English: "Japanese"}, + {Alpha3bCode: "kal", Alpha2Code: "kl", English: "Kalaallisut; Greenlandic"}, + {Alpha3bCode: "kan", Alpha2Code: "kn", English: "Kannada"}, + {Alpha3bCode: "kas", Alpha2Code: "ks", English: "Kashmiri"}, + {Alpha3bCode: "kau", Alpha2Code: "kr", English: "Kanuri"}, + {Alpha3bCode: "kaz", Alpha2Code: "kk", English: "Kazakh"}, + {Alpha3bCode: "khm", Alpha2Code: "km", English: "Central Khmer"}, + {Alpha3bCode: "kik", Alpha2Code: "ki", English: "Kikuyu; Gikuyu"}, + {Alpha3bCode: "kin", Alpha2Code: "rw", English: "Kinyarwanda"}, + {Alpha3bCode: "kir", Alpha2Code: "ky", English: "Kirghiz; Kyrgyz"}, + {Alpha3bCode: "kom", Alpha2Code: "kv", English: "Komi"}, + {Alpha3bCode: "kon", Alpha2Code: "kg", English: "Kongo"}, + {Alpha3bCode: "kor", Alpha2Code: "ko", English: "Korean"}, + {Alpha3bCode: "kua", Alpha2Code: "kj", English: "Kuanyama; Kwanyama"}, + {Alpha3bCode: "kur", Alpha2Code: "ku", English: "Kurdish"}, + {Alpha3bCode: "lao", Alpha2Code: "lo", English: "Lao"}, + {Alpha3bCode: "lat", Alpha2Code: "la", English: "Latin"}, + {Alpha3bCode: "lav", Alpha2Code: "lv", English: "Latvian"}, + {Alpha3bCode: "lim", Alpha2Code: "li", English: "Limburgan; Limburger; Limburgish"}, + {Alpha3bCode: "lin", Alpha2Code: "ln", English: "Lingala"}, + {Alpha3bCode: "lit", Alpha2Code: "lt", English: "Lithuanian"}, + {Alpha3bCode: "ltz", Alpha2Code: "lb", English: "Luxembourgish; Letzeburgesch"}, + {Alpha3bCode: "lub", Alpha2Code: "lu", English: "Luba-Katanga"}, + {Alpha3bCode: "lug", Alpha2Code: "lg", English: "Ganda"}, + {Alpha3bCode: "mac", Alpha2Code: "mk", English: "Macedonian"}, + {Alpha3bCode: "mah", Alpha2Code: "mh", English: "Marshallese"}, + {Alpha3bCode: "mal", Alpha2Code: "ml", English: "Malayalam"}, + {Alpha3bCode: "mao", Alpha2Code: "mi", English: "Maori"}, + {Alpha3bCode: "mar", Alpha2Code: "mr", English: "Marathi"}, + {Alpha3bCode: "may", Alpha2Code: "ms", English: "Malay"}, + {Alpha3bCode: "mlg", Alpha2Code: "mg", English: "Malagasy"}, + {Alpha3bCode: "mlt", Alpha2Code: "mt", English: "Maltese"}, + {Alpha3bCode: "mon", Alpha2Code: "mn", English: "Mongolian"}, + {Alpha3bCode: "nau", Alpha2Code: "na", English: "Nauru"}, + {Alpha3bCode: "nav", Alpha2Code: "nv", English: "Navajo; Navaho"}, + {Alpha3bCode: "nbl", Alpha2Code: "nr", English: "Ndebele, South; South Ndebele"}, + {Alpha3bCode: "nde", Alpha2Code: "nd", English: "Ndebele, North; North Ndebele"}, + {Alpha3bCode: "ndo", Alpha2Code: "ng", English: "Ndonga"}, + {Alpha3bCode: "nep", Alpha2Code: "ne", English: "Nepali"}, + {Alpha3bCode: "nno", Alpha2Code: "nn", English: "Norwegian Nynorsk; Nynorsk, Norwegian"}, + {Alpha3bCode: "nob", Alpha2Code: "nb", English: "Bokmål, Norwegian; Norwegian Bokmål"}, + {Alpha3bCode: "nor", Alpha2Code: "no", English: "Norwegian"}, + {Alpha3bCode: "nya", Alpha2Code: "ny", English: "Chichewa; Chewa; Nyanja"}, + {Alpha3bCode: "oci", Alpha2Code: "oc", English: "Occitan (post 1500); Provençal"}, + {Alpha3bCode: "oji", Alpha2Code: "oj", English: "Ojibwa"}, + {Alpha3bCode: "ori", Alpha2Code: "or", English: "Oriya"}, + {Alpha3bCode: "orm", Alpha2Code: "om", English: "Oromo"}, + {Alpha3bCode: "oss", Alpha2Code: "os", English: "Ossetian; Ossetic"}, + {Alpha3bCode: "pan", Alpha2Code: "pa", English: "Panjabi; Punjabi"}, + {Alpha3bCode: "per", Alpha2Code: "fa", English: "Persian"}, + {Alpha3bCode: "pli", Alpha2Code: "pi", English: "Pali"}, + {Alpha3bCode: "pol", Alpha2Code: "pl", English: "Polish"}, + {Alpha3bCode: "por", Alpha2Code: "pt", English: "Portuguese"}, + {Alpha3bCode: "pus", Alpha2Code: "ps", English: "Pushto; Pashto"}, + {Alpha3bCode: "que", Alpha2Code: "qu", English: "Quechua"}, + {Alpha3bCode: "roh", Alpha2Code: "rm", English: "Romansh"}, + {Alpha3bCode: "rum", Alpha2Code: "ro", English: "Romanian; Moldavian; Moldovan"}, + {Alpha3bCode: "run", Alpha2Code: "rn", English: "Rundi"}, + {Alpha3bCode: "rus", Alpha2Code: "ru", English: "Russian"}, + {Alpha3bCode: "sag", Alpha2Code: "sg", English: "Sango"}, + {Alpha3bCode: "san", Alpha2Code: "sa", English: "Sanskrit"}, + {Alpha3bCode: "sin", Alpha2Code: "si", English: "Sinhala; Sinhalese"}, + {Alpha3bCode: "slo", Alpha2Code: "sk", English: "Slovak"}, + {Alpha3bCode: "slv", Alpha2Code: "sl", English: "Slovenian"}, + {Alpha3bCode: "sme", Alpha2Code: "se", English: "Northern Sami"}, + {Alpha3bCode: "smo", Alpha2Code: "sm", English: "Samoan"}, + {Alpha3bCode: "sna", Alpha2Code: "sn", English: "Shona"}, + {Alpha3bCode: "snd", Alpha2Code: "sd", English: "Sindhi"}, + {Alpha3bCode: "som", Alpha2Code: "so", English: "Somali"}, + {Alpha3bCode: "sot", Alpha2Code: "st", English: "Sotho, Southern"}, + {Alpha3bCode: "spa", Alpha2Code: "es", English: "Spanish; Castilian"}, + {Alpha3bCode: "srd", Alpha2Code: "sc", English: "Sardinian"}, + {Alpha3bCode: "srp", Alpha2Code: "sr", English: "Serbian"}, + {Alpha3bCode: "ssw", Alpha2Code: "ss", English: "Swati"}, + {Alpha3bCode: "sun", Alpha2Code: "su", English: "Sundanese"}, + {Alpha3bCode: "swa", Alpha2Code: "sw", English: "Swahili"}, + {Alpha3bCode: "swe", Alpha2Code: "sv", English: "Swedish"}, + {Alpha3bCode: "tah", Alpha2Code: "ty", English: "Tahitian"}, + {Alpha3bCode: "tam", Alpha2Code: "ta", English: "Tamil"}, + {Alpha3bCode: "tat", Alpha2Code: "tt", English: "Tatar"}, + {Alpha3bCode: "tel", Alpha2Code: "te", English: "Telugu"}, + {Alpha3bCode: "tgk", Alpha2Code: "tg", English: "Tajik"}, + {Alpha3bCode: "tgl", Alpha2Code: "tl", English: "Tagalog"}, + {Alpha3bCode: "tha", Alpha2Code: "th", English: "Thai"}, + {Alpha3bCode: "tib", Alpha2Code: "bo", English: "Tibetan"}, + {Alpha3bCode: "tir", Alpha2Code: "ti", English: "Tigrinya"}, + {Alpha3bCode: "ton", Alpha2Code: "to", English: "Tonga (Tonga Islands)"}, + {Alpha3bCode: "tsn", Alpha2Code: "tn", English: "Tswana"}, + {Alpha3bCode: "tso", Alpha2Code: "ts", English: "Tsonga"}, + {Alpha3bCode: "tuk", Alpha2Code: "tk", English: "Turkmen"}, + {Alpha3bCode: "tur", Alpha2Code: "tr", English: "Turkish"}, + {Alpha3bCode: "twi", Alpha2Code: "tw", English: "Twi"}, + {Alpha3bCode: "uig", Alpha2Code: "ug", English: "Uighur; Uyghur"}, + {Alpha3bCode: "ukr", Alpha2Code: "uk", English: "Ukrainian"}, + {Alpha3bCode: "urd", Alpha2Code: "ur", English: "Urdu"}, + {Alpha3bCode: "uzb", Alpha2Code: "uz", English: "Uzbek"}, + {Alpha3bCode: "ven", Alpha2Code: "ve", English: "Venda"}, + {Alpha3bCode: "vie", Alpha2Code: "vi", English: "Vietnamese"}, + {Alpha3bCode: "vol", Alpha2Code: "vo", English: "Volapük"}, + {Alpha3bCode: "wel", Alpha2Code: "cy", English: "Welsh"}, + {Alpha3bCode: "wln", Alpha2Code: "wa", English: "Walloon"}, + {Alpha3bCode: "wol", Alpha2Code: "wo", English: "Wolof"}, + {Alpha3bCode: "xho", Alpha2Code: "xh", English: "Xhosa"}, + {Alpha3bCode: "yid", Alpha2Code: "yi", English: "Yiddish"}, + {Alpha3bCode: "yor", Alpha2Code: "yo", English: "Yoruba"}, + {Alpha3bCode: "zha", Alpha2Code: "za", English: "Zhuang; Chuang"}, + {Alpha3bCode: "zul", Alpha2Code: "zu", English: "Zulu"}, +} diff --git a/vendor/github.com/asaskevich/govalidator/utils.go b/vendor/github.com/asaskevich/govalidator/utils.go new file mode 100644 index 0000000000..f4c30f824a --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/utils.go @@ -0,0 +1,270 @@ +package govalidator + +import ( + "errors" + "fmt" + "html" + "math" + "path" + "regexp" + "strings" + "unicode" + "unicode/utf8" +) + +// Contains checks if the string contains the substring. +func Contains(str, substring string) bool { + return strings.Contains(str, substring) +} + +// Matches checks if string matches the pattern (pattern is regular expression) +// In case of error return false +func Matches(str, pattern string) bool { + match, _ := regexp.MatchString(pattern, str) + return match +} + +// LeftTrim trims characters from the left side of the input. +// If second argument is empty, it will remove leading spaces. +func LeftTrim(str, chars string) string { + if chars == "" { + return strings.TrimLeftFunc(str, unicode.IsSpace) + } + r, _ := regexp.Compile("^[" + chars + "]+") + return r.ReplaceAllString(str, "") +} + +// RightTrim trims characters from the right side of the input. +// If second argument is empty, it will remove trailing spaces. +func RightTrim(str, chars string) string { + if chars == "" { + return strings.TrimRightFunc(str, unicode.IsSpace) + } + r, _ := regexp.Compile("[" + chars + "]+$") + return r.ReplaceAllString(str, "") +} + +// Trim trims characters from both sides of the input. +// If second argument is empty, it will remove spaces. +func Trim(str, chars string) string { + return LeftTrim(RightTrim(str, chars), chars) +} + +// WhiteList removes characters that do not appear in the whitelist. +func WhiteList(str, chars string) string { + pattern := "[^" + chars + "]+" + r, _ := regexp.Compile(pattern) + return r.ReplaceAllString(str, "") +} + +// BlackList removes characters that appear in the blacklist. +func BlackList(str, chars string) string { + pattern := "[" + chars + "]+" + r, _ := regexp.Compile(pattern) + return r.ReplaceAllString(str, "") +} + +// StripLow removes characters with a numerical value < 32 and 127, mostly control characters. +// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD). +func StripLow(str string, keepNewLines bool) string { + chars := "" + if keepNewLines { + chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F" + } else { + chars = "\x00-\x1F\x7F" + } + return BlackList(str, chars) +} + +// ReplacePattern replaces regular expression pattern in string +func ReplacePattern(str, pattern, replace string) string { + r, _ := regexp.Compile(pattern) + return r.ReplaceAllString(str, replace) +} + +// Escape replaces <, >, & and " with HTML entities. +var Escape = html.EscapeString + +func addSegment(inrune, segment []rune) []rune { + if len(segment) == 0 { + return inrune + } + if len(inrune) != 0 { + inrune = append(inrune, '_') + } + inrune = append(inrune, segment...) + return inrune +} + +// UnderscoreToCamelCase converts from underscore separated form to camel case form. +// Ex.: my_func => MyFunc +func UnderscoreToCamelCase(s string) string { + return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1) +} + +// CamelCaseToUnderscore converts from camel case form to underscore separated form. +// Ex.: MyFunc => my_func +func CamelCaseToUnderscore(str string) string { + var output []rune + var segment []rune + for _, r := range str { + + // not treat number as separate segment + if !unicode.IsLower(r) && string(r) != "_" && !unicode.IsNumber(r) { + output = addSegment(output, segment) + segment = nil + } + segment = append(segment, unicode.ToLower(r)) + } + output = addSegment(output, segment) + return string(output) +} + +// Reverse returns reversed string +func Reverse(s string) string { + r := []rune(s) + for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { + r[i], r[j] = r[j], r[i] + } + return string(r) +} + +// GetLines splits string by "\n" and return array of lines +func GetLines(s string) []string { + return strings.Split(s, "\n") +} + +// GetLine returns specified line of multiline string +func GetLine(s string, index int) (string, error) { + lines := GetLines(s) + if index < 0 || index >= len(lines) { + return "", errors.New("line index out of bounds") + } + return lines[index], nil +} + +// RemoveTags removes all tags from HTML string +func RemoveTags(s string) string { + return ReplacePattern(s, "<[^>]*>", "") +} + +// SafeFileName returns safe string that can be used in file names +func SafeFileName(str string) string { + name := strings.ToLower(str) + name = path.Clean(path.Base(name)) + name = strings.Trim(name, " ") + separators, err := regexp.Compile(`[ &_=+:]`) + if err == nil { + name = separators.ReplaceAllString(name, "-") + } + legal, err := regexp.Compile(`[^[:alnum:]-.]`) + if err == nil { + name = legal.ReplaceAllString(name, "") + } + for strings.Contains(name, "--") { + name = strings.Replace(name, "--", "-", -1) + } + return name +} + +// NormalizeEmail canonicalize an email address. +// The local part of the email address is lowercased for all domains; the hostname is always lowercased and +// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). +// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and +// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are +// normalized to @gmail.com. +func NormalizeEmail(str string) (string, error) { + if !IsEmail(str) { + return "", fmt.Errorf("%s is not an email", str) + } + parts := strings.Split(str, "@") + parts[0] = strings.ToLower(parts[0]) + parts[1] = strings.ToLower(parts[1]) + if parts[1] == "gmail.com" || parts[1] == "googlemail.com" { + parts[1] = "gmail.com" + parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0] + } + return strings.Join(parts, "@"), nil +} + +// Truncate a string to the closest length without breaking words. +func Truncate(str string, length int, ending string) string { + var aftstr, befstr string + if len(str) > length { + words := strings.Fields(str) + before, present := 0, 0 + for i := range words { + befstr = aftstr + before = present + aftstr = aftstr + words[i] + " " + present = len(aftstr) + if present > length && i != 0 { + if (length - before) < (present - length) { + return Trim(befstr, " /\\.,\"'#!?&@+-") + ending + } + return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending + } + } + } + + return str +} + +// PadLeft pads left side of a string if size of string is less then indicated pad length +func PadLeft(str string, padStr string, padLen int) string { + return buildPadStr(str, padStr, padLen, true, false) +} + +// PadRight pads right side of a string if size of string is less then indicated pad length +func PadRight(str string, padStr string, padLen int) string { + return buildPadStr(str, padStr, padLen, false, true) +} + +// PadBoth pads both sides of a string if size of string is less then indicated pad length +func PadBoth(str string, padStr string, padLen int) string { + return buildPadStr(str, padStr, padLen, true, true) +} + +// PadString either left, right or both sides. +// Note that padding string can be unicode and more then one character +func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { + + // When padded length is less then the current string size + if padLen < utf8.RuneCountInString(str) { + return str + } + + padLen -= utf8.RuneCountInString(str) + + targetLen := padLen + + targetLenLeft := targetLen + targetLenRight := targetLen + if padLeft && padRight { + targetLenLeft = padLen / 2 + targetLenRight = padLen - targetLenLeft + } + + strToRepeatLen := utf8.RuneCountInString(padStr) + + repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) + repeatedString := strings.Repeat(padStr, repeatTimes) + + leftSide := "" + if padLeft { + leftSide = repeatedString[0:targetLenLeft] + } + + rightSide := "" + if padRight { + rightSide = repeatedString[0:targetLenRight] + } + + return leftSide + str + rightSide +} + +// TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object +func TruncatingErrorf(str string, args ...interface{}) error { + n := strings.Count(str, "%s") + return fmt.Errorf(str, args[:n]...) +} diff --git a/vendor/github.com/asaskevich/govalidator/validator.go b/vendor/github.com/asaskevich/govalidator/validator.go new file mode 100644 index 0000000000..c9c4fac065 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/validator.go @@ -0,0 +1,1768 @@ +// Package govalidator is package of validators and sanitizers for strings, structs and collections. +package govalidator + +import ( + "bytes" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "fmt" + "io/ioutil" + "net" + "net/url" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +var ( + fieldsRequiredByDefault bool + nilPtrAllowedByRequired = false + notNumberRegexp = regexp.MustCompile("[^0-9]+") + whiteSpacesAndMinus = regexp.MustCompile(`[\s-]+`) + paramsRegexp = regexp.MustCompile(`\(.*\)$`) +) + +const maxURLRuneCount = 2083 +const minURLRuneCount = 3 +const rfc3339WithoutZone = "2006-01-02T15:04:05" + +// SetFieldsRequiredByDefault causes validation to fail when struct fields +// do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). +// This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): +// type exampleStruct struct { +// Name string `` +// Email string `valid:"email"` +// This, however, will only fail when Email is empty or an invalid email address: +// type exampleStruct2 struct { +// Name string `valid:"-"` +// Email string `valid:"email"` +// Lastly, this will only fail when Email is an invalid email address but not when it's empty: +// type exampleStruct2 struct { +// Name string `valid:"-"` +// Email string `valid:"email,optional"` +func SetFieldsRequiredByDefault(value bool) { + fieldsRequiredByDefault = value +} + +// SetNilPtrAllowedByRequired causes validation to pass for nil ptrs when a field is set to required. +// The validation will still reject ptr fields in their zero value state. Example with this enabled: +// type exampleStruct struct { +// Name *string `valid:"required"` +// With `Name` set to "", this will be considered invalid input and will cause a validation error. +// With `Name` set to nil, this will be considered valid by validation. +// By default this is disabled. +func SetNilPtrAllowedByRequired(value bool) { + nilPtrAllowedByRequired = value +} + +// IsEmail checks if the string is an email. +func IsEmail(str string) bool { + // TODO uppercase letters are not supported + return rxEmail.MatchString(str) +} + +// IsExistingEmail checks if the string is an email of existing domain +func IsExistingEmail(email string) bool { + + if len(email) < 6 || len(email) > 254 { + return false + } + at := strings.LastIndex(email, "@") + if at <= 0 || at > len(email)-3 { + return false + } + user := email[:at] + host := email[at+1:] + if len(user) > 64 { + return false + } + switch host { + case "localhost", "example.com": + return true + } + if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { + return false + } + if _, err := net.LookupMX(host); err != nil { + if _, err := net.LookupIP(host); err != nil { + return false + } + } + + return true +} + +// IsURL checks if the string is an URL. +func IsURL(str string) bool { + if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") { + return false + } + strTemp := str + if strings.Contains(str, ":") && !strings.Contains(str, "://") { + // support no indicated urlscheme but with colon for port number + // http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString + strTemp = "http://" + str + } + u, err := url.Parse(strTemp) + if err != nil { + return false + } + if strings.HasPrefix(u.Host, ".") { + return false + } + if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) { + return false + } + return rxURL.MatchString(str) +} + +// IsRequestURL checks if the string rawurl, assuming +// it was received in an HTTP request, is a valid +// URL confirm to RFC 3986 +func IsRequestURL(rawurl string) bool { + url, err := url.ParseRequestURI(rawurl) + if err != nil { + return false //Couldn't even parse the rawurl + } + if len(url.Scheme) == 0 { + return false //No Scheme found + } + return true +} + +// IsRequestURI checks if the string rawurl, assuming +// it was received in an HTTP request, is an +// absolute URI or an absolute path. +func IsRequestURI(rawurl string) bool { + _, err := url.ParseRequestURI(rawurl) + return err == nil +} + +// IsAlpha checks if the string contains only letters (a-zA-Z). Empty string is valid. +func IsAlpha(str string) bool { + if IsNull(str) { + return true + } + return rxAlpha.MatchString(str) +} + +//IsUTFLetter checks if the string contains only unicode letter characters. +//Similar to IsAlpha but for all languages. Empty string is valid. +func IsUTFLetter(str string) bool { + if IsNull(str) { + return true + } + + for _, c := range str { + if !unicode.IsLetter(c) { + return false + } + } + return true + +} + +// IsAlphanumeric checks if the string contains only letters and numbers. Empty string is valid. +func IsAlphanumeric(str string) bool { + if IsNull(str) { + return true + } + return rxAlphanumeric.MatchString(str) +} + +// IsUTFLetterNumeric checks if the string contains only unicode letters and numbers. Empty string is valid. +func IsUTFLetterNumeric(str string) bool { + if IsNull(str) { + return true + } + for _, c := range str { + if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok + return false + } + } + return true + +} + +// IsNumeric checks if the string contains only numbers. Empty string is valid. +func IsNumeric(str string) bool { + if IsNull(str) { + return true + } + return rxNumeric.MatchString(str) +} + +// IsUTFNumeric checks if the string contains only unicode numbers of any kind. +// Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid. +func IsUTFNumeric(str string) bool { + if IsNull(str) { + return true + } + if strings.IndexAny(str, "+-") > 0 { + return false + } + if len(str) > 1 { + str = strings.TrimPrefix(str, "-") + str = strings.TrimPrefix(str, "+") + } + for _, c := range str { + if !unicode.IsNumber(c) { //numbers && minus sign are ok + return false + } + } + return true + +} + +// IsUTFDigit checks if the string contains only unicode radix-10 decimal digits. Empty string is valid. +func IsUTFDigit(str string) bool { + if IsNull(str) { + return true + } + if strings.IndexAny(str, "+-") > 0 { + return false + } + if len(str) > 1 { + str = strings.TrimPrefix(str, "-") + str = strings.TrimPrefix(str, "+") + } + for _, c := range str { + if !unicode.IsDigit(c) { //digits && minus sign are ok + return false + } + } + return true + +} + +// IsHexadecimal checks if the string is a hexadecimal number. +func IsHexadecimal(str string) bool { + return rxHexadecimal.MatchString(str) +} + +// IsHexcolor checks if the string is a hexadecimal color. +func IsHexcolor(str string) bool { + return rxHexcolor.MatchString(str) +} + +// IsRGBcolor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB). +func IsRGBcolor(str string) bool { + return rxRGBcolor.MatchString(str) +} + +// IsLowerCase checks if the string is lowercase. Empty string is valid. +func IsLowerCase(str string) bool { + if IsNull(str) { + return true + } + return str == strings.ToLower(str) +} + +// IsUpperCase checks if the string is uppercase. Empty string is valid. +func IsUpperCase(str string) bool { + if IsNull(str) { + return true + } + return str == strings.ToUpper(str) +} + +// HasLowerCase checks if the string contains at least 1 lowercase. Empty string is valid. +func HasLowerCase(str string) bool { + if IsNull(str) { + return true + } + return rxHasLowerCase.MatchString(str) +} + +// HasUpperCase checks if the string contains as least 1 uppercase. Empty string is valid. +func HasUpperCase(str string) bool { + if IsNull(str) { + return true + } + return rxHasUpperCase.MatchString(str) +} + +// IsInt checks if the string is an integer. Empty string is valid. +func IsInt(str string) bool { + if IsNull(str) { + return true + } + return rxInt.MatchString(str) +} + +// IsFloat checks if the string is a float. +func IsFloat(str string) bool { + return str != "" && rxFloat.MatchString(str) +} + +// IsDivisibleBy checks if the string is a number that's divisible by another. +// If second argument is not valid integer or zero, it's return false. +// Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero). +func IsDivisibleBy(str, num string) bool { + f, _ := ToFloat(str) + p := int64(f) + q, _ := ToInt(num) + if q == 0 { + return false + } + return (p == 0) || (p%q == 0) +} + +// IsNull checks if the string is null. +func IsNull(str string) bool { + return len(str) == 0 +} + +// IsNotNull checks if the string is not null. +func IsNotNull(str string) bool { + return !IsNull(str) +} + +// HasWhitespaceOnly checks the string only contains whitespace +func HasWhitespaceOnly(str string) bool { + return len(str) > 0 && rxHasWhitespaceOnly.MatchString(str) +} + +// HasWhitespace checks if the string contains any whitespace +func HasWhitespace(str string) bool { + return len(str) > 0 && rxHasWhitespace.MatchString(str) +} + +// IsByteLength checks if the string's length (in bytes) falls in a range. +func IsByteLength(str string, min, max int) bool { + return len(str) >= min && len(str) <= max +} + +// IsUUIDv3 checks if the string is a UUID version 3. +func IsUUIDv3(str string) bool { + return rxUUID3.MatchString(str) +} + +// IsUUIDv4 checks if the string is a UUID version 4. +func IsUUIDv4(str string) bool { + return rxUUID4.MatchString(str) +} + +// IsUUIDv5 checks if the string is a UUID version 5. +func IsUUIDv5(str string) bool { + return rxUUID5.MatchString(str) +} + +// IsUUID checks if the string is a UUID (version 3, 4 or 5). +func IsUUID(str string) bool { + return rxUUID.MatchString(str) +} + +// Byte to index table for O(1) lookups when unmarshaling. +// We use 0xFF as sentinel value for invalid indexes. +var ulidDec = [...]byte{ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, + 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, + 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, + 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, + 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, + 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, + 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, +} + +// EncodedSize is the length of a text encoded ULID. +const ulidEncodedSize = 26 + +// IsULID checks if the string is a ULID. +// +// Implementation got from: +// https://github.com/oklog/ulid (Apache-2.0 License) +// +func IsULID(str string) bool { + // Check if a base32 encoded ULID is the right length. + if len(str) != ulidEncodedSize { + return false + } + + // Check if all the characters in a base32 encoded ULID are part of the + // expected base32 character set. + if ulidDec[str[0]] == 0xFF || + ulidDec[str[1]] == 0xFF || + ulidDec[str[2]] == 0xFF || + ulidDec[str[3]] == 0xFF || + ulidDec[str[4]] == 0xFF || + ulidDec[str[5]] == 0xFF || + ulidDec[str[6]] == 0xFF || + ulidDec[str[7]] == 0xFF || + ulidDec[str[8]] == 0xFF || + ulidDec[str[9]] == 0xFF || + ulidDec[str[10]] == 0xFF || + ulidDec[str[11]] == 0xFF || + ulidDec[str[12]] == 0xFF || + ulidDec[str[13]] == 0xFF || + ulidDec[str[14]] == 0xFF || + ulidDec[str[15]] == 0xFF || + ulidDec[str[16]] == 0xFF || + ulidDec[str[17]] == 0xFF || + ulidDec[str[18]] == 0xFF || + ulidDec[str[19]] == 0xFF || + ulidDec[str[20]] == 0xFF || + ulidDec[str[21]] == 0xFF || + ulidDec[str[22]] == 0xFF || + ulidDec[str[23]] == 0xFF || + ulidDec[str[24]] == 0xFF || + ulidDec[str[25]] == 0xFF { + return false + } + + // Check if the first character in a base32 encoded ULID will overflow. This + // happens because the base32 representation encodes 130 bits, while the + // ULID is only 128 bits. + // + // See https://github.com/oklog/ulid/issues/9 for details. + if str[0] > '7' { + return false + } + return true +} + +// IsCreditCard checks if the string is a credit card. +func IsCreditCard(str string) bool { + sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") + if !rxCreditCard.MatchString(sanitized) { + return false + } + + number, _ := ToInt(sanitized) + number, lastDigit := number / 10, number % 10 + + var sum int64 + for i:=0; number > 0; i++ { + digit := number % 10 + + if i % 2 == 0 { + digit *= 2 + if digit > 9 { + digit -= 9 + } + } + + sum += digit + number = number / 10 + } + + return (sum + lastDigit) % 10 == 0 +} + +// IsISBN10 checks if the string is an ISBN version 10. +func IsISBN10(str string) bool { + return IsISBN(str, 10) +} + +// IsISBN13 checks if the string is an ISBN version 13. +func IsISBN13(str string) bool { + return IsISBN(str, 13) +} + +// IsISBN checks if the string is an ISBN (version 10 or 13). +// If version value is not equal to 10 or 13, it will be checks both variants. +func IsISBN(str string, version int) bool { + sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") + var checksum int32 + var i int32 + if version == 10 { + if !rxISBN10.MatchString(sanitized) { + return false + } + for i = 0; i < 9; i++ { + checksum += (i + 1) * int32(sanitized[i]-'0') + } + if sanitized[9] == 'X' { + checksum += 10 * 10 + } else { + checksum += 10 * int32(sanitized[9]-'0') + } + if checksum%11 == 0 { + return true + } + return false + } else if version == 13 { + if !rxISBN13.MatchString(sanitized) { + return false + } + factor := []int32{1, 3} + for i = 0; i < 12; i++ { + checksum += factor[i%2] * int32(sanitized[i]-'0') + } + return (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0 + } + return IsISBN(str, 10) || IsISBN(str, 13) +} + +// IsJSON checks if the string is valid JSON (note: uses json.Unmarshal). +func IsJSON(str string) bool { + var js json.RawMessage + return json.Unmarshal([]byte(str), &js) == nil +} + +// IsMultibyte checks if the string contains one or more multibyte chars. Empty string is valid. +func IsMultibyte(str string) bool { + if IsNull(str) { + return true + } + return rxMultibyte.MatchString(str) +} + +// IsASCII checks if the string contains ASCII chars only. Empty string is valid. +func IsASCII(str string) bool { + if IsNull(str) { + return true + } + return rxASCII.MatchString(str) +} + +// IsPrintableASCII checks if the string contains printable ASCII chars only. Empty string is valid. +func IsPrintableASCII(str string) bool { + if IsNull(str) { + return true + } + return rxPrintableASCII.MatchString(str) +} + +// IsFullWidth checks if the string contains any full-width chars. Empty string is valid. +func IsFullWidth(str string) bool { + if IsNull(str) { + return true + } + return rxFullWidth.MatchString(str) +} + +// IsHalfWidth checks if the string contains any half-width chars. Empty string is valid. +func IsHalfWidth(str string) bool { + if IsNull(str) { + return true + } + return rxHalfWidth.MatchString(str) +} + +// IsVariableWidth checks if the string contains a mixture of full and half-width chars. Empty string is valid. +func IsVariableWidth(str string) bool { + if IsNull(str) { + return true + } + return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) +} + +// IsBase64 checks if a string is base64 encoded. +func IsBase64(str string) bool { + return rxBase64.MatchString(str) +} + +// IsFilePath checks is a string is Win or Unix file path and returns it's type. +func IsFilePath(str string) (bool, int) { + if rxWinPath.MatchString(str) { + //check windows path limit see: + // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath + if len(str[3:]) > 32767 { + return false, Win + } + return true, Win + } else if rxUnixPath.MatchString(str) { + return true, Unix + } + return false, Unknown +} + +//IsWinFilePath checks both relative & absolute paths in Windows +func IsWinFilePath(str string) bool { + if rxARWinPath.MatchString(str) { + //check windows path limit see: + // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath + if len(str[3:]) > 32767 { + return false + } + return true + } + return false +} + +//IsUnixFilePath checks both relative & absolute paths in Unix +func IsUnixFilePath(str string) bool { + if rxARUnixPath.MatchString(str) { + return true + } + return false +} + +// IsDataURI checks if a string is base64 encoded data URI such as an image +func IsDataURI(str string) bool { + dataURI := strings.Split(str, ",") + if !rxDataURI.MatchString(dataURI[0]) { + return false + } + return IsBase64(dataURI[1]) +} + +// IsMagnetURI checks if a string is valid magnet URI +func IsMagnetURI(str string) bool { + return rxMagnetURI.MatchString(str) +} + +// IsISO3166Alpha2 checks if a string is valid two-letter country code +func IsISO3166Alpha2(str string) bool { + for _, entry := range ISO3166List { + if str == entry.Alpha2Code { + return true + } + } + return false +} + +// IsISO3166Alpha3 checks if a string is valid three-letter country code +func IsISO3166Alpha3(str string) bool { + for _, entry := range ISO3166List { + if str == entry.Alpha3Code { + return true + } + } + return false +} + +// IsISO693Alpha2 checks if a string is valid two-letter language code +func IsISO693Alpha2(str string) bool { + for _, entry := range ISO693List { + if str == entry.Alpha2Code { + return true + } + } + return false +} + +// IsISO693Alpha3b checks if a string is valid three-letter language code +func IsISO693Alpha3b(str string) bool { + for _, entry := range ISO693List { + if str == entry.Alpha3bCode { + return true + } + } + return false +} + +// IsDNSName will validate the given string as a DNS name +func IsDNSName(str string) bool { + if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 { + // constraints already violated + return false + } + return !IsIP(str) && rxDNSName.MatchString(str) +} + +// IsHash checks if a string is a hash of type algorithm. +// Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b'] +func IsHash(str string, algorithm string) bool { + var len string + algo := strings.ToLower(algorithm) + + if algo == "crc32" || algo == "crc32b" { + len = "8" + } else if algo == "md5" || algo == "md4" || algo == "ripemd128" || algo == "tiger128" { + len = "32" + } else if algo == "sha1" || algo == "ripemd160" || algo == "tiger160" { + len = "40" + } else if algo == "tiger192" { + len = "48" + } else if algo == "sha3-224" { + len = "56" + } else if algo == "sha256" || algo == "sha3-256" { + len = "64" + } else if algo == "sha384" || algo == "sha3-384" { + len = "96" + } else if algo == "sha512" || algo == "sha3-512" { + len = "128" + } else { + return false + } + + return Matches(str, "^[a-f0-9]{"+len+"}$") +} + +// IsSHA3224 checks is a string is a SHA3-224 hash. Alias for `IsHash(str, "sha3-224")` +func IsSHA3224(str string) bool { + return IsHash(str, "sha3-224") +} + +// IsSHA3256 checks is a string is a SHA3-256 hash. Alias for `IsHash(str, "sha3-256")` +func IsSHA3256(str string) bool { + return IsHash(str, "sha3-256") +} + +// IsSHA3384 checks is a string is a SHA3-384 hash. Alias for `IsHash(str, "sha3-384")` +func IsSHA3384(str string) bool { + return IsHash(str, "sha3-384") +} + +// IsSHA3512 checks is a string is a SHA3-512 hash. Alias for `IsHash(str, "sha3-512")` +func IsSHA3512(str string) bool { + return IsHash(str, "sha3-512") +} + +// IsSHA512 checks is a string is a SHA512 hash. Alias for `IsHash(str, "sha512")` +func IsSHA512(str string) bool { + return IsHash(str, "sha512") +} + +// IsSHA384 checks is a string is a SHA384 hash. Alias for `IsHash(str, "sha384")` +func IsSHA384(str string) bool { + return IsHash(str, "sha384") +} + +// IsSHA256 checks is a string is a SHA256 hash. Alias for `IsHash(str, "sha256")` +func IsSHA256(str string) bool { + return IsHash(str, "sha256") +} + +// IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(str, "tiger192")` +func IsTiger192(str string) bool { + return IsHash(str, "tiger192") +} + +// IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(str, "tiger160")` +func IsTiger160(str string) bool { + return IsHash(str, "tiger160") +} + +// IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(str, "ripemd160")` +func IsRipeMD160(str string) bool { + return IsHash(str, "ripemd160") +} + +// IsSHA1 checks is a string is a SHA-1 hash. Alias for `IsHash(str, "sha1")` +func IsSHA1(str string) bool { + return IsHash(str, "sha1") +} + +// IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(str, "tiger128")` +func IsTiger128(str string) bool { + return IsHash(str, "tiger128") +} + +// IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(str, "ripemd128")` +func IsRipeMD128(str string) bool { + return IsHash(str, "ripemd128") +} + +// IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(str, "crc32")` +func IsCRC32(str string) bool { + return IsHash(str, "crc32") +} + +// IsCRC32b checks is a string is a CRC32b hash. Alias for `IsHash(str, "crc32b")` +func IsCRC32b(str string) bool { + return IsHash(str, "crc32b") +} + +// IsMD5 checks is a string is a MD5 hash. Alias for `IsHash(str, "md5")` +func IsMD5(str string) bool { + return IsHash(str, "md5") +} + +// IsMD4 checks is a string is a MD4 hash. Alias for `IsHash(str, "md4")` +func IsMD4(str string) bool { + return IsHash(str, "md4") +} + +// IsDialString validates the given string for usage with the various Dial() functions +func IsDialString(str string) bool { + if h, p, err := net.SplitHostPort(str); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) { + return true + } + + return false +} + +// IsIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP` +func IsIP(str string) bool { + return net.ParseIP(str) != nil +} + +// IsPort checks if a string represents a valid port +func IsPort(str string) bool { + if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 { + return true + } + return false +} + +// IsIPv4 checks if the string is an IP version 4. +func IsIPv4(str string) bool { + ip := net.ParseIP(str) + return ip != nil && strings.Contains(str, ".") +} + +// IsIPv6 checks if the string is an IP version 6. +func IsIPv6(str string) bool { + ip := net.ParseIP(str) + return ip != nil && strings.Contains(str, ":") +} + +// IsCIDR checks if the string is an valid CIDR notiation (IPV4 & IPV6) +func IsCIDR(str string) bool { + _, _, err := net.ParseCIDR(str) + return err == nil +} + +// IsMAC checks if a string is valid MAC address. +// Possible MAC formats: +// 01:23:45:67:89:ab +// 01:23:45:67:89:ab:cd:ef +// 01-23-45-67-89-ab +// 01-23-45-67-89-ab-cd-ef +// 0123.4567.89ab +// 0123.4567.89ab.cdef +func IsMAC(str string) bool { + _, err := net.ParseMAC(str) + return err == nil +} + +// IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name +func IsHost(str string) bool { + return IsIP(str) || IsDNSName(str) +} + +// IsMongoID checks if the string is a valid hex-encoded representation of a MongoDB ObjectId. +func IsMongoID(str string) bool { + return rxHexadecimal.MatchString(str) && (len(str) == 24) +} + +// IsLatitude checks if a string is valid latitude. +func IsLatitude(str string) bool { + return rxLatitude.MatchString(str) +} + +// IsLongitude checks if a string is valid longitude. +func IsLongitude(str string) bool { + return rxLongitude.MatchString(str) +} + +// IsIMEI checks if a string is valid IMEI +func IsIMEI(str string) bool { + return rxIMEI.MatchString(str) +} + +// IsIMSI checks if a string is valid IMSI +func IsIMSI(str string) bool { + if !rxIMSI.MatchString(str) { + return false + } + + mcc, err := strconv.ParseInt(str[0:3], 10, 32) + if err != nil { + return false + } + + switch mcc { + case 202, 204, 206, 208, 212, 213, 214, 216, 218, 219: + case 220, 221, 222, 226, 228, 230, 231, 232, 234, 235: + case 238, 240, 242, 244, 246, 247, 248, 250, 255, 257: + case 259, 260, 262, 266, 268, 270, 272, 274, 276, 278: + case 280, 282, 283, 284, 286, 288, 289, 290, 292, 293: + case 294, 295, 297, 302, 308, 310, 311, 312, 313, 314: + case 315, 316, 330, 332, 334, 338, 340, 342, 344, 346: + case 348, 350, 352, 354, 356, 358, 360, 362, 363, 364: + case 365, 366, 368, 370, 372, 374, 376, 400, 401, 402: + case 404, 405, 406, 410, 412, 413, 414, 415, 416, 417: + case 418, 419, 420, 421, 422, 424, 425, 426, 427, 428: + case 429, 430, 431, 432, 434, 436, 437, 438, 440, 441: + case 450, 452, 454, 455, 456, 457, 460, 461, 466, 467: + case 470, 472, 502, 505, 510, 514, 515, 520, 525, 528: + case 530, 536, 537, 539, 540, 541, 542, 543, 544, 545: + case 546, 547, 548, 549, 550, 551, 552, 553, 554, 555: + case 602, 603, 604, 605, 606, 607, 608, 609, 610, 611: + case 612, 613, 614, 615, 616, 617, 618, 619, 620, 621: + case 622, 623, 624, 625, 626, 627, 628, 629, 630, 631: + case 632, 633, 634, 635, 636, 637, 638, 639, 640, 641: + case 642, 643, 645, 646, 647, 648, 649, 650, 651, 652: + case 653, 654, 655, 657, 658, 659, 702, 704, 706, 708: + case 710, 712, 714, 716, 722, 724, 730, 732, 734, 736: + case 738, 740, 742, 744, 746, 748, 750, 995: + return true + default: + return false + } + return true +} + +// IsRsaPublicKey checks if a string is valid public key with provided length +func IsRsaPublicKey(str string, keylen int) bool { + bb := bytes.NewBufferString(str) + pemBytes, err := ioutil.ReadAll(bb) + if err != nil { + return false + } + block, _ := pem.Decode(pemBytes) + if block != nil && block.Type != "PUBLIC KEY" { + return false + } + var der []byte + + if block != nil { + der = block.Bytes + } else { + der, err = base64.StdEncoding.DecodeString(str) + if err != nil { + return false + } + } + + key, err := x509.ParsePKIXPublicKey(der) + if err != nil { + return false + } + pubkey, ok := key.(*rsa.PublicKey) + if !ok { + return false + } + bitlen := len(pubkey.N.Bytes()) * 8 + return bitlen == int(keylen) +} + +// IsRegex checks if a give string is a valid regex with RE2 syntax or not +func IsRegex(str string) bool { + if _, err := regexp.Compile(str); err == nil { + return true + } + return false +} + +func toJSONName(tag string) string { + if tag == "" { + return "" + } + + // JSON name always comes first. If there's no options then split[0] is + // JSON name, if JSON name is not set, then split[0] is an empty string. + split := strings.SplitN(tag, ",", 2) + + name := split[0] + + // However it is possible that the field is skipped when + // (de-)serializing from/to JSON, in which case assume that there is no + // tag name to use + if name == "-" { + return "" + } + return name +} + +func prependPathToErrors(err error, path string) error { + switch err2 := err.(type) { + case Error: + err2.Path = append([]string{path}, err2.Path...) + return err2 + case Errors: + errors := err2.Errors() + for i, err3 := range errors { + errors[i] = prependPathToErrors(err3, path) + } + return err2 + } + return err +} + +// ValidateArray performs validation according to condition iterator that validates every element of the array +func ValidateArray(array []interface{}, iterator ConditionIterator) bool { + return Every(array, iterator) +} + +// ValidateMap use validation map for fields. +// result will be equal to `false` if there are any errors. +// s is the map containing the data to be validated. +// m is the validation map in the form: +// map[string]interface{}{"name":"required,alpha","address":map[string]interface{}{"line1":"required,alphanum"}} +func ValidateMap(s map[string]interface{}, m map[string]interface{}) (bool, error) { + if s == nil { + return true, nil + } + result := true + var err error + var errs Errors + var index int + val := reflect.ValueOf(s) + for key, value := range s { + presentResult := true + validator, ok := m[key] + if !ok { + presentResult = false + var err error + err = fmt.Errorf("all map keys has to be present in the validation map; got %s", key) + err = prependPathToErrors(err, key) + errs = append(errs, err) + } + valueField := reflect.ValueOf(value) + mapResult := true + typeResult := true + structResult := true + resultField := true + switch subValidator := validator.(type) { + case map[string]interface{}: + var err error + if v, ok := value.(map[string]interface{}); !ok { + mapResult = false + err = fmt.Errorf("map validator has to be for the map type only; got %s", valueField.Type().String()) + err = prependPathToErrors(err, key) + errs = append(errs, err) + } else { + mapResult, err = ValidateMap(v, subValidator) + if err != nil { + mapResult = false + err = prependPathToErrors(err, key) + errs = append(errs, err) + } + } + case string: + if (valueField.Kind() == reflect.Struct || + (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && + subValidator != "-" { + var err error + structResult, err = ValidateStruct(valueField.Interface()) + if err != nil { + err = prependPathToErrors(err, key) + errs = append(errs, err) + } + } + resultField, err = typeCheck(valueField, reflect.StructField{ + Name: key, + PkgPath: "", + Type: val.Type(), + Tag: reflect.StructTag(fmt.Sprintf("%s:%q", tagName, subValidator)), + Offset: 0, + Index: []int{index}, + Anonymous: false, + }, val, nil) + if err != nil { + errs = append(errs, err) + } + case nil: + // already handlerd when checked before + default: + typeResult = false + err = fmt.Errorf("map validator has to be either map[string]interface{} or string; got %s", valueField.Type().String()) + err = prependPathToErrors(err, key) + errs = append(errs, err) + } + result = result && presentResult && typeResult && resultField && structResult && mapResult + index++ + } + // checks required keys + requiredResult := true + for key, value := range m { + if schema, ok := value.(string); ok { + tags := parseTagIntoMap(schema) + if required, ok := tags["required"]; ok { + if _, ok := s[key]; !ok { + requiredResult = false + if required.customErrorMessage != "" { + err = Error{key, fmt.Errorf(required.customErrorMessage), true, "required", []string{}} + } else { + err = Error{key, fmt.Errorf("required field missing"), false, "required", []string{}} + } + errs = append(errs, err) + } + } + } + } + + if len(errs) > 0 { + err = errs + } + return result && requiredResult, err +} + +// ValidateStruct use tags for fields. +// result will be equal to `false` if there are any errors. +// todo currently there is no guarantee that errors will be returned in predictable order (tests may to fail) +func ValidateStruct(s interface{}) (bool, error) { + if s == nil { + return true, nil + } + result := true + var err error + val := reflect.ValueOf(s) + if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { + val = val.Elem() + } + // we only accept structs + if val.Kind() != reflect.Struct { + return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) + } + var errs Errors + for i := 0; i < val.NumField(); i++ { + valueField := val.Field(i) + typeField := val.Type().Field(i) + if typeField.PkgPath != "" { + continue // Private field + } + structResult := true + if valueField.Kind() == reflect.Interface { + valueField = valueField.Elem() + } + if (valueField.Kind() == reflect.Struct || + (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && + typeField.Tag.Get(tagName) != "-" { + var err error + structResult, err = ValidateStruct(valueField.Interface()) + if err != nil { + err = prependPathToErrors(err, typeField.Name) + errs = append(errs, err) + } + } + resultField, err2 := typeCheck(valueField, typeField, val, nil) + if err2 != nil { + + // Replace structure name with JSON name if there is a tag on the variable + jsonTag := toJSONName(typeField.Tag.Get("json")) + if jsonTag != "" { + switch jsonError := err2.(type) { + case Error: + jsonError.Name = jsonTag + err2 = jsonError + case Errors: + for i2, err3 := range jsonError { + switch customErr := err3.(type) { + case Error: + customErr.Name = jsonTag + jsonError[i2] = customErr + } + } + + err2 = jsonError + } + } + + errs = append(errs, err2) + } + result = result && resultField && structResult + } + if len(errs) > 0 { + err = errs + } + return result, err +} + +// ValidateStructAsync performs async validation of the struct and returns results through the channels +func ValidateStructAsync(s interface{}) (<-chan bool, <-chan error) { + res := make(chan bool) + errors := make(chan error) + + go func() { + defer close(res) + defer close(errors) + + isValid, isFailed := ValidateStruct(s) + + res <- isValid + errors <- isFailed + }() + + return res, errors +} + +// ValidateMapAsync performs async validation of the map and returns results through the channels +func ValidateMapAsync(s map[string]interface{}, m map[string]interface{}) (<-chan bool, <-chan error) { + res := make(chan bool) + errors := make(chan error) + + go func() { + defer close(res) + defer close(errors) + + isValid, isFailed := ValidateMap(s, m) + + res <- isValid + errors <- isFailed + }() + + return res, errors +} + +// parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""} +func parseTagIntoMap(tag string) tagOptionsMap { + optionsMap := make(tagOptionsMap) + options := strings.Split(tag, ",") + + for i, option := range options { + option = strings.TrimSpace(option) + + validationOptions := strings.Split(option, "~") + if !isValidTag(validationOptions[0]) { + continue + } + if len(validationOptions) == 2 { + optionsMap[validationOptions[0]] = tagOption{validationOptions[0], validationOptions[1], i} + } else { + optionsMap[validationOptions[0]] = tagOption{validationOptions[0], "", i} + } + } + return optionsMap +} + +func isValidTag(s string) bool { + if s == "" { + return false + } + for _, c := range s { + switch { + case strings.ContainsRune("\\'\"!#$%&()*+-./:<=>?@[]^_{|}~ ", c): + // Backslash and quote chars are reserved, but + // otherwise any punctuation chars are allowed + // in a tag name. + default: + if !unicode.IsLetter(c) && !unicode.IsDigit(c) { + return false + } + } + } + return true +} + +// IsSSN will validate the given string as a U.S. Social Security Number +func IsSSN(str string) bool { + if str == "" || len(str) != 11 { + return false + } + return rxSSN.MatchString(str) +} + +// IsSemver checks if string is valid semantic version +func IsSemver(str string) bool { + return rxSemver.MatchString(str) +} + +// IsType checks if interface is of some type +func IsType(v interface{}, params ...string) bool { + if len(params) == 1 { + typ := params[0] + return strings.Replace(reflect.TypeOf(v).String(), " ", "", -1) == strings.Replace(typ, " ", "", -1) + } + return false +} + +// IsTime checks if string is valid according to given format +func IsTime(str string, format string) bool { + _, err := time.Parse(format, str) + return err == nil +} + +// IsUnixTime checks if string is valid unix timestamp value +func IsUnixTime(str string) bool { + if _, err := strconv.Atoi(str); err == nil { + return true + } + return false +} + +// IsRFC3339 checks if string is valid timestamp value according to RFC3339 +func IsRFC3339(str string) bool { + return IsTime(str, time.RFC3339) +} + +// IsRFC3339WithoutZone checks if string is valid timestamp value according to RFC3339 which excludes the timezone. +func IsRFC3339WithoutZone(str string) bool { + return IsTime(str, rfc3339WithoutZone) +} + +// IsISO4217 checks if string is valid ISO currency code +func IsISO4217(str string) bool { + for _, currency := range ISO4217List { + if str == currency { + return true + } + } + + return false +} + +// ByteLength checks string's length +func ByteLength(str string, params ...string) bool { + if len(params) == 2 { + min, _ := ToInt(params[0]) + max, _ := ToInt(params[1]) + return len(str) >= int(min) && len(str) <= int(max) + } + + return false +} + +// RuneLength checks string's length +// Alias for StringLength +func RuneLength(str string, params ...string) bool { + return StringLength(str, params...) +} + +// IsRsaPub checks whether string is valid RSA key +// Alias for IsRsaPublicKey +func IsRsaPub(str string, params ...string) bool { + if len(params) == 1 { + len, _ := ToInt(params[0]) + return IsRsaPublicKey(str, int(len)) + } + + return false +} + +// StringMatches checks if a string matches a given pattern. +func StringMatches(s string, params ...string) bool { + if len(params) == 1 { + pattern := params[0] + return Matches(s, pattern) + } + return false +} + +// StringLength checks string's length (including multi byte strings) +func StringLength(str string, params ...string) bool { + + if len(params) == 2 { + strLength := utf8.RuneCountInString(str) + min, _ := ToInt(params[0]) + max, _ := ToInt(params[1]) + return strLength >= int(min) && strLength <= int(max) + } + + return false +} + +// MinStringLength checks string's minimum length (including multi byte strings) +func MinStringLength(str string, params ...string) bool { + + if len(params) == 1 { + strLength := utf8.RuneCountInString(str) + min, _ := ToInt(params[0]) + return strLength >= int(min) + } + + return false +} + +// MaxStringLength checks string's maximum length (including multi byte strings) +func MaxStringLength(str string, params ...string) bool { + + if len(params) == 1 { + strLength := utf8.RuneCountInString(str) + max, _ := ToInt(params[0]) + return strLength <= int(max) + } + + return false +} + +// Range checks string's length +func Range(str string, params ...string) bool { + if len(params) == 2 { + value, _ := ToFloat(str) + min, _ := ToFloat(params[0]) + max, _ := ToFloat(params[1]) + return InRange(value, min, max) + } + + return false +} + +// IsInRaw checks if string is in list of allowed values +func IsInRaw(str string, params ...string) bool { + if len(params) == 1 { + rawParams := params[0] + + parsedParams := strings.Split(rawParams, "|") + + return IsIn(str, parsedParams...) + } + + return false +} + +// IsIn checks if string str is a member of the set of strings params +func IsIn(str string, params ...string) bool { + for _, param := range params { + if str == param { + return true + } + } + + return false +} + +func checkRequired(v reflect.Value, t reflect.StructField, options tagOptionsMap) (bool, error) { + if nilPtrAllowedByRequired { + k := v.Kind() + if (k == reflect.Ptr || k == reflect.Interface) && v.IsNil() { + return true, nil + } + } + + if requiredOption, isRequired := options["required"]; isRequired { + if len(requiredOption.customErrorMessage) > 0 { + return false, Error{t.Name, fmt.Errorf(requiredOption.customErrorMessage), true, "required", []string{}} + } + return false, Error{t.Name, fmt.Errorf("non zero value required"), false, "required", []string{}} + } else if _, isOptional := options["optional"]; fieldsRequiredByDefault && !isOptional { + return false, Error{t.Name, fmt.Errorf("Missing required field"), false, "required", []string{}} + } + // not required and empty is valid + return true, nil +} + +func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options tagOptionsMap) (isValid bool, resultErr error) { + if !v.IsValid() { + return false, nil + } + + tag := t.Tag.Get(tagName) + + // checks if the field should be ignored + switch tag { + case "": + if v.Kind() != reflect.Slice && v.Kind() != reflect.Map { + if !fieldsRequiredByDefault { + return true, nil + } + return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false, "required", []string{}} + } + case "-": + return true, nil + } + + isRootType := false + if options == nil { + isRootType = true + options = parseTagIntoMap(tag) + } + + if isEmptyValue(v) { + // an empty value is not validated, checks only required + isValid, resultErr = checkRequired(v, t, options) + for key := range options { + delete(options, key) + } + return isValid, resultErr + } + + var customTypeErrors Errors + optionsOrder := options.orderedKeys() + for _, validatorName := range optionsOrder { + validatorStruct := options[validatorName] + if validatefunc, ok := CustomTypeTagMap.Get(validatorName); ok { + delete(options, validatorName) + + if result := validatefunc(v.Interface(), o.Interface()); !result { + if len(validatorStruct.customErrorMessage) > 0 { + customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: TruncatingErrorf(validatorStruct.customErrorMessage, fmt.Sprint(v), validatorName), CustomErrorMessageExists: true, Validator: stripParams(validatorName)}) + continue + } + customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), validatorName), CustomErrorMessageExists: false, Validator: stripParams(validatorName)}) + } + } + } + + if len(customTypeErrors.Errors()) > 0 { + return false, customTypeErrors + } + + if isRootType { + // Ensure that we've checked the value by all specified validators before report that the value is valid + defer func() { + delete(options, "optional") + delete(options, "required") + + if isValid && resultErr == nil && len(options) != 0 { + optionsOrder := options.orderedKeys() + for _, validator := range optionsOrder { + isValid = false + resultErr = Error{t.Name, fmt.Errorf( + "The following validator is invalid or can't be applied to the field: %q", validator), false, stripParams(validator), []string{}} + return + } + } + }() + } + + for _, validatorSpec := range optionsOrder { + validatorStruct := options[validatorSpec] + var negate bool + validator := validatorSpec + customMsgExists := len(validatorStruct.customErrorMessage) > 0 + + // checks whether the tag looks like '!something' or 'something' + if validator[0] == '!' { + validator = validator[1:] + negate = true + } + + // checks for interface param validators + for key, value := range InterfaceParamTagRegexMap { + ps := value.FindStringSubmatch(validator) + if len(ps) == 0 { + continue + } + + validatefunc, ok := InterfaceParamTagMap[key] + if !ok { + continue + } + + delete(options, validatorSpec) + + field := fmt.Sprint(v) + if result := validatefunc(v.Interface(), ps[1:]...); (!result && !negate) || (result && negate) { + if customMsgExists { + return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + if negate { + return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + } + } + + switch v.Kind() { + case reflect.Bool, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Float32, reflect.Float64, + reflect.String: + // for each tag option checks the map of validator functions + for _, validatorSpec := range optionsOrder { + validatorStruct := options[validatorSpec] + var negate bool + validator := validatorSpec + customMsgExists := len(validatorStruct.customErrorMessage) > 0 + + // checks whether the tag looks like '!something' or 'something' + if validator[0] == '!' { + validator = validator[1:] + negate = true + } + + // checks for param validators + for key, value := range ParamTagRegexMap { + ps := value.FindStringSubmatch(validator) + if len(ps) == 0 { + continue + } + + validatefunc, ok := ParamTagMap[key] + if !ok { + continue + } + + delete(options, validatorSpec) + + switch v.Kind() { + case reflect.String, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + + field := fmt.Sprint(v) // make value into string, then validate with regex + if result := validatefunc(field, ps[1:]...); (!result && !negate) || (result && negate) { + if customMsgExists { + return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + if negate { + return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + default: + // type not yet supported, fail + return false, Error{t.Name, fmt.Errorf("Validator %s doesn't support kind %s", validator, v.Kind()), false, stripParams(validatorSpec), []string{}} + } + } + + if validatefunc, ok := TagMap[validator]; ok { + delete(options, validatorSpec) + + switch v.Kind() { + case reflect.String, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + field := fmt.Sprint(v) // make value into string, then validate with regex + if result := validatefunc(field); !result && !negate || result && negate { + if customMsgExists { + return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + if negate { + return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} + } + default: + //Not Yet Supported Types (Fail here!) + err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", validator, v.Kind(), v) + return false, Error{t.Name, err, false, stripParams(validatorSpec), []string{}} + } + } + } + return true, nil + case reflect.Map: + if v.Type().Key().Kind() != reflect.String { + return false, &UnsupportedTypeError{v.Type()} + } + var sv stringValues + sv = v.MapKeys() + sort.Sort(sv) + result := true + for i, k := range sv { + var resultItem bool + var err error + if v.MapIndex(k).Kind() != reflect.Struct { + resultItem, err = typeCheck(v.MapIndex(k), t, o, options) + if err != nil { + return false, err + } + } else { + resultItem, err = ValidateStruct(v.MapIndex(k).Interface()) + if err != nil { + err = prependPathToErrors(err, t.Name+"."+sv[i].Interface().(string)) + return false, err + } + } + result = result && resultItem + } + return result, nil + case reflect.Slice, reflect.Array: + result := true + for i := 0; i < v.Len(); i++ { + var resultItem bool + var err error + if v.Index(i).Kind() != reflect.Struct { + resultItem, err = typeCheck(v.Index(i), t, o, options) + if err != nil { + return false, err + } + } else { + resultItem, err = ValidateStruct(v.Index(i).Interface()) + if err != nil { + err = prependPathToErrors(err, t.Name+"."+strconv.Itoa(i)) + return false, err + } + } + result = result && resultItem + } + return result, nil + case reflect.Interface: + // If the value is an interface then encode its element + if v.IsNil() { + return true, nil + } + return ValidateStruct(v.Interface()) + case reflect.Ptr: + // If the value is a pointer then checks its element + if v.IsNil() { + return true, nil + } + return typeCheck(v.Elem(), t, o, options) + case reflect.Struct: + return true, nil + default: + return false, &UnsupportedTypeError{v.Type()} + } +} + +func stripParams(validatorString string) string { + return paramsRegexp.ReplaceAllString(validatorString, "") +} + +// isEmptyValue checks whether value empty or not +func isEmptyValue(v reflect.Value) bool { + switch v.Kind() { + case reflect.String, reflect.Array: + return v.Len() == 0 + case reflect.Map, reflect.Slice: + return v.Len() == 0 || v.IsNil() + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + + return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) +} + +// ErrorByField returns error for specified field of the struct +// validated by ValidateStruct or empty string if there are no errors +// or this field doesn't exists or doesn't have any errors. +func ErrorByField(e error, field string) string { + if e == nil { + return "" + } + return ErrorsByField(e)[field] +} + +// ErrorsByField returns map of errors of the struct validated +// by ValidateStruct or empty map if there are no errors. +func ErrorsByField(e error) map[string]string { + m := make(map[string]string) + if e == nil { + return m + } + // prototype for ValidateStruct + + switch e := e.(type) { + case Error: + m[e.Name] = e.Err.Error() + case Errors: + for _, item := range e.Errors() { + n := ErrorsByField(item) + for k, v := range n { + m[k] = v + } + } + } + + return m +} + +// Error returns string equivalent for reflect.Type +func (e *UnsupportedTypeError) Error() string { + return "validator: unsupported type: " + e.Type.String() +} + +func (sv stringValues) Len() int { return len(sv) } +func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } +func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) } +func (sv stringValues) get(i int) string { return sv[i].String() } + +func IsE164(str string) bool { + return rxE164.MatchString(str) +} diff --git a/vendor/github.com/asaskevich/govalidator/wercker.yml b/vendor/github.com/asaskevich/govalidator/wercker.yml new file mode 100644 index 0000000000..bc5f7b0864 --- /dev/null +++ b/vendor/github.com/asaskevich/govalidator/wercker.yml @@ -0,0 +1,15 @@ +box: golang +build: + steps: + - setup-go-workspace + + - script: + name: go get + code: | + go version + go get -t ./... + + - script: + name: go test + code: | + go test -race -v ./... diff --git a/vendor/github.com/chanxuehong/util/security/compare.go b/vendor/github.com/chanxuehong/util/security/compare.go deleted file mode 100644 index f24ee451c3..0000000000 --- a/vendor/github.com/chanxuehong/util/security/compare.go +++ /dev/null @@ -1,36 +0,0 @@ -package security - -import ( - "crypto/subtle" -) - -func SecureCompare(given, actual []byte) bool { - if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 { - if subtle.ConstantTimeCompare(given, actual) == 1 { - return true - } - return false - } - // Securely compare actual to itself to keep constant time, but always return false - if subtle.ConstantTimeCompare(actual, actual) == 1 { - return false - } - return false -} - -func SecureCompareString(given, actual string) bool { - // The following code is incorrect: - // return SecureCompare([]byte(given), []byte(actual)) - - if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 { - if subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1 { - return true - } - return false - } - // Securely compare actual to itself to keep constant time, but always return false - if subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 { - return false - } - return false -} diff --git a/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md index 42d9abc07e..5152bf59bf 100644 --- a/vendor/github.com/fatih/color/README.md +++ b/vendor/github.com/fatih/color/README.md @@ -1,20 +1,11 @@ -# Archived project. No maintenance. - -This project is not maintained anymore and is archived. Feel free to fork and -make your own changes if needed. For more detail read my blog post: [Taking an indefinite sabbatical from my projects](https://arslan.io/2018/10/09/taking-an-indefinite-sabbatical-from-my-projects/) - -Thanks to everyone for their valuable feedback and contributions. - - -# Color [![GoDoc](https://godoc.org/github.com/fatih/color?status.svg)](https://godoc.org/github.com/fatih/color) +# color [![](https://github.com/fatih/color/workflows/build/badge.svg)](https://github.com/fatih/color/actions) [![PkgGoDev](https://pkg.go.dev/badge/github.com/fatih/color)](https://pkg.go.dev/github.com/fatih/color) Color lets you use colorized outputs in terms of [ANSI Escape Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It has support for Windows too! The API can be used in several ways, pick one that suits you. - -![Color](https://i.imgur.com/c1JI0lA.png) +![Color](https://user-images.githubusercontent.com/438920/96832689-03b3e000-13f4-11eb-9803-46f4c4de3406.jpg) ## Install @@ -87,7 +78,7 @@ notice("Don't forget this...") ### Custom fprint functions (FprintFunc) ```go -blue := color.New(FgBlue).FprintfFunc() +blue := color.New(color.FgBlue).FprintfFunc() blue(myWriter, "important notice: %s", stars) // Mix up with multiple attributes @@ -136,14 +127,16 @@ fmt.Println("All text will now be bold magenta.") There might be a case where you want to explicitly disable/enable color output. the `go-isatty` package will automatically disable color output for non-tty output streams -(for example if the output were piped directly to `less`) +(for example if the output were piped directly to `less`). -`Color` has support to disable/enable colors both globally and for single color -definitions. For example suppose you have a CLI app and a `--no-color` bool flag. You -can easily disable the color output with: +The `color` package also disables color output if the [`NO_COLOR`](https://no-color.org) environment +variable is set (regardless of its value). -```go +`Color` has support to disable/enable colors programatically both globally and +for single color definitions. For example suppose you have a CLI app and a +`--no-color` bool flag. You can easily disable the color output with: +```go var flagNoColor = flag.Bool("no-color", false, "Disable color output") if *flagNoColor { @@ -165,6 +158,10 @@ c.EnableColor() c.Println("This prints again cyan...") ``` +## GitHub Actions + +To output color in GitHub Actions (or other CI systems that support ANSI colors), make sure to set `color.NoColor = false` so that it bypasses the check for non-tty output streams. + ## Todo * Save/Return previous values @@ -179,4 +176,3 @@ c.Println("This prints again cyan...") ## License The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details - diff --git a/vendor/github.com/fatih/color/color.go b/vendor/github.com/fatih/color/color.go index 91c8e9f062..98a60f3c88 100644 --- a/vendor/github.com/fatih/color/color.go +++ b/vendor/github.com/fatih/color/color.go @@ -15,9 +15,11 @@ import ( var ( // NoColor defines if the output is colorized or not. It's dynamically set to // false or true based on the stdout's file descriptor referring to a terminal - // or not. This is a global option and affects all colors. For more control - // over each color block use the methods DisableColor() individually. - NoColor = os.Getenv("TERM") == "dumb" || + // or not. It's also set to true if the NO_COLOR environment variable is + // set (regardless of its value). This is a global option and affects all + // colors. For more control over each color block use the methods + // DisableColor() individually. + NoColor = noColorExists() || os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) // Output defines the standard output of the print functions. By default @@ -33,6 +35,12 @@ var ( colorsCacheMu sync.Mutex // protects colorsCache ) +// noColorExists returns true if the environment variable NO_COLOR exists. +func noColorExists() bool { + _, exists := os.LookupEnv("NO_COLOR") + return exists +} + // Color defines a custom color object which is defined by SGR parameters. type Color struct { params []Attribute @@ -108,7 +116,14 @@ const ( // New returns a newly created color object. func New(value ...Attribute) *Color { - c := &Color{params: make([]Attribute, 0)} + c := &Color{ + params: make([]Attribute, 0), + } + + if noColorExists() { + c.noColor = boolPtr(true) + } + c.Add(value...) return c } @@ -387,7 +402,7 @@ func (c *Color) EnableColor() { } func (c *Color) isNoColorSet() bool { - // check first if we have user setted action + // check first if we have user set action if c.noColor != nil { return *c.noColor } diff --git a/vendor/github.com/fatih/color/doc.go b/vendor/github.com/fatih/color/doc.go index cf1e96500f..04541de786 100644 --- a/vendor/github.com/fatih/color/doc.go +++ b/vendor/github.com/fatih/color/doc.go @@ -118,6 +118,8 @@ the color output with: color.NoColor = true // disables colorized output } +You can also disable the color by setting the NO_COLOR environment variable to any value. + It also has support for single color definitions (local). You can disable/enable color output on the fly: diff --git a/vendor/github.com/gabriel-vasile/mimetype/.gitattributes b/vendor/github.com/gabriel-vasile/mimetype/.gitattributes new file mode 100644 index 0000000000..0cc26ec01c --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/.gitattributes @@ -0,0 +1 @@ +testdata/* linguist-vendored diff --git a/vendor/github.com/gabriel-vasile/mimetype/CODE_OF_CONDUCT.md b/vendor/github.com/gabriel-vasile/mimetype/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..8479cd87d6 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at vasile.gabriel@email.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/vendor/github.com/gabriel-vasile/mimetype/CONTRIBUTING.md b/vendor/github.com/gabriel-vasile/mimetype/CONTRIBUTING.md new file mode 100644 index 0000000000..56ae4e57c6 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/CONTRIBUTING.md @@ -0,0 +1,12 @@ +## Contribute +Contributions to **mimetype** are welcome. If you find an issue and you consider +contributing, you can use the [Github issues tracker](https://github.com/gabriel-vasile/mimetype/issues) +in order to report it, or better yet, open a pull request. + +Code contributions must respect these rules: + - code must be test covered + - code must be formatted using gofmt tool + - exported names must be documented + +**Important**: By submitting a pull request, you agree to allow the project +owner to license your work under the same license as that used by the project. diff --git a/vendor/github.com/gabriel-vasile/mimetype/LICENSE b/vendor/github.com/gabriel-vasile/mimetype/LICENSE new file mode 100644 index 0000000000..6aac070c78 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018-2020 Gabriel Vasile + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/gabriel-vasile/mimetype/README.md b/vendor/github.com/gabriel-vasile/mimetype/README.md new file mode 100644 index 0000000000..d310928dea --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/README.md @@ -0,0 +1,108 @@ +

+ mimetype +

+ +

+ A package for detecting MIME types and extensions based on magic numbers +

+
+ Goroutine safe, extensible, no C bindings +
+ +

+ + Build Status + + + Go Reference + + + Go report card + + + Code coverage + + + License + +

+ +## Features +- fast and precise MIME type and file extension detection +- long list of [supported MIME types](supported_mimes.md) +- possibility to [extend](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#example-package-Extend) with other file formats +- common file formats are prioritized +- [text vs. binary files differentiation](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#example-package-TextVsBinary) +- safe for concurrent usage + +## Install +```bash +go get github.com/gabriel-vasile/mimetype +``` + +## Usage +```go +mtype := mimetype.Detect([]byte) +// OR +mtype, err := mimetype.DetectReader(io.Reader) +// OR +mtype, err := mimetype.DetectFile("/path/to/file") +fmt.Println(mtype.String(), mtype.Extension()) +``` +See the [runnable Go Playground examples](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#pkg-overview). + +## Usage' +Only use libraries like **mimetype** as a last resort. Content type detection +using magic numbers is slow, inaccurate, and non-standard. Most of the times +protocols have methods for specifying such metadata; e.g., `Content-Type` header +in HTTP and SMTP. + +## FAQ +Q: My file is in the list of [supported MIME types](supported_mimes.md) but +it is not correctly detected. What should I do? + +A: Some file formats (often Microsoft Office documents) keep their signatures +towards the end of the file. Try increasing the number of bytes used for detection +with: +```go +mimetype.SetLimit(1024*1024) // Set limit to 1MB. +// or +mimetype.SetLimit(0) // No limit, whole file content used. +mimetype.DetectFile("file.doc") +``` +If increasing the limit does not help, please +[open an issue](https://github.com/gabriel-vasile/mimetype/issues/new?assignees=&labels=&template=mismatched-mime-type-detected.md&title=). + +## Structure +**mimetype** uses a hierarchical structure to keep the MIME type detection logic. +This reduces the number of calls needed for detecting the file type. The reason +behind this choice is that there are file formats used as containers for other +file formats. For example, Microsoft Office files are just zip archives, +containing specific metadata files. Once a file has been identified as a +zip, there is no need to check if it is a text file, but it is worth checking if +it is an Microsoft Office file. + +To prevent loading entire files into memory, when detecting from a +[reader](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#DetectReader) +or from a [file](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#DetectFile) +**mimetype** limits itself to reading only the header of the input. +
+ structure +
+ +## Performance +Thanks to the hierarchical structure, searching for common formats first, +and limiting itself to file headers, **mimetype** matches the performance of +stdlib `http.DetectContentType` while outperforming the alternative package. + +```bash + mimetype http.DetectContentType filetype +BenchmarkMatchTar-24 250 ns/op 400 ns/op 3778 ns/op +BenchmarkMatchZip-24 524 ns/op 351 ns/op 4884 ns/op +BenchmarkMatchJpeg-24 103 ns/op 228 ns/op 839 ns/op +BenchmarkMatchGif-24 139 ns/op 202 ns/op 751 ns/op +BenchmarkMatchPng-24 165 ns/op 221 ns/op 1176 ns/op +``` + +## Contributing +See [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go b/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go new file mode 100644 index 0000000000..0647f730e5 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go @@ -0,0 +1,309 @@ +package charset + +import ( + "bytes" + "encoding/xml" + "strings" + "unicode/utf8" + + "golang.org/x/net/html" +) + +const ( + F = 0 /* character never appears in text */ + T = 1 /* character appears in plain ASCII text */ + I = 2 /* character appears in ISO-8859 text */ + X = 3 /* character appears in non-ISO extended ASCII (Mac, IBM PC) */ +) + +var ( + boms = []struct { + bom []byte + enc string + }{ + {[]byte{0xEF, 0xBB, 0xBF}, "utf-8"}, + {[]byte{0x00, 0x00, 0xFE, 0xFF}, "utf-32be"}, + {[]byte{0xFF, 0xFE, 0x00, 0x00}, "utf-32le"}, + {[]byte{0xFE, 0xFF}, "utf-16be"}, + {[]byte{0xFF, 0xFE}, "utf-16le"}, + } + + // https://github.com/file/file/blob/fa93fb9f7d21935f1c7644c47d2975d31f12b812/src/encoding.c#L241 + textChars = [256]byte{ + /* BEL BS HT LF VT FF CR */ + F, F, F, F, F, F, F, T, T, T, T, T, T, T, F, F, /* 0x0X */ + /* ESC */ + F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, F, /* 0x1X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x2X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x3X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x4X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x5X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x6X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, /* 0x7X */ + /* NEL */ + X, X, X, X, X, T, X, X, X, X, X, X, X, X, X, X, /* 0x8X */ + X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, /* 0x9X */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xaX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xbX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xcX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xdX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xeX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xfX */ + } +) + +// FromBOM returns the charset declared in the BOM of content. +func FromBOM(content []byte) string { + for _, b := range boms { + if bytes.HasPrefix(content, b.bom) { + return b.enc + } + } + return "" +} + +// FromPlain returns the charset of a plain text. It relies on BOM presence +// and it falls back on checking each byte in content. +func FromPlain(content []byte) string { + if len(content) == 0 { + return "" + } + if cset := FromBOM(content); cset != "" { + return cset + } + origContent := content + // Try to detect UTF-8. + // First eliminate any partial rune at the end. + for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- { + b := content[i] + if b < 0x80 { + break + } + if utf8.RuneStart(b) { + content = content[:i] + break + } + } + hasHighBit := false + for _, c := range content { + if c >= 0x80 { + hasHighBit = true + break + } + } + if hasHighBit && utf8.Valid(content) { + return "utf-8" + } + + // ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8. + if ascii(origContent) { + return "utf-8" + } + + return latin(origContent) +} + +func latin(content []byte) string { + hasControlBytes := false + for _, b := range content { + t := textChars[b] + if t != T && t != I { + return "" + } + if b >= 0x80 && b <= 0x9F { + hasControlBytes = true + } + } + // Code range 0x80 to 0x9F is reserved for control characters in ISO-8859-1 + // (so-called C1 Controls). Windows 1252, however, has printable punctuation + // characters in this range. + if hasControlBytes { + return "windows-1252" + } + return "iso-8859-1" +} + +func ascii(content []byte) bool { + for _, b := range content { + if textChars[b] != T { + return false + } + } + return true +} + +// FromXML returns the charset of an XML document. It relies on the XML +// header and falls back on the plain +// text content. +func FromXML(content []byte) string { + if cset := fromXML(content); cset != "" { + return cset + } + return FromPlain(content) +} +func fromXML(content []byte) string { + content = trimLWS(content) + dec := xml.NewDecoder(bytes.NewReader(content)) + rawT, err := dec.RawToken() + if err != nil { + return "" + } + + t, ok := rawT.(xml.ProcInst) + if !ok { + return "" + } + + return strings.ToLower(xmlEncoding(string(t.Inst))) +} + +// FromHTML returns the charset of an HTML document. It first looks if a BOM is +// present and if so uses it to determine the charset. If no BOM is present, +// it relies on the meta tag and falls back on the +// plain text content. +func FromHTML(content []byte) string { + if cset := FromBOM(content); cset != "" { + return cset + } + if cset := fromHTML(content); cset != "" { + return cset + } + return FromPlain(content) +} + +func fromHTML(content []byte) string { + z := html.NewTokenizer(bytes.NewReader(content)) + for { + switch z.Next() { + case html.ErrorToken: + return "" + + case html.StartTagToken, html.SelfClosingTagToken: + tagName, hasAttr := z.TagName() + if !bytes.Equal(tagName, []byte("meta")) { + continue + } + attrList := make(map[string]bool) + gotPragma := false + + const ( + dontKnow = iota + doNeedPragma + doNotNeedPragma + ) + needPragma := dontKnow + + name := "" + for hasAttr { + var key, val []byte + key, val, hasAttr = z.TagAttr() + ks := string(key) + if attrList[ks] { + continue + } + attrList[ks] = true + for i, c := range val { + if 'A' <= c && c <= 'Z' { + val[i] = c + 0x20 + } + } + + switch ks { + case "http-equiv": + if bytes.Equal(val, []byte("content-type")) { + gotPragma = true + } + + case "content": + name = fromMetaElement(string(val)) + if name != "" { + needPragma = doNeedPragma + } + + case "charset": + name = string(val) + needPragma = doNotNeedPragma + } + } + + if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma { + continue + } + + if strings.HasPrefix(name, "utf-16") { + name = "utf-8" + } + + return name + } + } +} + +func fromMetaElement(s string) string { + for s != "" { + csLoc := strings.Index(s, "charset") + if csLoc == -1 { + return "" + } + s = s[csLoc+len("charset"):] + s = strings.TrimLeft(s, " \t\n\f\r") + if !strings.HasPrefix(s, "=") { + continue + } + s = s[1:] + s = strings.TrimLeft(s, " \t\n\f\r") + if s == "" { + return "" + } + if q := s[0]; q == '"' || q == '\'' { + s = s[1:] + closeQuote := strings.IndexRune(s, rune(q)) + if closeQuote == -1 { + return "" + } + return s[:closeQuote] + } + + end := strings.IndexAny(s, "; \t\n\f\r") + if end == -1 { + end = len(s) + } + return s[:end] + } + return "" +} + +func xmlEncoding(s string) string { + param := "encoding=" + idx := strings.Index(s, param) + if idx == -1 { + return "" + } + v := s[idx+len(param):] + if v == "" { + return "" + } + if v[0] != '\'' && v[0] != '"' { + return "" + } + idx = strings.IndexRune(v[1:], rune(v[0])) + if idx == -1 { + return "" + } + return v[1 : idx+1] +} + +// trimLWS trims whitespace from beginning of the input. +// TODO: find a way to call trimLWS once per detection instead of once in each +// detector which needs the trimmed input. +func trimLWS(in []byte) []byte { + firstNonWS := 0 + for ; firstNonWS < len(in) && isWS(in[firstNonWS]); firstNonWS++ { + } + + return in[firstNonWS:] +} + +func isWS(b byte) bool { + return b == '\t' || b == '\n' || b == '\x0c' || b == '\r' || b == ' ' +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/json/json.go b/vendor/github.com/gabriel-vasile/mimetype/internal/json/json.go new file mode 100644 index 0000000000..ee39349aef --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/json/json.go @@ -0,0 +1,544 @@ +// Copyright (c) 2009 The Go Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Package json provides a JSON value parser state machine. +// This package is almost entirely copied from the Go stdlib. +// Changes made to it permit users of the package to tell +// if some slice of bytes is a valid beginning of a json string. +package json + +import ( + "fmt" +) + +type ( + scanStatus int +) + +const ( + parseObjectKey = iota // parsing object key (before colon) + parseObjectValue // parsing object value (after colon) + parseArrayValue // parsing array value + + scanContinue scanStatus = iota // uninteresting byte + scanBeginLiteral // end implied by next result != scanContinue + scanBeginObject // begin object + scanObjectKey // just finished object key (string) + scanObjectValue // just finished non-last object value + scanEndObject // end object (implies scanObjectValue if possible) + scanBeginArray // begin array + scanArrayValue // just finished array value + scanEndArray // end array (implies scanArrayValue if possible) + scanSkipSpace // space byte; can skip; known to be last "continue" result + scanEnd // top-level value ended *before* this byte; known to be first "stop" result + scanError // hit an error, scanner.err. + + // This limits the max nesting depth to prevent stack overflow. + // This is permitted by https://tools.ietf.org/html/rfc7159#section-9 + maxNestingDepth = 10000 +) + +type ( + scanner struct { + step func(*scanner, byte) scanStatus + parseState []int + endTop bool + err error + index int + } +) + +// Scan returns the number of bytes scanned and if there was any error +// in trying to reach the end of data. +func Scan(data []byte) (int, error) { + s := &scanner{} + _ = checkValid(data, s) + return s.index, s.err +} + +// checkValid verifies that data is valid JSON-encoded data. +// scan is passed in for use by checkValid to avoid an allocation. +func checkValid(data []byte, scan *scanner) error { + scan.reset() + for _, c := range data { + scan.index++ + if scan.step(scan, c) == scanError { + return scan.err + } + } + if scan.eof() == scanError { + return scan.err + } + return nil +} + +func isSpace(c byte) bool { + return c == ' ' || c == '\t' || c == '\r' || c == '\n' +} + +func (s *scanner) reset() { + s.step = stateBeginValue + s.parseState = s.parseState[0:0] + s.err = nil +} + +// eof tells the scanner that the end of input has been reached. +// It returns a scan status just as s.step does. +func (s *scanner) eof() scanStatus { + if s.err != nil { + return scanError + } + if s.endTop { + return scanEnd + } + s.step(s, ' ') + if s.endTop { + return scanEnd + } + if s.err == nil { + s.err = fmt.Errorf("unexpected end of JSON input") + } + return scanError +} + +// pushParseState pushes a new parse state p onto the parse stack. +// an error state is returned if maxNestingDepth was exceeded, otherwise successState is returned. +func (s *scanner) pushParseState(c byte, newParseState int, successState scanStatus) scanStatus { + s.parseState = append(s.parseState, newParseState) + if len(s.parseState) <= maxNestingDepth { + return successState + } + return s.error(c, "exceeded max depth") +} + +// popParseState pops a parse state (already obtained) off the stack +// and updates s.step accordingly. +func (s *scanner) popParseState() { + n := len(s.parseState) - 1 + s.parseState = s.parseState[0:n] + if n == 0 { + s.step = stateEndTop + s.endTop = true + } else { + s.step = stateEndValue + } +} + +// stateBeginValueOrEmpty is the state after reading `[`. +func stateBeginValueOrEmpty(s *scanner, c byte) scanStatus { + if c <= ' ' && isSpace(c) { + return scanSkipSpace + } + if c == ']' { + return stateEndValue(s, c) + } + return stateBeginValue(s, c) +} + +// stateBeginValue is the state at the beginning of the input. +func stateBeginValue(s *scanner, c byte) scanStatus { + if c <= ' ' && isSpace(c) { + return scanSkipSpace + } + switch c { + case '{': + s.step = stateBeginStringOrEmpty + return s.pushParseState(c, parseObjectKey, scanBeginObject) + case '[': + s.step = stateBeginValueOrEmpty + return s.pushParseState(c, parseArrayValue, scanBeginArray) + case '"': + s.step = stateInString + return scanBeginLiteral + case '-': + s.step = stateNeg + return scanBeginLiteral + case '0': // beginning of 0.123 + s.step = state0 + return scanBeginLiteral + case 't': // beginning of true + s.step = stateT + return scanBeginLiteral + case 'f': // beginning of false + s.step = stateF + return scanBeginLiteral + case 'n': // beginning of null + s.step = stateN + return scanBeginLiteral + } + if '1' <= c && c <= '9' { // beginning of 1234.5 + s.step = state1 + return scanBeginLiteral + } + return s.error(c, "looking for beginning of value") +} + +// stateBeginStringOrEmpty is the state after reading `{`. +func stateBeginStringOrEmpty(s *scanner, c byte) scanStatus { + if c <= ' ' && isSpace(c) { + return scanSkipSpace + } + if c == '}' { + n := len(s.parseState) + s.parseState[n-1] = parseObjectValue + return stateEndValue(s, c) + } + return stateBeginString(s, c) +} + +// stateBeginString is the state after reading `{"key": value,`. +func stateBeginString(s *scanner, c byte) scanStatus { + if c <= ' ' && isSpace(c) { + return scanSkipSpace + } + if c == '"' { + s.step = stateInString + return scanBeginLiteral + } + return s.error(c, "looking for beginning of object key string") +} + +// stateEndValue is the state after completing a value, +// such as after reading `{}` or `true` or `["x"`. +func stateEndValue(s *scanner, c byte) scanStatus { + n := len(s.parseState) + if n == 0 { + // Completed top-level before the current byte. + s.step = stateEndTop + s.endTop = true + return stateEndTop(s, c) + } + if c <= ' ' && isSpace(c) { + s.step = stateEndValue + return scanSkipSpace + } + ps := s.parseState[n-1] + switch ps { + case parseObjectKey: + if c == ':' { + s.parseState[n-1] = parseObjectValue + s.step = stateBeginValue + return scanObjectKey + } + return s.error(c, "after object key") + case parseObjectValue: + if c == ',' { + s.parseState[n-1] = parseObjectKey + s.step = stateBeginString + return scanObjectValue + } + if c == '}' { + s.popParseState() + return scanEndObject + } + return s.error(c, "after object key:value pair") + case parseArrayValue: + if c == ',' { + s.step = stateBeginValue + return scanArrayValue + } + if c == ']' { + s.popParseState() + return scanEndArray + } + return s.error(c, "after array element") + } + return s.error(c, "") +} + +// stateEndTop is the state after finishing the top-level value, +// such as after reading `{}` or `[1,2,3]`. +// Only space characters should be seen now. +func stateEndTop(s *scanner, c byte) scanStatus { + if c != ' ' && c != '\t' && c != '\r' && c != '\n' { + // Complain about non-space byte on next call. + s.error(c, "after top-level value") + } + return scanEnd +} + +// stateInString is the state after reading `"`. +func stateInString(s *scanner, c byte) scanStatus { + if c == '"' { + s.step = stateEndValue + return scanContinue + } + if c == '\\' { + s.step = stateInStringEsc + return scanContinue + } + if c < 0x20 { + return s.error(c, "in string literal") + } + return scanContinue +} + +// stateInStringEsc is the state after reading `"\` during a quoted string. +func stateInStringEsc(s *scanner, c byte) scanStatus { + switch c { + case 'b', 'f', 'n', 'r', 't', '\\', '/', '"': + s.step = stateInString + return scanContinue + case 'u': + s.step = stateInStringEscU + return scanContinue + } + return s.error(c, "in string escape code") +} + +// stateInStringEscU is the state after reading `"\u` during a quoted string. +func stateInStringEscU(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { + s.step = stateInStringEscU1 + return scanContinue + } + // numbers + return s.error(c, "in \\u hexadecimal character escape") +} + +// stateInStringEscU1 is the state after reading `"\u1` during a quoted string. +func stateInStringEscU1(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { + s.step = stateInStringEscU12 + return scanContinue + } + // numbers + return s.error(c, "in \\u hexadecimal character escape") +} + +// stateInStringEscU12 is the state after reading `"\u12` during a quoted string. +func stateInStringEscU12(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { + s.step = stateInStringEscU123 + return scanContinue + } + // numbers + return s.error(c, "in \\u hexadecimal character escape") +} + +// stateInStringEscU123 is the state after reading `"\u123` during a quoted string. +func stateInStringEscU123(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { + s.step = stateInString + return scanContinue + } + // numbers + return s.error(c, "in \\u hexadecimal character escape") +} + +// stateNeg is the state after reading `-` during a number. +func stateNeg(s *scanner, c byte) scanStatus { + if c == '0' { + s.step = state0 + return scanContinue + } + if '1' <= c && c <= '9' { + s.step = state1 + return scanContinue + } + return s.error(c, "in numeric literal") +} + +// state1 is the state after reading a non-zero integer during a number, +// such as after reading `1` or `100` but not `0`. +func state1(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' { + s.step = state1 + return scanContinue + } + return state0(s, c) +} + +// state0 is the state after reading `0` during a number. +func state0(s *scanner, c byte) scanStatus { + if c == '.' { + s.step = stateDot + return scanContinue + } + if c == 'e' || c == 'E' { + s.step = stateE + return scanContinue + } + return stateEndValue(s, c) +} + +// stateDot is the state after reading the integer and decimal point in a number, +// such as after reading `1.`. +func stateDot(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' { + s.step = stateDot0 + return scanContinue + } + return s.error(c, "after decimal point in numeric literal") +} + +// stateDot0 is the state after reading the integer, decimal point, and subsequent +// digits of a number, such as after reading `3.14`. +func stateDot0(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' { + return scanContinue + } + if c == 'e' || c == 'E' { + s.step = stateE + return scanContinue + } + return stateEndValue(s, c) +} + +// stateE is the state after reading the mantissa and e in a number, +// such as after reading `314e` or `0.314e`. +func stateE(s *scanner, c byte) scanStatus { + if c == '+' || c == '-' { + s.step = stateESign + return scanContinue + } + return stateESign(s, c) +} + +// stateESign is the state after reading the mantissa, e, and sign in a number, +// such as after reading `314e-` or `0.314e+`. +func stateESign(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' { + s.step = stateE0 + return scanContinue + } + return s.error(c, "in exponent of numeric literal") +} + +// stateE0 is the state after reading the mantissa, e, optional sign, +// and at least one digit of the exponent in a number, +// such as after reading `314e-2` or `0.314e+1` or `3.14e0`. +func stateE0(s *scanner, c byte) scanStatus { + if '0' <= c && c <= '9' { + return scanContinue + } + return stateEndValue(s, c) +} + +// stateT is the state after reading `t`. +func stateT(s *scanner, c byte) scanStatus { + if c == 'r' { + s.step = stateTr + return scanContinue + } + return s.error(c, "in literal true (expecting 'r')") +} + +// stateTr is the state after reading `tr`. +func stateTr(s *scanner, c byte) scanStatus { + if c == 'u' { + s.step = stateTru + return scanContinue + } + return s.error(c, "in literal true (expecting 'u')") +} + +// stateTru is the state after reading `tru`. +func stateTru(s *scanner, c byte) scanStatus { + if c == 'e' { + s.step = stateEndValue + return scanContinue + } + return s.error(c, "in literal true (expecting 'e')") +} + +// stateF is the state after reading `f`. +func stateF(s *scanner, c byte) scanStatus { + if c == 'a' { + s.step = stateFa + return scanContinue + } + return s.error(c, "in literal false (expecting 'a')") +} + +// stateFa is the state after reading `fa`. +func stateFa(s *scanner, c byte) scanStatus { + if c == 'l' { + s.step = stateFal + return scanContinue + } + return s.error(c, "in literal false (expecting 'l')") +} + +// stateFal is the state after reading `fal`. +func stateFal(s *scanner, c byte) scanStatus { + if c == 's' { + s.step = stateFals + return scanContinue + } + return s.error(c, "in literal false (expecting 's')") +} + +// stateFals is the state after reading `fals`. +func stateFals(s *scanner, c byte) scanStatus { + if c == 'e' { + s.step = stateEndValue + return scanContinue + } + return s.error(c, "in literal false (expecting 'e')") +} + +// stateN is the state after reading `n`. +func stateN(s *scanner, c byte) scanStatus { + if c == 'u' { + s.step = stateNu + return scanContinue + } + return s.error(c, "in literal null (expecting 'u')") +} + +// stateNu is the state after reading `nu`. +func stateNu(s *scanner, c byte) scanStatus { + if c == 'l' { + s.step = stateNul + return scanContinue + } + return s.error(c, "in literal null (expecting 'l')") +} + +// stateNul is the state after reading `nul`. +func stateNul(s *scanner, c byte) scanStatus { + if c == 'l' { + s.step = stateEndValue + return scanContinue + } + return s.error(c, "in literal null (expecting 'l')") +} + +// stateError is the state after reaching a syntax error, +// such as after reading `[1}` or `5.1.2`. +func stateError(s *scanner, c byte) scanStatus { + return scanError +} + +// error records an error and switches to the error state. +func (s *scanner) error(c byte, context string) scanStatus { + s.step = stateError + s.err = fmt.Errorf("invalid character <<%c>> %s", c, context) + return scanError +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go new file mode 100644 index 0000000000..fec11f080a --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go @@ -0,0 +1,124 @@ +package magic + +import ( + "bytes" + "encoding/binary" +) + +var ( + // SevenZ matches a 7z archive. + SevenZ = prefix([]byte{0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C}) + // Gzip matches gzip files based on http://www.zlib.org/rfc-gzip.html#header-trailer. + Gzip = prefix([]byte{0x1f, 0x8b}) + // Fits matches an Flexible Image Transport System file. + Fits = prefix([]byte{ + 0x53, 0x49, 0x4D, 0x50, 0x4C, 0x45, 0x20, 0x20, 0x3D, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x54, + }) + // Xar matches an eXtensible ARchive format file. + Xar = prefix([]byte{0x78, 0x61, 0x72, 0x21}) + // Bz2 matches a bzip2 file. + Bz2 = prefix([]byte{0x42, 0x5A, 0x68}) + // Ar matches an ar (Unix) archive file. + Ar = prefix([]byte{0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E}) + // Deb matches a Debian package file. + Deb = offset([]byte{ + 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, + 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79, + }, 8) + // Warc matches a Web ARChive file. + Warc = prefix([]byte("WARC/1.0"), []byte("WARC/1.1")) + // Cab matches a Microsoft Cabinet archive file. + Cab = prefix([]byte("MSCF\x00\x00\x00\x00")) + // Xz matches an xz compressed stream based on https://tukaani.org/xz/xz-file-format.txt. + Xz = prefix([]byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}) + // Lzip matches an Lzip compressed file. + Lzip = prefix([]byte{0x4c, 0x5a, 0x49, 0x50}) + // RPM matches an RPM or Delta RPM package file. + RPM = prefix([]byte{0xed, 0xab, 0xee, 0xdb}, []byte("drpm")) + // Cpio matches a cpio archive file. + Cpio = prefix([]byte("070707"), []byte("070701"), []byte("070702")) + // RAR matches a RAR archive file. + RAR = prefix([]byte("Rar!\x1A\x07\x00"), []byte("Rar!\x1A\x07\x01\x00")) +) + +// InstallShieldCab matches an InstallShield Cabinet archive file. +func InstallShieldCab(raw []byte, _ uint32) bool { + return len(raw) > 7 && + bytes.Equal(raw[0:4], []byte("ISc(")) && + raw[6] == 0 && + (raw[7] == 1 || raw[7] == 2 || raw[7] == 4) +} + +// Zstd matches a Zstandard archive file. +func Zstd(raw []byte, limit uint32) bool { + return len(raw) >= 4 && + (0x22 <= raw[0] && raw[0] <= 0x28 || raw[0] == 0x1E) && // Different Zstandard versions. + bytes.HasPrefix(raw[1:], []byte{0xB5, 0x2F, 0xFD}) +} + +// CRX matches a Chrome extension file: a zip archive prepended by a package header. +func CRX(raw []byte, limit uint32) bool { + const minHeaderLen = 16 + if len(raw) < minHeaderLen || !bytes.HasPrefix(raw, []byte("Cr24")) { + return false + } + pubkeyLen := binary.LittleEndian.Uint32(raw[8:12]) + sigLen := binary.LittleEndian.Uint32(raw[12:16]) + zipOffset := minHeaderLen + pubkeyLen + sigLen + if uint32(len(raw)) < zipOffset { + return false + } + return Zip(raw[zipOffset:], limit) +} + +// Tar matches a (t)ape (ar)chive file. +func Tar(raw []byte, _ uint32) bool { + // The "magic" header field for files in in UStar (POSIX IEEE P1003.1) archives + // has the prefix "ustar". The values of the remaining bytes in this field vary + // by archiver implementation. + if len(raw) >= 512 && bytes.HasPrefix(raw[257:], []byte{0x75, 0x73, 0x74, 0x61, 0x72}) { + return true + } + + if len(raw) < 256 { + return false + } + + // The older v7 format has no "magic" field, and therefore must be identified + // with heuristics based on legal ranges of values for other header fields: + // https://www.nationalarchives.gov.uk/PRONOM/Format/proFormatSearch.aspx?status=detailReport&id=385&strPageToDisplay=signatures + rules := []struct { + min, max uint8 + i int + }{ + {0x21, 0xEF, 0}, + {0x30, 0x37, 105}, + {0x20, 0x37, 106}, + {0x00, 0x00, 107}, + {0x30, 0x37, 113}, + {0x20, 0x37, 114}, + {0x00, 0x00, 115}, + {0x30, 0x37, 121}, + {0x20, 0x37, 122}, + {0x00, 0x00, 123}, + {0x30, 0x37, 134}, + {0x30, 0x37, 146}, + {0x30, 0x37, 153}, + {0x00, 0x37, 154}, + } + for _, r := range rules { + if raw[r.i] < r.min || raw[r.i] > r.max { + return false + } + } + + for _, i := range []uint8{135, 147, 155} { + if raw[i] != 0x00 && raw[i] != 0x20 { + return false + } + } + + return true +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go new file mode 100644 index 0000000000..d17e32482c --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go @@ -0,0 +1,76 @@ +package magic + +import ( + "bytes" + "encoding/binary" +) + +var ( + // Flac matches a Free Lossless Audio Codec file. + Flac = prefix([]byte("\x66\x4C\x61\x43\x00\x00\x00\x22")) + // Midi matches a Musical Instrument Digital Interface file. + Midi = prefix([]byte("\x4D\x54\x68\x64")) + // Ape matches a Monkey's Audio file. + Ape = prefix([]byte("\x4D\x41\x43\x20\x96\x0F\x00\x00\x34\x00\x00\x00\x18\x00\x00\x00\x90\xE3")) + // MusePack matches a Musepack file. + MusePack = prefix([]byte("MPCK")) + // Au matches a Sun Microsystems au file. + Au = prefix([]byte("\x2E\x73\x6E\x64")) + // Amr matches an Adaptive Multi-Rate file. + Amr = prefix([]byte("\x23\x21\x41\x4D\x52")) + // Voc matches a Creative Voice file. + Voc = prefix([]byte("Creative Voice File")) + // M3u matches a Playlist file. + M3u = prefix([]byte("#EXTM3U")) + // AAC matches an Advanced Audio Coding file. + AAC = prefix([]byte{0xFF, 0xF1}, []byte{0xFF, 0xF9}) +) + +// Mp3 matches an mp3 file. +func Mp3(raw []byte, limit uint32) bool { + if len(raw) < 3 { + return false + } + + if bytes.HasPrefix(raw, []byte("ID3")) { + // MP3s with an ID3v2 tag will start with "ID3" + // ID3v1 tags, however appear at the end of the file. + return true + } + + // Match MP3 files without tags + switch binary.BigEndian.Uint16(raw[:2]) & 0xFFFE { + case 0xFFFA: + // MPEG ADTS, layer III, v1 + return true + case 0xFFF2: + // MPEG ADTS, layer III, v2 + return true + case 0xFFE2: + // MPEG ADTS, layer III, v2.5 + return true + } + + return false +} + +// Wav matches a Waveform Audio File Format file. +func Wav(raw []byte, limit uint32) bool { + return len(raw) > 12 && + bytes.Equal(raw[:4], []byte("RIFF")) && + bytes.Equal(raw[8:12], []byte{0x57, 0x41, 0x56, 0x45}) +} + +// Aiff matches Audio Interchange File Format file. +func Aiff(raw []byte, limit uint32) bool { + return len(raw) > 12 && + bytes.Equal(raw[:4], []byte{0x46, 0x4F, 0x52, 0x4D}) && + bytes.Equal(raw[8:12], []byte{0x41, 0x49, 0x46, 0x46}) +} + +// Qcp matches a Qualcomm Pure Voice file. +func Qcp(raw []byte, limit uint32) bool { + return len(raw) > 12 && + bytes.Equal(raw[:4], []byte("RIFF")) && + bytes.Equal(raw[8:12], []byte("QLCM")) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go new file mode 100644 index 0000000000..29bdded3e8 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go @@ -0,0 +1,196 @@ +package magic + +import ( + "bytes" + "debug/macho" + "encoding/binary" +) + +var ( + // Lnk matches Microsoft lnk binary format. + Lnk = prefix([]byte{0x4C, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00}) + // Wasm matches a web assembly File Format file. + Wasm = prefix([]byte{0x00, 0x61, 0x73, 0x6D}) + // Exe matches a Windows/DOS executable file. + Exe = prefix([]byte{0x4D, 0x5A}) + // Elf matches an Executable and Linkable Format file. + Elf = prefix([]byte{0x7F, 0x45, 0x4C, 0x46}) + // Nes matches a Nintendo Entertainment system ROM file. + Nes = prefix([]byte{0x4E, 0x45, 0x53, 0x1A}) + // SWF matches an Adobe Flash swf file. + SWF = prefix([]byte("CWS"), []byte("FWS"), []byte("ZWS")) + // Torrent has bencoded text in the beginning. + Torrent = prefix([]byte("d8:announce")) +) + +// Java bytecode and Mach-O binaries share the same magic number. +// More info here https://github.com/threatstack/libmagic/blob/master/magic/Magdir/cafebabe +func classOrMachOFat(in []byte) bool { + // There should be at least 8 bytes for both of them because the only way to + // quickly distinguish them is by comparing byte at position 7 + if len(in) < 8 { + return false + } + + return bytes.HasPrefix(in, []byte{0xCA, 0xFE, 0xBA, 0xBE}) +} + +// Class matches a java class file. +func Class(raw []byte, limit uint32) bool { + return classOrMachOFat(raw) && raw[7] > 30 +} + +// MachO matches Mach-O binaries format. +func MachO(raw []byte, limit uint32) bool { + if classOrMachOFat(raw) && raw[7] < 20 { + return true + } + + if len(raw) < 4 { + return false + } + + be := binary.BigEndian.Uint32(raw) + le := binary.LittleEndian.Uint32(raw) + + return be == macho.Magic32 || + le == macho.Magic32 || + be == macho.Magic64 || + le == macho.Magic64 +} + +// Dbf matches a dBase file. +// https://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm +func Dbf(raw []byte, limit uint32) bool { + if len(raw) < 68 { + return false + } + + // 3rd and 4th bytes contain the last update month and day of month. + if !(0 < raw[2] && raw[2] < 13 && 0 < raw[3] && raw[3] < 32) { + return false + } + + // 12, 13, 30, 31 are reserved bytes and always filled with 0x00. + if raw[12] != 0x00 || raw[13] != 0x00 || raw[30] != 0x00 || raw[31] != 0x00 { + return false + } + // Production MDX flag; + // 0x01 if a production .MDX file exists for this table; + // 0x00 if no .MDX file exists. + if raw[28] > 0x01 { + return false + } + + // dbf type is dictated by the first byte. + dbfTypes := []byte{ + 0x02, 0x03, 0x04, 0x05, 0x30, 0x31, 0x32, 0x42, 0x62, 0x7B, 0x82, + 0x83, 0x87, 0x8A, 0x8B, 0x8E, 0xB3, 0xCB, 0xE5, 0xF5, 0xF4, 0xFB, + } + for _, b := range dbfTypes { + if raw[0] == b { + return true + } + } + + return false +} + +// ElfObj matches an object file. +func ElfObj(raw []byte, limit uint32) bool { + return len(raw) > 17 && ((raw[16] == 0x01 && raw[17] == 0x00) || + (raw[16] == 0x00 && raw[17] == 0x01)) +} + +// ElfExe matches an executable file. +func ElfExe(raw []byte, limit uint32) bool { + return len(raw) > 17 && ((raw[16] == 0x02 && raw[17] == 0x00) || + (raw[16] == 0x00 && raw[17] == 0x02)) +} + +// ElfLib matches a shared library file. +func ElfLib(raw []byte, limit uint32) bool { + return len(raw) > 17 && ((raw[16] == 0x03 && raw[17] == 0x00) || + (raw[16] == 0x00 && raw[17] == 0x03)) +} + +// ElfDump matches a core dump file. +func ElfDump(raw []byte, limit uint32) bool { + return len(raw) > 17 && ((raw[16] == 0x04 && raw[17] == 0x00) || + (raw[16] == 0x00 && raw[17] == 0x04)) +} + +// Dcm matches a DICOM medical format file. +func Dcm(raw []byte, limit uint32) bool { + return len(raw) > 131 && + bytes.Equal(raw[128:132], []byte{0x44, 0x49, 0x43, 0x4D}) +} + +// Marc matches a MARC21 (MAchine-Readable Cataloging) file. +func Marc(raw []byte, limit uint32) bool { + // File is at least 24 bytes ("leader" field size). + if len(raw) < 24 { + return false + } + + // Fixed bytes at offset 20. + if !bytes.Equal(raw[20:24], []byte("4500")) { + return false + } + + // First 5 bytes are ASCII digits. + for i := 0; i < 5; i++ { + if raw[i] < '0' || raw[i] > '9' { + return false + } + } + + // Field terminator is present in first 2048 bytes. + return bytes.Contains(raw[:min(2048, len(raw))], []byte{0x1E}) +} + +// Glb matches a glTF model format file. +// GLB is the binary file format representation of 3D models save in +// the GL transmission Format (glTF). +// see more: https://docs.fileformat.com/3d/glb/ +// https://www.iana.org/assignments/media-types/model/gltf-binary +// GLB file format is based on little endian and its header structure +// show below: +// +// <-- 12-byte header --> +// | magic | version | length | +// | (uint32) | (uint32) | (uint32) | +// | \x67\x6C\x54\x46 | \x01\x00\x00\x00 | ... | +// | g l T F | 1 | ... | +var Glb = prefix([]byte("\x67\x6C\x54\x46\x02\x00\x00\x00"), + []byte("\x67\x6C\x54\x46\x01\x00\x00\x00")) + +// TzIf matches a Time Zone Information Format (TZif) file. +// See more: https://tools.ietf.org/id/draft-murchison-tzdist-tzif-00.html#rfc.section.3 +// Its header structure is shown below: +// +---------------+---+ +// | magic (4) | <-+-- version (1) +// +---------------+---+---------------------------------------+ +// | [unused - reserved for future use] (15) | +// +---------------+---------------+---------------+-----------+ +// | isutccnt (4) | isstdcnt (4) | leapcnt (4) | +// +---------------+---------------+---------------+ +// | timecnt (4) | typecnt (4) | charcnt (4) | +func TzIf(raw []byte, limit uint32) bool { + // File is at least 44 bytes (header size). + if len(raw) < 44 { + return false + } + + if !bytes.HasPrefix(raw, []byte("TZif")) { + return false + } + + // Field "typecnt" MUST not be zero. + if binary.BigEndian.Uint32(raw[36:40]) == 0 { + return false + } + + // Version has to be NUL (0x00), '2' (0x32) or '3' (0x33). + return raw[4] == 0x00 || raw[4] == 0x32 || raw[4] == 0x33 +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/database.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/database.go new file mode 100644 index 0000000000..cb1fed12f7 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/database.go @@ -0,0 +1,13 @@ +package magic + +var ( + // Sqlite matches an SQLite database file. + Sqlite = prefix([]byte{ + 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, + 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00, + }) + // MsAccessAce matches Microsoft Access dababase file. + MsAccessAce = offset([]byte("Standard ACE DB"), 4) + // MsAccessMdb matches legacy Microsoft Access database file (JET, 2003 and earlier). + MsAccessMdb = offset([]byte("Standard Jet DB"), 4) +) diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go new file mode 100644 index 0000000000..b3b26d5a12 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go @@ -0,0 +1,62 @@ +package magic + +import "bytes" + +var ( + // Pdf matches a Portable Document Format file. + // https://github.com/file/file/blob/11010cc805546a3e35597e67e1129a481aed40e8/magic/Magdir/pdf + Pdf = prefix( + // usual pdf signature + []byte("%PDF-"), + // new-line prefixed signature + []byte("\012%PDF-"), + // UTF-8 BOM prefixed signature + []byte("\xef\xbb\xbf%PDF-"), + ) + // Fdf matches a Forms Data Format file. + Fdf = prefix([]byte("%FDF")) + // Mobi matches a Mobi file. + Mobi = offset([]byte("BOOKMOBI"), 60) + // Lit matches a Microsoft Lit file. + Lit = prefix([]byte("ITOLITLS")) +) + +// DjVu matches a DjVu file. +func DjVu(raw []byte, limit uint32) bool { + if len(raw) < 12 { + return false + } + if !bytes.HasPrefix(raw, []byte{0x41, 0x54, 0x26, 0x54, 0x46, 0x4F, 0x52, 0x4D}) { + return false + } + return bytes.HasPrefix(raw[12:], []byte("DJVM")) || + bytes.HasPrefix(raw[12:], []byte("DJVU")) || + bytes.HasPrefix(raw[12:], []byte("DJVI")) || + bytes.HasPrefix(raw[12:], []byte("THUM")) +} + +// P7s matches an .p7s signature File (PEM, Base64). +func P7s(raw []byte, limit uint32) bool { + // Check for PEM Encoding. + if bytes.HasPrefix(raw, []byte("-----BEGIN PKCS7")) { + return true + } + // Check if DER Encoding is long enough. + if len(raw) < 20 { + return false + } + // Magic Bytes for the signedData ASN.1 encoding. + startHeader := [][]byte{{0x30, 0x80}, {0x30, 0x81}, {0x30, 0x82}, {0x30, 0x83}, {0x30, 0x84}} + signedDataMatch := []byte{0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07} + // Check if Header is correct. There are multiple valid headers. + for i, match := range startHeader { + // If first bytes match, then check for ASN.1 Object Type. + if bytes.HasPrefix(raw, match) { + if bytes.HasPrefix(raw[i+2:], signedDataMatch) { + return true + } + } + } + + return false +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/font.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/font.go new file mode 100644 index 0000000000..43af28212e --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/font.go @@ -0,0 +1,39 @@ +package magic + +import ( + "bytes" +) + +var ( + // Woff matches a Web Open Font Format file. + Woff = prefix([]byte("wOFF")) + // Woff2 matches a Web Open Font Format version 2 file. + Woff2 = prefix([]byte("wOF2")) + // Otf matches an OpenType font file. + Otf = prefix([]byte{0x4F, 0x54, 0x54, 0x4F, 0x00}) +) + +// Ttf matches a TrueType font file. +func Ttf(raw []byte, limit uint32) bool { + if !bytes.HasPrefix(raw, []byte{0x00, 0x01, 0x00, 0x00}) { + return false + } + return !MsAccessAce(raw, limit) && !MsAccessMdb(raw, limit) +} + +// Eot matches an Embedded OpenType font file. +func Eot(raw []byte, limit uint32) bool { + return len(raw) > 35 && + bytes.Equal(raw[34:36], []byte{0x4C, 0x50}) && + (bytes.Equal(raw[8:11], []byte{0x02, 0x00, 0x01}) || + bytes.Equal(raw[8:11], []byte{0x01, 0x00, 0x00}) || + bytes.Equal(raw[8:11], []byte{0x02, 0x00, 0x02})) +} + +// Ttc matches a TrueType Collection font file. +func Ttc(raw []byte, limit uint32) bool { + return len(raw) > 7 && + bytes.HasPrefix(raw, []byte("ttcf")) && + (bytes.Equal(raw[4:8], []byte{0x00, 0x01, 0x00, 0x00}) || + bytes.Equal(raw[4:8], []byte{0x00, 0x02, 0x00, 0x00})) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ftyp.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ftyp.go new file mode 100644 index 0000000000..6575b4aecd --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ftyp.go @@ -0,0 +1,88 @@ +package magic + +import "bytes" + +var ( + // AVIF matches an AV1 Image File Format still or animated. + // Wikipedia page seems outdated listing image/avif-sequence for animations. + // https://github.com/AOMediaCodec/av1-avif/issues/59 + AVIF = ftyp([]byte("avif"), []byte("avis")) + // Mp4 matches an MP4 file. + Mp4 = ftyp( + []byte("avc1"), []byte("dash"), []byte("iso2"), []byte("iso3"), + []byte("iso4"), []byte("iso5"), []byte("iso6"), []byte("isom"), + []byte("mmp4"), []byte("mp41"), []byte("mp42"), []byte("mp4v"), + []byte("mp71"), []byte("MSNV"), []byte("NDAS"), []byte("NDSC"), + []byte("NSDC"), []byte("NSDH"), []byte("NDSM"), []byte("NDSP"), + []byte("NDSS"), []byte("NDXC"), []byte("NDXH"), []byte("NDXM"), + []byte("NDXP"), []byte("NDXS"), []byte("F4V "), []byte("F4P "), + ) + // ThreeGP matches a 3GPP file. + ThreeGP = ftyp( + []byte("3gp1"), []byte("3gp2"), []byte("3gp3"), []byte("3gp4"), + []byte("3gp5"), []byte("3gp6"), []byte("3gp7"), []byte("3gs7"), + []byte("3ge6"), []byte("3ge7"), []byte("3gg6"), + ) + // ThreeG2 matches a 3GPP2 file. + ThreeG2 = ftyp( + []byte("3g24"), []byte("3g25"), []byte("3g26"), []byte("3g2a"), + []byte("3g2b"), []byte("3g2c"), []byte("KDDI"), + ) + // AMp4 matches an audio MP4 file. + AMp4 = ftyp( + // audio for Adobe Flash Player 9+ + []byte("F4A "), []byte("F4B "), + // Apple iTunes AAC-LC (.M4A) Audio + []byte("M4B "), []byte("M4P "), + // MPEG-4 (.MP4) for SonyPSP + []byte("MSNV"), + // Nero Digital AAC Audio + []byte("NDAS"), + ) + // Mqv matches a Sony / Mobile QuickTime file. + Mqv = ftyp([]byte("mqt ")) + // M4a matches an audio M4A file. + M4a = ftyp([]byte("M4A ")) + // M4v matches an Appl4 M4V video file. + M4v = ftyp([]byte("M4V "), []byte("M4VH"), []byte("M4VP")) + // Heic matches a High Efficiency Image Coding (HEIC) file. + Heic = ftyp([]byte("heic"), []byte("heix")) + // HeicSequence matches a High Efficiency Image Coding (HEIC) file sequence. + HeicSequence = ftyp([]byte("hevc"), []byte("hevx")) + // Heif matches a High Efficiency Image File Format (HEIF) file. + Heif = ftyp([]byte("mif1"), []byte("heim"), []byte("heis"), []byte("avic")) + // HeifSequence matches a High Efficiency Image File Format (HEIF) file sequence. + HeifSequence = ftyp([]byte("msf1"), []byte("hevm"), []byte("hevs"), []byte("avcs")) + // TODO: add support for remaining video formats at ftyps.com. +) + +// QuickTime matches a QuickTime File Format file. +// https://www.loc.gov/preservation/digital/formats/fdd/fdd000052.shtml +// https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFChap1/qtff1.html#//apple_ref/doc/uid/TP40000939-CH203-38190 +// https://github.com/apache/tika/blob/0f5570691133c75ac4472c3340354a6c4080b104/tika-core/src/main/resources/org/apache/tika/mime/tika-mimetypes.xml#L7758-L7777 +func QuickTime(raw []byte, _ uint32) bool { + if len(raw) < 12 { + return false + } + // First 4 bytes represent the size of the atom as unsigned int. + // Next 4 bytes are the type of the atom. + // For `ftyp` atoms check if first byte in size is 0, otherwise, a text file + // which happens to contain 'ftypqt ' at index 4 will trigger a false positive. + if bytes.Equal(raw[4:12], []byte("ftypqt ")) || + bytes.Equal(raw[4:12], []byte("ftypmoov")) { + return raw[0] == 0x00 + } + basicAtomTypes := [][]byte{ + []byte("moov\x00"), + []byte("mdat\x00"), + []byte("free\x00"), + []byte("skip\x00"), + []byte("pnot\x00"), + } + for _, a := range basicAtomTypes { + if bytes.Equal(raw[4:9], a) { + return true + } + } + return bytes.Equal(raw[:8], []byte("\x00\x00\x00\x08wide")) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go new file mode 100644 index 0000000000..f077e16724 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go @@ -0,0 +1,55 @@ +package magic + +import ( + "bytes" + "encoding/binary" +) + +// Shp matches a shape format file. +// https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf +func Shp(raw []byte, limit uint32) bool { + if len(raw) < 112 { + return false + } + + if !(binary.BigEndian.Uint32(raw[0:4]) == 9994 && + binary.BigEndian.Uint32(raw[4:8]) == 0 && + binary.BigEndian.Uint32(raw[8:12]) == 0 && + binary.BigEndian.Uint32(raw[12:16]) == 0 && + binary.BigEndian.Uint32(raw[16:20]) == 0 && + binary.BigEndian.Uint32(raw[20:24]) == 0 && + binary.LittleEndian.Uint32(raw[28:32]) == 1000) { + return false + } + + shapeTypes := []int{ + 0, // Null shape + 1, // Point + 3, // Polyline + 5, // Polygon + 8, // MultiPoint + 11, // PointZ + 13, // PolylineZ + 15, // PolygonZ + 18, // MultiPointZ + 21, // PointM + 23, // PolylineM + 25, // PolygonM + 28, // MultiPointM + 31, // MultiPatch + } + + for _, st := range shapeTypes { + if st == int(binary.LittleEndian.Uint32(raw[108:112])) { + return true + } + } + + return false +} + +// Shx matches a shape index format file. +// https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf +func Shx(raw []byte, limit uint32) bool { + return bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x27, 0x0A}) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go new file mode 100644 index 0000000000..0eb7e95f37 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go @@ -0,0 +1,110 @@ +package magic + +import "bytes" + +var ( + // Png matches a Portable Network Graphics file. + // https://www.w3.org/TR/PNG/ + Png = prefix([]byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}) + // Apng matches an Animated Portable Network Graphics file. + // https://wiki.mozilla.org/APNG_Specification + Apng = offset([]byte("acTL"), 37) + // Jpg matches a Joint Photographic Experts Group file. + Jpg = prefix([]byte{0xFF, 0xD8, 0xFF}) + // Jp2 matches a JPEG 2000 Image file (ISO 15444-1). + Jp2 = jpeg2k([]byte{0x6a, 0x70, 0x32, 0x20}) + // Jpx matches a JPEG 2000 Image file (ISO 15444-2). + Jpx = jpeg2k([]byte{0x6a, 0x70, 0x78, 0x20}) + // Jpm matches a JPEG 2000 Image file (ISO 15444-6). + Jpm = jpeg2k([]byte{0x6a, 0x70, 0x6D, 0x20}) + // Gif matches a Graphics Interchange Format file. + Gif = prefix([]byte("GIF87a"), []byte("GIF89a")) + // Bmp matches a bitmap image file. + Bmp = prefix([]byte{0x42, 0x4D}) + // Ps matches a PostScript file. + Ps = prefix([]byte("%!PS-Adobe-")) + // Psd matches a Photoshop Document file. + Psd = prefix([]byte("8BPS")) + // Ico matches an ICO file. + Ico = prefix([]byte{0x00, 0x00, 0x01, 0x00}, []byte{0x00, 0x00, 0x02, 0x00}) + // Icns matches an ICNS (Apple Icon Image format) file. + Icns = prefix([]byte("icns")) + // Tiff matches a Tagged Image File Format file. + Tiff = prefix([]byte{0x49, 0x49, 0x2A, 0x00}, []byte{0x4D, 0x4D, 0x00, 0x2A}) + // Bpg matches a Better Portable Graphics file. + Bpg = prefix([]byte{0x42, 0x50, 0x47, 0xFB}) + // Xcf matches GIMP image data. + Xcf = prefix([]byte("gimp xcf")) + // Pat matches GIMP pattern data. + Pat = offset([]byte("GPAT"), 20) + // Gbr matches GIMP brush data. + Gbr = offset([]byte("GIMP"), 20) + // Hdr matches Radiance HDR image. + // https://web.archive.org/web/20060913152809/http://local.wasp.uwa.edu.au/~pbourke/dataformats/pic/ + Hdr = prefix([]byte("#?RADIANCE\n")) + // Xpm matches X PixMap image data. + Xpm = prefix([]byte{0x2F, 0x2A, 0x20, 0x58, 0x50, 0x4D, 0x20, 0x2A, 0x2F}) + // Jxs matches a JPEG XS coded image file (ISO/IEC 21122-3). + Jxs = prefix([]byte{0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x53, 0x20, 0x0D, 0x0A, 0x87, 0x0A}) + // Jxr matches Microsoft HD JXR photo file. + Jxr = prefix([]byte{0x49, 0x49, 0xBC, 0x01}) +) + +func jpeg2k(sig []byte) Detector { + return func(raw []byte, _ uint32) bool { + if len(raw) < 24 { + return false + } + + if !bytes.Equal(raw[4:8], []byte{0x6A, 0x50, 0x20, 0x20}) && + !bytes.Equal(raw[4:8], []byte{0x6A, 0x50, 0x32, 0x20}) { + return false + } + return bytes.Equal(raw[20:24], sig) + } +} + +// Webp matches a WebP file. +func Webp(raw []byte, _ uint32) bool { + return len(raw) > 12 && + bytes.Equal(raw[0:4], []byte("RIFF")) && + bytes.Equal(raw[8:12], []byte{0x57, 0x45, 0x42, 0x50}) +} + +// Dwg matches a CAD drawing file. +func Dwg(raw []byte, _ uint32) bool { + if len(raw) < 6 || raw[0] != 0x41 || raw[1] != 0x43 { + return false + } + dwgVersions := [][]byte{ + {0x31, 0x2E, 0x34, 0x30}, + {0x31, 0x2E, 0x35, 0x30}, + {0x32, 0x2E, 0x31, 0x30}, + {0x31, 0x30, 0x30, 0x32}, + {0x31, 0x30, 0x30, 0x33}, + {0x31, 0x30, 0x30, 0x34}, + {0x31, 0x30, 0x30, 0x36}, + {0x31, 0x30, 0x30, 0x39}, + {0x31, 0x30, 0x31, 0x32}, + {0x31, 0x30, 0x31, 0x34}, + {0x31, 0x30, 0x31, 0x35}, + {0x31, 0x30, 0x31, 0x38}, + {0x31, 0x30, 0x32, 0x31}, + {0x31, 0x30, 0x32, 0x34}, + {0x31, 0x30, 0x33, 0x32}, + } + + for _, d := range dwgVersions { + if bytes.Equal(raw[2:6], d) { + return true + } + } + + return false +} + +// Jxl matches JPEG XL image file. +func Jxl(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0xFF, 0x0A}) || + bytes.HasPrefix(raw, []byte("\x00\x00\x00\x0cJXL\x20\x0d\x0a\x87\x0a")) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go new file mode 100644 index 0000000000..466058fbe2 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go @@ -0,0 +1,239 @@ +// Package magic holds the matching functions used to find MIME types. +package magic + +import ( + "bytes" + "fmt" +) + +type ( + // Detector receiveѕ the raw data of a file and returns whether the data + // meets any conditions. The limit parameter is an upper limit to the number + // of bytes received and is used to tell if the byte slice represents the + // whole file or is just the header of a file: len(raw) < limit or len(raw)>limit. + Detector func(raw []byte, limit uint32) bool + xmlSig struct { + // the local name of the root tag + localName []byte + // the namespace of the XML document + xmlns []byte + } +) + +// prefix creates a Detector which returns true if any of the provided signatures +// is the prefix of the raw input. +func prefix(sigs ...[]byte) Detector { + return func(raw []byte, limit uint32) bool { + for _, s := range sigs { + if bytes.HasPrefix(raw, s) { + return true + } + } + return false + } +} + +// offset creates a Detector which returns true if the provided signature can be +// found at offset in the raw input. +func offset(sig []byte, offset int) Detector { + return func(raw []byte, limit uint32) bool { + return len(raw) > offset && bytes.HasPrefix(raw[offset:], sig) + } +} + +// ciPrefix is like prefix but the check is case insensitive. +func ciPrefix(sigs ...[]byte) Detector { + return func(raw []byte, limit uint32) bool { + for _, s := range sigs { + if ciCheck(s, raw) { + return true + } + } + return false + } +} +func ciCheck(sig, raw []byte) bool { + if len(raw) < len(sig)+1 { + return false + } + // perform case insensitive check + for i, b := range sig { + db := raw[i] + if 'A' <= b && b <= 'Z' { + db &= 0xDF + } + if b != db { + return false + } + } + + return true +} + +// xml creates a Detector which returns true if any of the provided XML signatures +// matches the raw input. +func xml(sigs ...xmlSig) Detector { + return func(raw []byte, limit uint32) bool { + raw = trimLWS(raw) + if len(raw) == 0 { + return false + } + for _, s := range sigs { + if xmlCheck(s, raw) { + return true + } + } + return false + } +} +func xmlCheck(sig xmlSig, raw []byte) bool { + raw = raw[:min(len(raw), 512)] + + if len(sig.localName) == 0 { + return bytes.Index(raw, sig.xmlns) > 0 + } + if len(sig.xmlns) == 0 { + return bytes.Index(raw, sig.localName) > 0 + } + + localNameIndex := bytes.Index(raw, sig.localName) + return localNameIndex != -1 && localNameIndex < bytes.Index(raw, sig.xmlns) +} + +// markup creates a Detector which returns true is any of the HTML signatures +// matches the raw input. +func markup(sigs ...[]byte) Detector { + return func(raw []byte, limit uint32) bool { + if bytes.HasPrefix(raw, []byte{0xEF, 0xBB, 0xBF}) { + // We skip the UTF-8 BOM if present to ensure we correctly + // process any leading whitespace. The presence of the BOM + // is taken into account during charset detection in charset.go. + raw = trimLWS(raw[3:]) + } else { + raw = trimLWS(raw) + } + if len(raw) == 0 { + return false + } + for _, s := range sigs { + if markupCheck(s, raw) { + return true + } + } + return false + } +} +func markupCheck(sig, raw []byte) bool { + if len(raw) < len(sig)+1 { + return false + } + + // perform case insensitive check + for i, b := range sig { + db := raw[i] + if 'A' <= b && b <= 'Z' { + db &= 0xDF + } + if b != db { + return false + } + } + // Next byte must be space or right angle bracket. + if db := raw[len(sig)]; db != ' ' && db != '>' { + return false + } + + return true +} + +// ftyp creates a Detector which returns true if any of the FTYP signatures +// matches the raw input. +func ftyp(sigs ...[]byte) Detector { + return func(raw []byte, limit uint32) bool { + if len(raw) < 12 { + return false + } + for _, s := range sigs { + if bytes.Equal(raw[4:12], append([]byte("ftyp"), s...)) { + return true + } + } + return false + } +} + +func newXMLSig(localName, xmlns string) xmlSig { + ret := xmlSig{xmlns: []byte(xmlns)} + if localName != "" { + ret.localName = []byte(fmt.Sprintf("<%s", localName)) + } + + return ret +} + +// A valid shebang starts with the "#!" characters, +// followed by any number of spaces, +// followed by the path to the interpreter, +// and, optionally, followed by the arguments for the interpreter. +// +// Ex: +// #! /usr/bin/env php +// /usr/bin/env is the interpreter, php is the first and only argument. +func shebang(sigs ...[]byte) Detector { + return func(raw []byte, limit uint32) bool { + for _, s := range sigs { + if shebangCheck(s, firstLine(raw)) { + return true + } + } + return false + } +} + +func shebangCheck(sig, raw []byte) bool { + if len(raw) < len(sig)+2 { + return false + } + if raw[0] != '#' || raw[1] != '!' { + return false + } + + return bytes.Equal(trimLWS(trimRWS(raw[2:])), sig) +} + +// trimLWS trims whitespace from beginning of the input. +func trimLWS(in []byte) []byte { + firstNonWS := 0 + for ; firstNonWS < len(in) && isWS(in[firstNonWS]); firstNonWS++ { + } + + return in[firstNonWS:] +} + +// trimRWS trims whitespace from the end of the input. +func trimRWS(in []byte) []byte { + lastNonWS := len(in) - 1 + for ; lastNonWS > 0 && isWS(in[lastNonWS]); lastNonWS-- { + } + + return in[:lastNonWS+1] +} + +func firstLine(in []byte) []byte { + lineEnd := 0 + for ; lineEnd < len(in) && in[lineEnd] != '\n'; lineEnd++ { + } + + return in[:lineEnd] +} + +func isWS(b byte) bool { + return b == '\t' || b == '\n' || b == '\x0c' || b == '\r' || b == ' ' +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go new file mode 100644 index 0000000000..5964ce596c --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go @@ -0,0 +1,225 @@ +package magic + +import ( + "bytes" + "encoding/binary" +) + +var ( + xlsxSigFiles = []string{ + "xl/worksheets/", + "xl/drawings/", + "xl/theme/", + "xl/_rels/", + "xl/styles.xml", + "xl/workbook.xml", + "xl/sharedStrings.xml", + } + docxSigFiles = []string{ + "word/media/", + "word/_rels/document.xml.rels", + "word/document.xml", + "word/styles.xml", + "word/fontTable.xml", + "word/settings.xml", + "word/numbering.xml", + "word/header", + "word/footer", + } + pptxSigFiles = []string{ + "ppt/slides/", + "ppt/media/", + "ppt/slideLayouts/", + "ppt/theme/", + "ppt/slideMasters/", + "ppt/tags/", + "ppt/notesMasters/", + "ppt/_rels/", + "ppt/handoutMasters/", + "ppt/notesSlides/", + "ppt/presentation.xml", + "ppt/tableStyles.xml", + "ppt/presProps.xml", + "ppt/viewProps.xml", + } +) + +// Xlsx matches a Microsoft Excel 2007 file. +func Xlsx(raw []byte, limit uint32) bool { + return zipContains(raw, xlsxSigFiles...) +} + +// Docx matches a Microsoft Word 2007 file. +func Docx(raw []byte, limit uint32) bool { + return zipContains(raw, docxSigFiles...) +} + +// Pptx matches a Microsoft PowerPoint 2007 file. +func Pptx(raw []byte, limit uint32) bool { + return zipContains(raw, pptxSigFiles...) +} + +// Ole matches an Open Linking and Embedding file. +// +// https://en.wikipedia.org/wiki/Object_Linking_and_Embedding +func Ole(raw []byte, limit uint32) bool { + return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}) +} + +// Aaf matches an Advanced Authoring Format file. +// See: https://pyaaf.readthedocs.io/en/latest/about.html +// See: https://en.wikipedia.org/wiki/Advanced_Authoring_Format +func Aaf(raw []byte, limit uint32) bool { + if len(raw) < 31 { + return false + } + return bytes.HasPrefix(raw[8:], []byte{0x41, 0x41, 0x46, 0x42, 0x0D, 0x00, 0x4F, 0x4D}) && + (raw[30] == 0x09 || raw[30] == 0x0C) +} + +// Doc matches a Microsoft Word 97-2003 file. +// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py +func Doc(raw []byte, _ uint32) bool { + clsids := [][]byte{ + // Microsoft Word 97-2003 Document (Word.Document.8) + {0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + // Microsoft Word 6.0-7.0 Document (Word.Document.6) + {0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + // Microsoft Word Picture (Word.Picture.8) + {0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + } + + for _, clsid := range clsids { + if matchOleClsid(raw, clsid) { + return true + } + } + + return false +} + +// Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation. +func Ppt(raw []byte, limit uint32) bool { + // Root CLSID test is the safest way to detect identify OLE, however, the format + // often places the root CLSID at the end of the file. + if matchOleClsid(raw, []byte{ + 0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11, + 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8, + }) || matchOleClsid(raw, []byte{ + 0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11, + 0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3, + }) { + return true + } + + lin := len(raw) + if lin < 520 { + return false + } + pptSubHeaders := [][]byte{ + {0xA0, 0x46, 0x1D, 0xF0}, + {0x00, 0x6E, 0x1E, 0xF0}, + {0x0F, 0x00, 0xE8, 0x03}, + } + for _, h := range pptSubHeaders { + if bytes.HasPrefix(raw[512:], h) { + return true + } + } + + if bytes.HasPrefix(raw[512:], []byte{0xFD, 0xFF, 0xFF, 0xFF}) && + raw[518] == 0x00 && raw[519] == 0x00 { + return true + } + + return lin > 1152 && bytes.Contains(raw[1152:min(4096, lin)], + []byte("P\x00o\x00w\x00e\x00r\x00P\x00o\x00i\x00n\x00t\x00 D\x00o\x00c\x00u\x00m\x00e\x00n\x00t")) +} + +// Xls matches a Microsoft Excel 97-2003 file. +func Xls(raw []byte, limit uint32) bool { + // Root CLSID test is the safest way to detect identify OLE, however, the format + // often places the root CLSID at the end of the file. + if matchOleClsid(raw, []byte{ + 0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + }) || matchOleClsid(raw, []byte{ + 0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + }) { + return true + } + + lin := len(raw) + if lin < 520 { + return false + } + xlsSubHeaders := [][]byte{ + {0x09, 0x08, 0x10, 0x00, 0x00, 0x06, 0x05, 0x00}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x10}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x1F}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x22}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x23}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x28}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x29}, + } + for _, h := range xlsSubHeaders { + if bytes.HasPrefix(raw[512:], h) { + return true + } + } + + return lin > 1152 && bytes.Contains(raw[1152:min(4096, lin)], + []byte("W\x00k\x00s\x00S\x00S\x00W\x00o\x00r\x00k\x00B\x00o\x00o\x00k")) +} + +// Pub matches a Microsoft Publisher file. +func Pub(raw []byte, limit uint32) bool { + return matchOleClsid(raw, []byte{ + 0x01, 0x12, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, + }) +} + +// Msg matches a Microsoft Outlook email file. +func Msg(raw []byte, limit uint32) bool { + return matchOleClsid(raw, []byte{ + 0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, + }) +} + +// Msi matches a Microsoft Windows Installer file. +// http://fileformats.archiveteam.org/wiki/Microsoft_Compound_File +func Msi(raw []byte, limit uint32) bool { + return matchOleClsid(raw, []byte{ + 0x84, 0x10, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, + }) +} + +// Helper to match by a specific CLSID of a compound file. +// +// http://fileformats.archiveteam.org/wiki/Microsoft_Compound_File +func matchOleClsid(in []byte, clsid []byte) bool { + // Microsoft Compound files v3 have a sector length of 512, while v4 has 4096. + // Change sector offset depending on file version. + // https://www.loc.gov/preservation/digital/formats/fdd/fdd000392.shtml + sectorLength := 512 + if len(in) < sectorLength { + return false + } + if in[26] == 0x04 && in[27] == 0x00 { + sectorLength = 4096 + } + + // SecID of first sector of the directory stream. + firstSecID := int(binary.LittleEndian.Uint32(in[48:52])) + + // Expected offset of CLSID for root storage object. + clsidOffset := sectorLength*(1+firstSecID) + 80 + + if len(in) <= clsidOffset+16 { + return false + } + + return bytes.HasPrefix(in[clsidOffset:], clsid) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ogg.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ogg.go new file mode 100644 index 0000000000..bb4cd781b6 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ogg.go @@ -0,0 +1,42 @@ +package magic + +import ( + "bytes" +) + +/* + NOTE: + + In May 2003, two Internet RFCs were published relating to the format. + The Ogg bitstream was defined in RFC 3533 (which is classified as + 'informative') and its Internet content type (application/ogg) in RFC + 3534 (which is, as of 2006, a proposed standard protocol). In + September 2008, RFC 3534 was obsoleted by RFC 5334, which added + content types video/ogg, audio/ogg and filename extensions .ogx, .ogv, + .oga, .spx. + + See: + https://tools.ietf.org/html/rfc3533 + https://developer.mozilla.org/en-US/docs/Web/HTTP/Configuring_servers_for_Ogg_media#Serve_media_with_the_correct_MIME_type + https://github.com/file/file/blob/master/magic/Magdir/vorbis +*/ + +// Ogg matches an Ogg file. +func Ogg(raw []byte, limit uint32) bool { + return bytes.HasPrefix(raw, []byte("\x4F\x67\x67\x53\x00")) +} + +// OggAudio matches an audio ogg file. +func OggAudio(raw []byte, limit uint32) bool { + return len(raw) >= 37 && (bytes.HasPrefix(raw[28:], []byte("\x7fFLAC")) || + bytes.HasPrefix(raw[28:], []byte("\x01vorbis")) || + bytes.HasPrefix(raw[28:], []byte("OpusHead")) || + bytes.HasPrefix(raw[28:], []byte("Speex\x20\x20\x20"))) +} + +// OggVideo matches a video ogg file. +func OggVideo(raw []byte, limit uint32) bool { + return len(raw) >= 37 && (bytes.HasPrefix(raw[28:], []byte("\x80theora")) || + bytes.HasPrefix(raw[28:], []byte("fishead\x00")) || + bytes.HasPrefix(raw[28:], []byte("\x01video\x00\x00\x00"))) // OGM video +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go new file mode 100644 index 0000000000..e2a03caf50 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go @@ -0,0 +1,375 @@ +package magic + +import ( + "bufio" + "bytes" + "strings" + "time" + + "github.com/gabriel-vasile/mimetype/internal/charset" + "github.com/gabriel-vasile/mimetype/internal/json" +) + +var ( + // HTML matches a Hypertext Markup Language file. + HTML = markup( + []byte(" 0 +} + +// GeoJSON matches a RFC 7946 GeoJSON file. +// +// GeoJSON detection implies searching for key:value pairs like: `"type": "Feature"` +// in the input. +// BUG(gabriel-vasile): The "type" key should be searched for in the root object. +func GeoJSON(raw []byte, limit uint32) bool { + raw = trimLWS(raw) + if len(raw) == 0 { + return false + } + // GeoJSON is always a JSON object, not a JSON array or any other JSON value. + if raw[0] != '{' { + return false + } + + s := []byte(`"type"`) + si, sl := bytes.Index(raw, s), len(s) + + if si == -1 { + return false + } + + // If the "type" string is the suffix of the input, + // there is no need to search for the value of the key. + if si+sl == len(raw) { + return false + } + // Skip the "type" part. + raw = raw[si+sl:] + // Skip any whitespace before the colon. + raw = trimLWS(raw) + // Check for colon. + if len(raw) == 0 || raw[0] != ':' { + return false + } + // Skip any whitespace after the colon. + raw = trimLWS(raw[1:]) + + geoJSONTypes := [][]byte{ + []byte(`"Feature"`), + []byte(`"FeatureCollection"`), + []byte(`"Point"`), + []byte(`"LineString"`), + []byte(`"Polygon"`), + []byte(`"MultiPoint"`), + []byte(`"MultiLineString"`), + []byte(`"MultiPolygon"`), + []byte(`"GeometryCollection"`), + } + for _, t := range geoJSONTypes { + if bytes.HasPrefix(raw, t) { + return true + } + } + + return false +} + +// NdJSON matches a Newline delimited JSON file. All complete lines from raw +// must be valid JSON documents meaning they contain one of the valid JSON data +// types. +func NdJSON(raw []byte, limit uint32) bool { + lCount, hasObjOrArr := 0, false + sc := bufio.NewScanner(dropLastLine(raw, limit)) + for sc.Scan() { + l := sc.Bytes() + // Empty lines are allowed in NDJSON. + if l = trimRWS(trimLWS(l)); len(l) == 0 { + continue + } + _, err := json.Scan(l) + if err != nil { + return false + } + if l[0] == '[' || l[0] == '{' { + hasObjOrArr = true + } + lCount++ + } + + return lCount > 1 && hasObjOrArr +} + +// HAR matches a HAR Spec file. +// Spec: http://www.softwareishard.com/blog/har-12-spec/ +func HAR(raw []byte, limit uint32) bool { + s := []byte(`"log"`) + si, sl := bytes.Index(raw, s), len(s) + + if si == -1 { + return false + } + + // If the "log" string is the suffix of the input, + // there is no need to search for the value of the key. + if si+sl == len(raw) { + return false + } + // Skip the "log" part. + raw = raw[si+sl:] + // Skip any whitespace before the colon. + raw = trimLWS(raw) + // Check for colon. + if len(raw) == 0 || raw[0] != ':' { + return false + } + // Skip any whitespace after the colon. + raw = trimLWS(raw[1:]) + + harJSONTypes := [][]byte{ + []byte(`"version"`), + []byte(`"creator"`), + []byte(`"entries"`), + } + for _, t := range harJSONTypes { + si := bytes.Index(raw, t) + if si > -1 { + return true + } + } + + return false +} + +// Svg matches a SVG file. +func Svg(raw []byte, limit uint32) bool { + return bytes.Contains(raw, []byte(" 00:02:19,376) limits secondLine + // length to exactly 29 characters. + if len(secondLine) != 29 { + return false + } + // Decimal separator of fractional seconds in the timestamps must be a + // comma, not a period. + if strings.Contains(secondLine, ".") { + return false + } + // For Go <1.17, comma is not recognised as a decimal separator by `time.Parse`. + secondLine = strings.ReplaceAll(secondLine, ",", ".") + // Second line must be a time range. + ts := strings.Split(secondLine, " --> ") + if len(ts) != 2 { + return false + } + const layout = "15:04:05.000" + t0, err := time.Parse(layout, ts[0]) + if err != nil { + return false + } + t1, err := time.Parse(layout, ts[1]) + if err != nil { + return false + } + if t0.After(t1) { + return false + } + + // A third line must exist and not be empty. This is the actual subtitle text. + return s.Scan() && len(s.Bytes()) != 0 +} + +// Vtt matches a Web Video Text Tracks (WebVTT) file. See +// https://www.iana.org/assignments/media-types/text/vtt. +func Vtt(raw []byte, limit uint32) bool { + // Prefix match. + prefixes := [][]byte{ + {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0A}, // UTF-8 BOM, "WEBVTT" and a line feed + {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0D}, // UTF-8 BOM, "WEBVTT" and a carriage return + {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x20}, // UTF-8 BOM, "WEBVTT" and a space + {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x09}, // UTF-8 BOM, "WEBVTT" and a horizontal tab + {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0A}, // "WEBVTT" and a line feed + {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0D}, // "WEBVTT" and a carriage return + {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x20}, // "WEBVTT" and a space + {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x09}, // "WEBVTT" and a horizontal tab + } + for _, p := range prefixes { + if bytes.HasPrefix(raw, p) { + return true + } + } + + // Exact match. + return bytes.Equal(raw, []byte{0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) || // UTF-8 BOM and "WEBVTT" + bytes.Equal(raw, []byte{0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) // "WEBVTT" +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go new file mode 100644 index 0000000000..6a1561923c --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go @@ -0,0 +1,51 @@ +package magic + +import ( + "bytes" + "encoding/csv" + "io" +) + +// Csv matches a comma-separated values file. +func Csv(raw []byte, limit uint32) bool { + return sv(raw, ',', limit) +} + +// Tsv matches a tab-separated values file. +func Tsv(raw []byte, limit uint32) bool { + return sv(raw, '\t', limit) +} + +func sv(in []byte, comma rune, limit uint32) bool { + r := csv.NewReader(dropLastLine(in, limit)) + r.Comma = comma + r.TrimLeadingSpace = true + r.LazyQuotes = true + r.Comment = '#' + + lines, err := r.ReadAll() + return err == nil && r.FieldsPerRecord > 1 && len(lines) > 1 +} + +// dropLastLine drops the last incomplete line from b. +// +// mimetype limits itself to ReadLimit bytes when performing a detection. +// This means, for file formats like CSV for NDJSON, the last line of the input +// can be an incomplete line. +func dropLastLine(b []byte, cutAt uint32) io.Reader { + if cutAt == 0 { + return bytes.NewReader(b) + } + if uint32(len(b)) >= cutAt { + for i := cutAt - 1; i > 0; i-- { + if b[i] == '\n' { + return bytes.NewReader(b[:i]) + } + } + + // No newline was found between the 0 index and cutAt. + return bytes.NewReader(b[:cutAt]) + } + + return bytes.NewReader(b) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go new file mode 100644 index 0000000000..9caf55538a --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go @@ -0,0 +1,85 @@ +package magic + +import ( + "bytes" +) + +var ( + // Flv matches a Flash video file. + Flv = prefix([]byte("\x46\x4C\x56\x01")) + // Asf matches an Advanced Systems Format file. + Asf = prefix([]byte{ + 0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, + 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C, + }) + // Rmvb matches a RealMedia Variable Bitrate file. + Rmvb = prefix([]byte{0x2E, 0x52, 0x4D, 0x46}) +) + +// WebM matches a WebM file. +func WebM(raw []byte, limit uint32) bool { + return isMatroskaFileTypeMatched(raw, "webm") +} + +// Mkv matches a mkv file. +func Mkv(raw []byte, limit uint32) bool { + return isMatroskaFileTypeMatched(raw, "matroska") +} + +// isMatroskaFileTypeMatched is used for webm and mkv file matching. +// It checks for .Eߣ sequence. If the sequence is found, +// then it means it is Matroska media container, including WebM. +// Then it verifies which of the file type it is representing by matching the +// file specific string. +func isMatroskaFileTypeMatched(in []byte, flType string) bool { + if bytes.HasPrefix(in, []byte("\x1A\x45\xDF\xA3")) { + return isFileTypeNamePresent(in, flType) + } + return false +} + +// isFileTypeNamePresent accepts the matroska input data stream and searches +// for the given file type in the stream. Return whether a match is found. +// The logic of search is: find first instance of \x42\x82 and then +// search for given string after n bytes of above instance. +func isFileTypeNamePresent(in []byte, flType string) bool { + ind, maxInd, lenIn := 0, 4096, len(in) + if lenIn < maxInd { // restricting length to 4096 + maxInd = lenIn + } + ind = bytes.Index(in[:maxInd], []byte("\x42\x82")) + if ind > 0 && lenIn > ind+2 { + ind += 2 + + // filetype name will be present exactly + // n bytes after the match of the two bytes "\x42\x82" + n := vintWidth(int(in[ind])) + if lenIn > ind+n { + return bytes.HasPrefix(in[ind+n:], []byte(flType)) + } + } + return false +} + +// vintWidth parses the variable-integer width in matroska containers +func vintWidth(v int) int { + mask, max, num := 128, 8, 1 + for num < max && v&mask == 0 { + mask = mask >> 1 + num++ + } + return num +} + +// Mpeg matches a Moving Picture Experts Group file. +func Mpeg(raw []byte, limit uint32) bool { + return len(raw) > 3 && bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x01}) && + raw[3] >= 0xB0 && raw[3] <= 0xBF +} + +// Avi matches an Audio Video Interleaved file. +func Avi(raw []byte, limit uint32) bool { + return len(raw) > 16 && + bytes.Equal(raw[:4], []byte("RIFF")) && + bytes.Equal(raw[8:16], []byte("AVI LIST")) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go new file mode 100644 index 0000000000..dabee947b9 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go @@ -0,0 +1,92 @@ +package magic + +import ( + "bytes" + "encoding/binary" + "strings" +) + +var ( + // Odt matches an OpenDocument Text file. + Odt = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.text"), 30) + // Ott matches an OpenDocument Text Template file. + Ott = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.text-template"), 30) + // Ods matches an OpenDocument Spreadsheet file. + Ods = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.spreadsheet"), 30) + // Ots matches an OpenDocument Spreadsheet Template file. + Ots = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.spreadsheet-template"), 30) + // Odp matches an OpenDocument Presentation file. + Odp = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.presentation"), 30) + // Otp matches an OpenDocument Presentation Template file. + Otp = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.presentation-template"), 30) + // Odg matches an OpenDocument Drawing file. + Odg = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.graphics"), 30) + // Otg matches an OpenDocument Drawing Template file. + Otg = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.graphics-template"), 30) + // Odf matches an OpenDocument Formula file. + Odf = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.formula"), 30) + // Odc matches an OpenDocument Chart file. + Odc = offset([]byte("mimetypeapplication/vnd.oasis.opendocument.chart"), 30) + // Epub matches an EPUB file. + Epub = offset([]byte("mimetypeapplication/epub+zip"), 30) + // Sxc matches an OpenOffice Spreadsheet file. + Sxc = offset([]byte("mimetypeapplication/vnd.sun.xml.calc"), 30) +) + +// Zip matches a zip archive. +func Zip(raw []byte, limit uint32) bool { + return len(raw) > 3 && + raw[0] == 0x50 && raw[1] == 0x4B && + (raw[2] == 0x3 || raw[2] == 0x5 || raw[2] == 0x7) && + (raw[3] == 0x4 || raw[3] == 0x6 || raw[3] == 0x8) +} + +// Jar matches a Java archive file. +func Jar(raw []byte, limit uint32) bool { + return zipContains(raw, "META-INF/MANIFEST.MF") +} + +// zipTokenizer holds the source zip file and scanned index. +type zipTokenizer struct { + in []byte + i int // current index +} + +// next returns the next file name from the zip headers. +// https://web.archive.org/web/20191129114319/https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html +func (t *zipTokenizer) next() (fileName string) { + if t.i > len(t.in) { + return + } + in := t.in[t.i:] + // pkSig is the signature of the zip local file header. + pkSig := []byte("PK\003\004") + pkIndex := bytes.Index(in, pkSig) + // 30 is the offset of the file name in the header. + fNameOffset := pkIndex + 30 + // end if signature not found or file name offset outside of file. + if pkIndex == -1 || fNameOffset > len(in) { + return + } + + fNameLen := int(binary.LittleEndian.Uint16(in[pkIndex+26 : pkIndex+28])) + if fNameLen <= 0 || fNameOffset+fNameLen > len(in) { + return + } + t.i += fNameOffset + fNameLen + return string(in[fNameOffset : fNameOffset+fNameLen]) +} + +// zipContains returns true if the zip file headers from in contain any of the paths. +func zipContains(in []byte, paths ...string) bool { + t := zipTokenizer{in: in} + for i, tok := 0, t.next(); tok != ""; i, tok = i+1, t.next() { + for p := range paths { + if strings.HasPrefix(tok, paths[p]) { + return true + } + } + } + + return false +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/mime.go b/vendor/github.com/gabriel-vasile/mimetype/mime.go new file mode 100644 index 0000000000..62cb15f593 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/mime.go @@ -0,0 +1,186 @@ +package mimetype + +import ( + "mime" + + "github.com/gabriel-vasile/mimetype/internal/charset" + "github.com/gabriel-vasile/mimetype/internal/magic" +) + +// MIME struct holds information about a file format: the string representation +// of the MIME type, the extension and the parent file format. +type MIME struct { + mime string + aliases []string + extension string + // detector receives the raw input and a limit for the number of bytes it is + // allowed to check. It returns whether the input matches a signature or not. + detector magic.Detector + children []*MIME + parent *MIME +} + +// String returns the string representation of the MIME type, e.g., "application/zip". +func (m *MIME) String() string { + return m.mime +} + +// Extension returns the file extension associated with the MIME type. +// It includes the leading dot, as in ".html". When the file format does not +// have an extension, the empty string is returned. +func (m *MIME) Extension() string { + return m.extension +} + +// Parent returns the parent MIME type from the hierarchy. +// Each MIME type has a non-nil parent, except for the root MIME type. +// +// For example, the application/json and text/html MIME types have text/plain as +// their parent because they are text files who happen to contain JSON or HTML. +// Another example is the ZIP format, which is used as container +// for Microsoft Office files, EPUB files, JAR files, and others. +func (m *MIME) Parent() *MIME { + return m.parent +} + +// Is checks whether this MIME type, or any of its aliases, is equal to the +// expected MIME type. MIME type equality test is done on the "type/subtype" +// section, ignores any optional MIME parameters, ignores any leading and +// trailing whitespace, and is case insensitive. +func (m *MIME) Is(expectedMIME string) bool { + // Parsing is needed because some detected MIME types contain parameters + // that need to be stripped for the comparison. + expectedMIME, _, _ = mime.ParseMediaType(expectedMIME) + found, _, _ := mime.ParseMediaType(m.mime) + + if expectedMIME == found { + return true + } + + for _, alias := range m.aliases { + if alias == expectedMIME { + return true + } + } + + return false +} + +func newMIME( + mime, extension string, + detector magic.Detector, + children ...*MIME) *MIME { + m := &MIME{ + mime: mime, + extension: extension, + detector: detector, + children: children, + } + + for _, c := range children { + c.parent = m + } + + return m +} + +func (m *MIME) alias(aliases ...string) *MIME { + m.aliases = aliases + return m +} + +// match does a depth-first search on the signature tree. It returns the deepest +// successful node for which all the children detection functions fail. +func (m *MIME) match(in []byte, readLimit uint32) *MIME { + for _, c := range m.children { + if c.detector(in, readLimit) { + return c.match(in, readLimit) + } + } + + needsCharset := map[string]func([]byte) string{ + "text/plain": charset.FromPlain, + "text/html": charset.FromHTML, + "text/xml": charset.FromXML, + } + // ps holds optional MIME parameters. + ps := map[string]string{} + if f, ok := needsCharset[m.mime]; ok { + if cset := f(in); cset != "" { + ps["charset"] = cset + } + } + + return m.cloneHierarchy(ps) +} + +// flatten transforms an hierarchy of MIMEs into a slice of MIMEs. +func (m *MIME) flatten() []*MIME { + out := []*MIME{m} + for _, c := range m.children { + out = append(out, c.flatten()...) + } + + return out +} + +// clone creates a new MIME with the provided optional MIME parameters. +func (m *MIME) clone(ps map[string]string) *MIME { + clonedMIME := m.mime + if len(ps) > 0 { + clonedMIME = mime.FormatMediaType(m.mime, ps) + } + + return &MIME{ + mime: clonedMIME, + aliases: m.aliases, + extension: m.extension, + } +} + +// cloneHierarchy creates a clone of m and all its ancestors. The optional MIME +// parameters are set on the last child of the hierarchy. +func (m *MIME) cloneHierarchy(ps map[string]string) *MIME { + ret := m.clone(ps) + lastChild := ret + for p := m.Parent(); p != nil; p = p.Parent() { + pClone := p.clone(nil) + lastChild.parent = pClone + lastChild = pClone + } + + return ret +} + +func (m *MIME) lookup(mime string) *MIME { + for _, n := range append(m.aliases, m.mime) { + if n == mime { + return m + } + } + + for _, c := range m.children { + if m := c.lookup(mime); m != nil { + return m + } + } + return nil +} + +// Extend adds detection for a sub-format. The detector is a function +// returning true when the raw input file satisfies a signature. +// The sub-format will be detected if all the detectors in the parent chain return true. +// The extension should include the leading dot, as in ".html". +func (m *MIME) Extend(detector func(raw []byte, limit uint32) bool, mime, extension string, aliases ...string) { + c := &MIME{ + mime: mime, + extension: extension, + detector: detector, + parent: m, + aliases: aliases, + } + + mu.Lock() + m.children = append([]*MIME{c}, m.children...) + mu.Unlock() +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/mimetype.gif b/vendor/github.com/gabriel-vasile/mimetype/mimetype.gif new file mode 100644 index 0000000000..c3e8087673 Binary files /dev/null and b/vendor/github.com/gabriel-vasile/mimetype/mimetype.gif differ diff --git a/vendor/github.com/gabriel-vasile/mimetype/mimetype.go b/vendor/github.com/gabriel-vasile/mimetype/mimetype.go new file mode 100644 index 0000000000..08e68e334a --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/mimetype.go @@ -0,0 +1,123 @@ +// Package mimetype uses magic number signatures to detect the MIME type of a file. +// +// File formats are stored in a hierarchy with application/octet-stream at its root. +// For example, the hierarchy for HTML format is application/octet-stream -> +// text/plain -> text/html. +package mimetype + +import ( + "io" + "io/ioutil" + "mime" + "os" + "sync/atomic" +) + +// readLimit is the maximum number of bytes from the input used when detecting. +var readLimit uint32 = 3072 + +// Detect returns the MIME type found from the provided byte slice. +// +// The result is always a valid MIME type, with application/octet-stream +// returned when identification failed. +func Detect(in []byte) *MIME { + // Using atomic because readLimit can be written at the same time in other goroutine. + l := atomic.LoadUint32(&readLimit) + if l > 0 && len(in) > int(l) { + in = in[:l] + } + mu.RLock() + defer mu.RUnlock() + return root.match(in, l) +} + +// DetectReader returns the MIME type of the provided reader. +// +// The result is always a valid MIME type, with application/octet-stream +// returned when identification failed with or without an error. +// Any error returned is related to the reading from the input reader. +// +// DetectReader assumes the reader offset is at the start. If the input is an +// io.ReadSeeker you previously read from, it should be rewinded before detection: +// reader.Seek(0, io.SeekStart) +func DetectReader(r io.Reader) (*MIME, error) { + var in []byte + var err error + + // Using atomic because readLimit can be written at the same time in other goroutine. + l := atomic.LoadUint32(&readLimit) + if l == 0 { + in, err = ioutil.ReadAll(r) + if err != nil { + return errMIME, err + } + } else { + var n int + in = make([]byte, l) + // io.UnexpectedEOF means len(r) < len(in). It is not an error in this case, + // it just means the input file is smaller than the allocated bytes slice. + n, err = io.ReadFull(r, in) + if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { + return errMIME, err + } + in = in[:n] + } + + mu.RLock() + defer mu.RUnlock() + return root.match(in, l), nil +} + +// DetectFile returns the MIME type of the provided file. +// +// The result is always a valid MIME type, with application/octet-stream +// returned when identification failed with or without an error. +// Any error returned is related to the opening and reading from the input file. +func DetectFile(path string) (*MIME, error) { + f, err := os.Open(path) + if err != nil { + return errMIME, err + } + defer f.Close() + + return DetectReader(f) +} + +// EqualsAny reports whether s MIME type is equal to any MIME type in mimes. +// MIME type equality test is done on the "type/subtype" section, ignores +// any optional MIME parameters, ignores any leading and trailing whitespace, +// and is case insensitive. +func EqualsAny(s string, mimes ...string) bool { + s, _, _ = mime.ParseMediaType(s) + for _, m := range mimes { + m, _, _ = mime.ParseMediaType(m) + if s == m { + return true + } + } + + return false +} + +// SetLimit sets the maximum number of bytes read from input when detecting the MIME type. +// Increasing the limit provides better detection for file formats which store +// their magical numbers towards the end of the file: docx, pptx, xlsx, etc. +// A limit of 0 means the whole input file will be used. +func SetLimit(limit uint32) { + // Using atomic because readLimit can be read at the same time in other goroutine. + atomic.StoreUint32(&readLimit, limit) +} + +// Extend adds detection for other file formats. +// It is equivalent to calling Extend() on the root mime type "application/octet-stream". +func Extend(detector func(raw []byte, limit uint32) bool, mime, extension string, aliases ...string) { + root.Extend(detector, mime, extension, aliases...) +} + +// Lookup finds a MIME object by its string representation. +// The representation can be the main mime type, or any of its aliases. +func Lookup(mime string) *MIME { + mu.RLock() + defer mu.RUnlock() + return root.lookup(mime) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md new file mode 100644 index 0000000000..cdec4e674e --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md @@ -0,0 +1,178 @@ +## 172 Supported MIME types +This file is automatically generated when running tests. Do not edit manually. + +Extension | MIME type | Aliases +--------- | --------- | ------- +**n/a** | application/octet-stream | - +**.xpm** | image/x-xpixmap | - +**.7z** | application/x-7z-compressed | - +**.zip** | application/zip | application/x-zip, application/x-zip-compressed +**.xlsx** | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | - +**.docx** | application/vnd.openxmlformats-officedocument.wordprocessingml.document | - +**.pptx** | application/vnd.openxmlformats-officedocument.presentationml.presentation | - +**.epub** | application/epub+zip | - +**.jar** | application/jar | - +**.odt** | application/vnd.oasis.opendocument.text | application/x-vnd.oasis.opendocument.text +**.ott** | application/vnd.oasis.opendocument.text-template | application/x-vnd.oasis.opendocument.text-template +**.ods** | application/vnd.oasis.opendocument.spreadsheet | application/x-vnd.oasis.opendocument.spreadsheet +**.ots** | application/vnd.oasis.opendocument.spreadsheet-template | application/x-vnd.oasis.opendocument.spreadsheet-template +**.odp** | application/vnd.oasis.opendocument.presentation | application/x-vnd.oasis.opendocument.presentation +**.otp** | application/vnd.oasis.opendocument.presentation-template | application/x-vnd.oasis.opendocument.presentation-template +**.odg** | application/vnd.oasis.opendocument.graphics | application/x-vnd.oasis.opendocument.graphics +**.otg** | application/vnd.oasis.opendocument.graphics-template | application/x-vnd.oasis.opendocument.graphics-template +**.odf** | application/vnd.oasis.opendocument.formula | application/x-vnd.oasis.opendocument.formula +**.odc** | application/vnd.oasis.opendocument.chart | application/x-vnd.oasis.opendocument.chart +**.sxc** | application/vnd.sun.xml.calc | - +**.pdf** | application/pdf | application/x-pdf +**.fdf** | application/vnd.fdf | - +**n/a** | application/x-ole-storage | - +**.msi** | application/x-ms-installer | application/x-windows-installer, application/x-msi +**.aaf** | application/octet-stream | - +**.msg** | application/vnd.ms-outlook | - +**.xls** | application/vnd.ms-excel | application/msexcel +**.pub** | application/vnd.ms-publisher | - +**.ppt** | application/vnd.ms-powerpoint | application/mspowerpoint +**.doc** | application/msword | application/vnd.ms-word +**.ps** | application/postscript | - +**.psd** | image/vnd.adobe.photoshop | image/x-psd, application/photoshop +**.p7s** | application/pkcs7-signature | - +**.ogg** | application/ogg | application/x-ogg +**.oga** | audio/ogg | - +**.ogv** | video/ogg | - +**.png** | image/png | - +**.png** | image/vnd.mozilla.apng | - +**.jpg** | image/jpeg | - +**.jxl** | image/jxl | - +**.jp2** | image/jp2 | - +**.jpf** | image/jpx | - +**.jpm** | image/jpm | video/jpm +**.jxs** | image/jxs | - +**.gif** | image/gif | - +**.webp** | image/webp | - +**.exe** | application/vnd.microsoft.portable-executable | - +**n/a** | application/x-elf | - +**n/a** | application/x-object | - +**n/a** | application/x-executable | - +**.so** | application/x-sharedlib | - +**n/a** | application/x-coredump | - +**.a** | application/x-archive | application/x-unix-archive +**.deb** | application/vnd.debian.binary-package | - +**.tar** | application/x-tar | - +**.xar** | application/x-xar | - +**.bz2** | application/x-bzip2 | - +**.fits** | application/fits | - +**.tiff** | image/tiff | - +**.bmp** | image/bmp | image/x-bmp, image/x-ms-bmp +**.ico** | image/x-icon | - +**.mp3** | audio/mpeg | audio/x-mpeg, audio/mp3 +**.flac** | audio/flac | - +**.midi** | audio/midi | audio/mid, audio/sp-midi, audio/x-mid, audio/x-midi +**.ape** | audio/ape | - +**.mpc** | audio/musepack | - +**.amr** | audio/amr | audio/amr-nb +**.wav** | audio/wav | audio/x-wav, audio/vnd.wave, audio/wave +**.aiff** | audio/aiff | audio/x-aiff +**.au** | audio/basic | - +**.mpeg** | video/mpeg | - +**.mov** | video/quicktime | - +**.mqv** | video/quicktime | - +**.mp4** | video/mp4 | - +**.webm** | video/webm | audio/webm +**.3gp** | video/3gpp | video/3gp, audio/3gpp +**.3g2** | video/3gpp2 | video/3g2, audio/3gpp2 +**.avi** | video/x-msvideo | video/avi, video/msvideo +**.flv** | video/x-flv | - +**.mkv** | video/x-matroska | - +**.asf** | video/x-ms-asf | video/asf, video/x-ms-wmv +**.aac** | audio/aac | - +**.voc** | audio/x-unknown | - +**.mp4** | audio/mp4 | audio/x-m4a, audio/x-mp4a +**.m4a** | audio/x-m4a | - +**.m3u** | application/vnd.apple.mpegurl | audio/mpegurl +**.m4v** | video/x-m4v | - +**.rmvb** | application/vnd.rn-realmedia-vbr | - +**.gz** | application/gzip | application/x-gzip, application/x-gunzip, application/gzipped, application/gzip-compressed, application/x-gzip-compressed, gzip/document +**.class** | application/x-java-applet | - +**.swf** | application/x-shockwave-flash | - +**.crx** | application/x-chrome-extension | - +**.ttf** | font/ttf | font/sfnt, application/x-font-ttf, application/font-sfnt +**.woff** | font/woff | - +**.woff2** | font/woff2 | - +**.otf** | font/otf | - +**.ttc** | font/collection | - +**.eot** | application/vnd.ms-fontobject | - +**.wasm** | application/wasm | - +**.shx** | application/vnd.shx | - +**.shp** | application/vnd.shp | - +**.dbf** | application/x-dbf | - +**.dcm** | application/dicom | - +**.rar** | application/x-rar-compressed | application/x-rar +**.djvu** | image/vnd.djvu | - +**.mobi** | application/x-mobipocket-ebook | - +**.lit** | application/x-ms-reader | - +**.bpg** | image/bpg | - +**.sqlite** | application/vnd.sqlite3 | application/x-sqlite3 +**.dwg** | image/vnd.dwg | image/x-dwg, application/acad, application/x-acad, application/autocad_dwg, application/dwg, application/x-dwg, application/x-autocad, drawing/dwg +**.nes** | application/vnd.nintendo.snes.rom | - +**.lnk** | application/x-ms-shortcut | - +**.macho** | application/x-mach-binary | - +**.qcp** | audio/qcelp | - +**.icns** | image/x-icns | - +**.heic** | image/heic | - +**.heic** | image/heic-sequence | - +**.heif** | image/heif | - +**.heif** | image/heif-sequence | - +**.hdr** | image/vnd.radiance | - +**.mrc** | application/marc | - +**.mdb** | application/x-msaccess | - +**.accdb** | application/x-msaccess | - +**.zst** | application/zstd | - +**.cab** | application/vnd.ms-cab-compressed | - +**.rpm** | application/x-rpm | - +**.xz** | application/x-xz | - +**.lz** | application/lzip | application/x-lzip +**.torrent** | application/x-bittorrent | - +**.cpio** | application/x-cpio | - +**n/a** | application/tzif | - +**.xcf** | image/x-xcf | - +**.pat** | image/x-gimp-pat | - +**.gbr** | image/x-gimp-gbr | - +**.glb** | model/gltf-binary | - +**.avif** | image/avif | - +**.cab** | application/x-installshield | - +**.jxr** | image/jxr | image/vnd.ms-photo +**.txt** | text/plain | - +**.html** | text/html | - +**.svg** | image/svg+xml | - +**.xml** | text/xml | - +**.rss** | application/rss+xml | text/rss +**.atom** | application/atom+xml | - +**.x3d** | model/x3d+xml | - +**.kml** | application/vnd.google-earth.kml+xml | - +**.xlf** | application/x-xliff+xml | - +**.dae** | model/vnd.collada+xml | - +**.gml** | application/gml+xml | - +**.gpx** | application/gpx+xml | - +**.tcx** | application/vnd.garmin.tcx+xml | - +**.amf** | application/x-amf | - +**.3mf** | application/vnd.ms-package.3dmanufacturing-3dmodel+xml | - +**.xfdf** | application/vnd.adobe.xfdf | - +**.owl** | application/owl+xml | - +**.php** | text/x-php | - +**.js** | application/javascript | application/x-javascript, text/javascript +**.lua** | text/x-lua | - +**.pl** | text/x-perl | - +**.py** | text/x-python | text/x-script.python, application/x-python +**.json** | application/json | - +**.geojson** | application/geo+json | - +**.har** | application/json | - +**.ndjson** | application/x-ndjson | - +**.rtf** | text/rtf | - +**.srt** | application/x-subrip | application/x-srt, text/x-srt +**.tcl** | text/x-tcl | application/x-tcl +**.csv** | text/csv | - +**.tsv** | text/tab-separated-values | - +**.vcf** | text/vcard | - +**.ics** | text/calendar | - +**.warc** | application/warc | - +**.vtt** | text/vtt | - diff --git a/vendor/github.com/gabriel-vasile/mimetype/tree.go b/vendor/github.com/gabriel-vasile/mimetype/tree.go new file mode 100644 index 0000000000..253bd00649 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/tree.go @@ -0,0 +1,260 @@ +package mimetype + +import ( + "sync" + + "github.com/gabriel-vasile/mimetype/internal/magic" +) + +// mimetype stores the list of MIME types in a tree structure with +// "application/octet-stream" at the root of the hierarchy. The hierarchy +// approach minimizes the number of checks that need to be done on the input +// and allows for more precise results once the base type of file has been +// identified. +// +// root is a detector which passes for any slice of bytes. +// When a detector passes the check, the children detectors +// are tried in order to find a more accurate MIME type. +var root = newMIME("application/octet-stream", "", + func([]byte, uint32) bool { return true }, + xpm, sevenZ, zip, pdf, fdf, ole, ps, psd, p7s, ogg, png, jpg, jxl, jp2, jpx, + jpm, jxs, gif, webp, exe, elf, ar, tar, xar, bz2, fits, tiff, bmp, ico, mp3, flac, + midi, ape, musePack, amr, wav, aiff, au, mpeg, quickTime, mqv, mp4, webM, + threeGP, threeG2, avi, flv, mkv, asf, aac, voc, aMp4, m4a, m3u, m4v, rmvb, + gzip, class, swf, crx, ttf, woff, woff2, otf, ttc, eot, wasm, shx, dbf, dcm, rar, + djvu, mobi, lit, bpg, sqlite3, dwg, nes, lnk, macho, qcp, icns, heic, + heicSeq, heif, heifSeq, hdr, mrc, mdb, accdb, zstd, cab, rpm, xz, lzip, + torrent, cpio, tzif, xcf, pat, gbr, glb, avif, cabIS, jxr, + // Keep text last because it is the slowest check + text, +) + +// errMIME is returned from Detect functions when err is not nil. +// Detect could return root for erroneous cases, but it needs to lock mu in order to do so. +// errMIME is same as root but it does not require locking. +var errMIME = newMIME("application/octet-stream", "", func([]byte, uint32) bool { return false }) + +// mu guards access to the root MIME tree. Access to root must be synchronized with this lock. +var mu = &sync.RWMutex{} + +// The list of nodes appended to the root node. +var ( + xz = newMIME("application/x-xz", ".xz", magic.Xz) + gzip = newMIME("application/gzip", ".gz", magic.Gzip).alias( + "application/x-gzip", "application/x-gunzip", "application/gzipped", + "application/gzip-compressed", "application/x-gzip-compressed", + "gzip/document") + sevenZ = newMIME("application/x-7z-compressed", ".7z", magic.SevenZ) + zip = newMIME("application/zip", ".zip", magic.Zip, xlsx, docx, pptx, epub, jar, odt, ods, odp, odg, odf, odc, sxc). + alias("application/x-zip", "application/x-zip-compressed") + tar = newMIME("application/x-tar", ".tar", magic.Tar) + xar = newMIME("application/x-xar", ".xar", magic.Xar) + bz2 = newMIME("application/x-bzip2", ".bz2", magic.Bz2) + pdf = newMIME("application/pdf", ".pdf", magic.Pdf). + alias("application/x-pdf") + fdf = newMIME("application/vnd.fdf", ".fdf", magic.Fdf) + xlsx = newMIME("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx", magic.Xlsx) + docx = newMIME("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx", magic.Docx) + pptx = newMIME("application/vnd.openxmlformats-officedocument.presentationml.presentation", ".pptx", magic.Pptx) + epub = newMIME("application/epub+zip", ".epub", magic.Epub) + jar = newMIME("application/jar", ".jar", magic.Jar) + ole = newMIME("application/x-ole-storage", "", magic.Ole, msi, aaf, msg, xls, pub, ppt, doc) + msi = newMIME("application/x-ms-installer", ".msi", magic.Msi). + alias("application/x-windows-installer", "application/x-msi") + aaf = newMIME("application/octet-stream", ".aaf", magic.Aaf) + doc = newMIME("application/msword", ".doc", magic.Doc). + alias("application/vnd.ms-word") + ppt = newMIME("application/vnd.ms-powerpoint", ".ppt", magic.Ppt). + alias("application/mspowerpoint") + pub = newMIME("application/vnd.ms-publisher", ".pub", magic.Pub) + xls = newMIME("application/vnd.ms-excel", ".xls", magic.Xls). + alias("application/msexcel") + msg = newMIME("application/vnd.ms-outlook", ".msg", magic.Msg) + ps = newMIME("application/postscript", ".ps", magic.Ps) + fits = newMIME("application/fits", ".fits", magic.Fits) + ogg = newMIME("application/ogg", ".ogg", magic.Ogg, oggAudio, oggVideo). + alias("application/x-ogg") + oggAudio = newMIME("audio/ogg", ".oga", magic.OggAudio) + oggVideo = newMIME("video/ogg", ".ogv", magic.OggVideo) + text = newMIME("text/plain", ".txt", magic.Text, html, svg, xml, php, js, lua, perl, python, json, ndJSON, rtf, srt, tcl, csv, tsv, vCard, iCalendar, warc, vtt) + xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2) + json = newMIME("application/json", ".json", magic.JSON, geoJSON, har) + har = newMIME("application/json", ".har", magic.HAR) + csv = newMIME("text/csv", ".csv", magic.Csv) + tsv = newMIME("text/tab-separated-values", ".tsv", magic.Tsv) + geoJSON = newMIME("application/geo+json", ".geojson", magic.GeoJSON) + ndJSON = newMIME("application/x-ndjson", ".ndjson", magic.NdJSON) + html = newMIME("text/html", ".html", magic.HTML) + php = newMIME("text/x-php", ".php", magic.Php) + rtf = newMIME("text/rtf", ".rtf", magic.Rtf) + js = newMIME("application/javascript", ".js", magic.Js). + alias("application/x-javascript", "text/javascript") + srt = newMIME("application/x-subrip", ".srt", magic.Srt). + alias("application/x-srt", "text/x-srt") + vtt = newMIME("text/vtt", ".vtt", magic.Vtt) + lua = newMIME("text/x-lua", ".lua", magic.Lua) + perl = newMIME("text/x-perl", ".pl", magic.Perl) + python = newMIME("text/x-python", ".py", magic.Python). + alias("text/x-script.python", "application/x-python") + tcl = newMIME("text/x-tcl", ".tcl", magic.Tcl). + alias("application/x-tcl") + vCard = newMIME("text/vcard", ".vcf", magic.VCard) + iCalendar = newMIME("text/calendar", ".ics", magic.ICalendar) + svg = newMIME("image/svg+xml", ".svg", magic.Svg) + rss = newMIME("application/rss+xml", ".rss", magic.Rss). + alias("text/rss") + owl2 = newMIME("application/owl+xml", ".owl", magic.Owl2) + atom = newMIME("application/atom+xml", ".atom", magic.Atom) + x3d = newMIME("model/x3d+xml", ".x3d", magic.X3d) + kml = newMIME("application/vnd.google-earth.kml+xml", ".kml", magic.Kml) + xliff = newMIME("application/x-xliff+xml", ".xlf", magic.Xliff) + collada = newMIME("model/vnd.collada+xml", ".dae", magic.Collada) + gml = newMIME("application/gml+xml", ".gml", magic.Gml) + gpx = newMIME("application/gpx+xml", ".gpx", magic.Gpx) + tcx = newMIME("application/vnd.garmin.tcx+xml", ".tcx", magic.Tcx) + amf = newMIME("application/x-amf", ".amf", magic.Amf) + threemf = newMIME("application/vnd.ms-package.3dmanufacturing-3dmodel+xml", ".3mf", magic.Threemf) + png = newMIME("image/png", ".png", magic.Png, apng) + apng = newMIME("image/vnd.mozilla.apng", ".png", magic.Apng) + jpg = newMIME("image/jpeg", ".jpg", magic.Jpg) + jxl = newMIME("image/jxl", ".jxl", magic.Jxl) + jp2 = newMIME("image/jp2", ".jp2", magic.Jp2) + jpx = newMIME("image/jpx", ".jpf", magic.Jpx) + jpm = newMIME("image/jpm", ".jpm", magic.Jpm). + alias("video/jpm") + jxs = newMIME("image/jxs", ".jxs", magic.Jxs) + xpm = newMIME("image/x-xpixmap", ".xpm", magic.Xpm) + bpg = newMIME("image/bpg", ".bpg", magic.Bpg) + gif = newMIME("image/gif", ".gif", magic.Gif) + webp = newMIME("image/webp", ".webp", magic.Webp) + tiff = newMIME("image/tiff", ".tiff", magic.Tiff) + bmp = newMIME("image/bmp", ".bmp", magic.Bmp). + alias("image/x-bmp", "image/x-ms-bmp") + ico = newMIME("image/x-icon", ".ico", magic.Ico) + icns = newMIME("image/x-icns", ".icns", magic.Icns) + psd = newMIME("image/vnd.adobe.photoshop", ".psd", magic.Psd). + alias("image/x-psd", "application/photoshop") + heic = newMIME("image/heic", ".heic", magic.Heic) + heicSeq = newMIME("image/heic-sequence", ".heic", magic.HeicSequence) + heif = newMIME("image/heif", ".heif", magic.Heif) + heifSeq = newMIME("image/heif-sequence", ".heif", magic.HeifSequence) + hdr = newMIME("image/vnd.radiance", ".hdr", magic.Hdr) + avif = newMIME("image/avif", ".avif", magic.AVIF) + mp3 = newMIME("audio/mpeg", ".mp3", magic.Mp3). + alias("audio/x-mpeg", "audio/mp3") + flac = newMIME("audio/flac", ".flac", magic.Flac) + midi = newMIME("audio/midi", ".midi", magic.Midi). + alias("audio/mid", "audio/sp-midi", "audio/x-mid", "audio/x-midi") + ape = newMIME("audio/ape", ".ape", magic.Ape) + musePack = newMIME("audio/musepack", ".mpc", magic.MusePack) + wav = newMIME("audio/wav", ".wav", magic.Wav). + alias("audio/x-wav", "audio/vnd.wave", "audio/wave") + aiff = newMIME("audio/aiff", ".aiff", magic.Aiff).alias("audio/x-aiff") + au = newMIME("audio/basic", ".au", magic.Au) + amr = newMIME("audio/amr", ".amr", magic.Amr). + alias("audio/amr-nb") + aac = newMIME("audio/aac", ".aac", magic.AAC) + voc = newMIME("audio/x-unknown", ".voc", magic.Voc) + aMp4 = newMIME("audio/mp4", ".mp4", magic.AMp4). + alias("audio/x-m4a", "audio/x-mp4a") + m4a = newMIME("audio/x-m4a", ".m4a", magic.M4a) + m3u = newMIME("application/vnd.apple.mpegurl", ".m3u", magic.M3u). + alias("audio/mpegurl") + m4v = newMIME("video/x-m4v", ".m4v", magic.M4v) + mp4 = newMIME("video/mp4", ".mp4", magic.Mp4) + webM = newMIME("video/webm", ".webm", magic.WebM). + alias("audio/webm") + mpeg = newMIME("video/mpeg", ".mpeg", magic.Mpeg) + quickTime = newMIME("video/quicktime", ".mov", magic.QuickTime) + mqv = newMIME("video/quicktime", ".mqv", magic.Mqv) + threeGP = newMIME("video/3gpp", ".3gp", magic.ThreeGP). + alias("video/3gp", "audio/3gpp") + threeG2 = newMIME("video/3gpp2", ".3g2", magic.ThreeG2). + alias("video/3g2", "audio/3gpp2") + avi = newMIME("video/x-msvideo", ".avi", magic.Avi). + alias("video/avi", "video/msvideo") + flv = newMIME("video/x-flv", ".flv", magic.Flv) + mkv = newMIME("video/x-matroska", ".mkv", magic.Mkv) + asf = newMIME("video/x-ms-asf", ".asf", magic.Asf). + alias("video/asf", "video/x-ms-wmv") + rmvb = newMIME("application/vnd.rn-realmedia-vbr", ".rmvb", magic.Rmvb) + class = newMIME("application/x-java-applet", ".class", magic.Class) + swf = newMIME("application/x-shockwave-flash", ".swf", magic.SWF) + crx = newMIME("application/x-chrome-extension", ".crx", magic.CRX) + ttf = newMIME("font/ttf", ".ttf", magic.Ttf). + alias("font/sfnt", "application/x-font-ttf", "application/font-sfnt") + woff = newMIME("font/woff", ".woff", magic.Woff) + woff2 = newMIME("font/woff2", ".woff2", magic.Woff2) + otf = newMIME("font/otf", ".otf", magic.Otf) + ttc = newMIME("font/collection", ".ttc", magic.Ttc) + eot = newMIME("application/vnd.ms-fontobject", ".eot", magic.Eot) + wasm = newMIME("application/wasm", ".wasm", magic.Wasm) + shp = newMIME("application/vnd.shp", ".shp", magic.Shp) + shx = newMIME("application/vnd.shx", ".shx", magic.Shx, shp) + dbf = newMIME("application/x-dbf", ".dbf", magic.Dbf) + exe = newMIME("application/vnd.microsoft.portable-executable", ".exe", magic.Exe) + elf = newMIME("application/x-elf", "", magic.Elf, elfObj, elfExe, elfLib, elfDump) + elfObj = newMIME("application/x-object", "", magic.ElfObj) + elfExe = newMIME("application/x-executable", "", magic.ElfExe) + elfLib = newMIME("application/x-sharedlib", ".so", magic.ElfLib) + elfDump = newMIME("application/x-coredump", "", magic.ElfDump) + ar = newMIME("application/x-archive", ".a", magic.Ar, deb). + alias("application/x-unix-archive") + deb = newMIME("application/vnd.debian.binary-package", ".deb", magic.Deb) + rpm = newMIME("application/x-rpm", ".rpm", magic.RPM) + dcm = newMIME("application/dicom", ".dcm", magic.Dcm) + odt = newMIME("application/vnd.oasis.opendocument.text", ".odt", magic.Odt, ott). + alias("application/x-vnd.oasis.opendocument.text") + ott = newMIME("application/vnd.oasis.opendocument.text-template", ".ott", magic.Ott). + alias("application/x-vnd.oasis.opendocument.text-template") + ods = newMIME("application/vnd.oasis.opendocument.spreadsheet", ".ods", magic.Ods, ots). + alias("application/x-vnd.oasis.opendocument.spreadsheet") + ots = newMIME("application/vnd.oasis.opendocument.spreadsheet-template", ".ots", magic.Ots). + alias("application/x-vnd.oasis.opendocument.spreadsheet-template") + odp = newMIME("application/vnd.oasis.opendocument.presentation", ".odp", magic.Odp, otp). + alias("application/x-vnd.oasis.opendocument.presentation") + otp = newMIME("application/vnd.oasis.opendocument.presentation-template", ".otp", magic.Otp). + alias("application/x-vnd.oasis.opendocument.presentation-template") + odg = newMIME("application/vnd.oasis.opendocument.graphics", ".odg", magic.Odg, otg). + alias("application/x-vnd.oasis.opendocument.graphics") + otg = newMIME("application/vnd.oasis.opendocument.graphics-template", ".otg", magic.Otg). + alias("application/x-vnd.oasis.opendocument.graphics-template") + odf = newMIME("application/vnd.oasis.opendocument.formula", ".odf", magic.Odf). + alias("application/x-vnd.oasis.opendocument.formula") + odc = newMIME("application/vnd.oasis.opendocument.chart", ".odc", magic.Odc). + alias("application/x-vnd.oasis.opendocument.chart") + sxc = newMIME("application/vnd.sun.xml.calc", ".sxc", magic.Sxc) + rar = newMIME("application/x-rar-compressed", ".rar", magic.RAR). + alias("application/x-rar") + djvu = newMIME("image/vnd.djvu", ".djvu", magic.DjVu) + mobi = newMIME("application/x-mobipocket-ebook", ".mobi", magic.Mobi) + lit = newMIME("application/x-ms-reader", ".lit", magic.Lit) + sqlite3 = newMIME("application/vnd.sqlite3", ".sqlite", magic.Sqlite). + alias("application/x-sqlite3") + dwg = newMIME("image/vnd.dwg", ".dwg", magic.Dwg). + alias("image/x-dwg", "application/acad", "application/x-acad", + "application/autocad_dwg", "application/dwg", "application/x-dwg", + "application/x-autocad", "drawing/dwg") + warc = newMIME("application/warc", ".warc", magic.Warc) + nes = newMIME("application/vnd.nintendo.snes.rom", ".nes", magic.Nes) + lnk = newMIME("application/x-ms-shortcut", ".lnk", magic.Lnk) + macho = newMIME("application/x-mach-binary", ".macho", magic.MachO) + qcp = newMIME("audio/qcelp", ".qcp", magic.Qcp) + mrc = newMIME("application/marc", ".mrc", magic.Marc) + mdb = newMIME("application/x-msaccess", ".mdb", magic.MsAccessMdb) + accdb = newMIME("application/x-msaccess", ".accdb", magic.MsAccessAce) + zstd = newMIME("application/zstd", ".zst", magic.Zstd) + cab = newMIME("application/vnd.ms-cab-compressed", ".cab", magic.Cab) + cabIS = newMIME("application/x-installshield", ".cab", magic.InstallShieldCab) + lzip = newMIME("application/lzip", ".lz", magic.Lzip).alias("application/x-lzip") + torrent = newMIME("application/x-bittorrent", ".torrent", magic.Torrent) + cpio = newMIME("application/x-cpio", ".cpio", magic.Cpio) + tzif = newMIME("application/tzif", "", magic.TzIf) + p7s = newMIME("application/pkcs7-signature", ".p7s", magic.P7s) + xcf = newMIME("image/x-xcf", ".xcf", magic.Xcf) + pat = newMIME("image/x-gimp-pat", ".pat", magic.Pat) + gbr = newMIME("image/x-gimp-gbr", ".gbr", magic.Gbr) + xfdf = newMIME("application/vnd.adobe.xfdf", ".xfdf", magic.Xfdf) + glb = newMIME("model/gltf-binary", ".glb", magic.Glb) + jxr = newMIME("image/jxr", ".jxr", magic.Jxr).alias("image/vnd.ms-photo") +) diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/.travis.yml b/vendor/github.com/go-asn1-ber/asn1-ber/.travis.yml deleted file mode 100644 index 8bffb90170..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/.travis.yml +++ /dev/null @@ -1,39 +0,0 @@ -language: go - -go: - - 1.2.x - - 1.6.x - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x - - 1.14.x - - tip - -os: - - linux - -arch: - - amd64 - -dist: xenial - -env: - - GOARCH=amd64 - -jobs: - include: - - os: windows - go: 1.14.x - - os: osx - go: 1.14.x - - os: linux - go: 1.14.x - arch: arm64 - - os: linux - go: 1.14.x - env: - - GOARCH=386 - -script: - - go test -v -cover ./... || go test -v ./... diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/LICENSE b/vendor/github.com/go-asn1-ber/asn1-ber/LICENSE deleted file mode 100644 index 23f9425345..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2011-2015 Michael Mitton (mmitton@gmail.com) -Portions copyright (c) 2015-2016 go-asn1-ber Authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/README.md b/vendor/github.com/go-asn1-ber/asn1-ber/README.md deleted file mode 100644 index e3a9560d68..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/README.md +++ /dev/null @@ -1,24 +0,0 @@ -[![GoDoc](https://godoc.org/gopkg.in/asn1-ber.v1?status.svg)](https://godoc.org/gopkg.in/asn1-ber.v1) [![Build Status](https://travis-ci.org/go-asn1-ber/asn1-ber.svg)](https://travis-ci.org/go-asn1-ber/asn1-ber) - - -ASN1 BER Encoding / Decoding Library for the GO programming language. ---------------------------------------------------------------------- - -Required libraries: - None - -Working: - Very basic encoding / decoding needed for LDAP protocol - -Tests Implemented: - A few - -TODO: - Fix all encoding / decoding to conform to ASN1 BER spec - Implement Tests / Benchmarks - ---- - -The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/) -The design is licensed under the Creative Commons 3.0 Attributions license. -Read this article for more details: http://blog.golang.org/gopher diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/ber.go b/vendor/github.com/go-asn1-ber/asn1-ber/ber.go deleted file mode 100644 index 4fd7a66e18..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/ber.go +++ /dev/null @@ -1,620 +0,0 @@ -package ber - -import ( - "bytes" - "errors" - "fmt" - "io" - "math" - "os" - "reflect" - "time" - "unicode/utf8" -) - -// MaxPacketLengthBytes specifies the maximum allowed packet size when calling ReadPacket or DecodePacket. Set to 0 for -// no limit. -var MaxPacketLengthBytes int64 = math.MaxInt32 - -type Packet struct { - Identifier - Value interface{} - ByteValue []byte - Data *bytes.Buffer - Children []*Packet - Description string -} - -type Identifier struct { - ClassType Class - TagType Type - Tag Tag -} - -type Tag uint64 - -const ( - TagEOC Tag = 0x00 - TagBoolean Tag = 0x01 - TagInteger Tag = 0x02 - TagBitString Tag = 0x03 - TagOctetString Tag = 0x04 - TagNULL Tag = 0x05 - TagObjectIdentifier Tag = 0x06 - TagObjectDescriptor Tag = 0x07 - TagExternal Tag = 0x08 - TagRealFloat Tag = 0x09 - TagEnumerated Tag = 0x0a - TagEmbeddedPDV Tag = 0x0b - TagUTF8String Tag = 0x0c - TagRelativeOID Tag = 0x0d - TagSequence Tag = 0x10 - TagSet Tag = 0x11 - TagNumericString Tag = 0x12 - TagPrintableString Tag = 0x13 - TagT61String Tag = 0x14 - TagVideotexString Tag = 0x15 - TagIA5String Tag = 0x16 - TagUTCTime Tag = 0x17 - TagGeneralizedTime Tag = 0x18 - TagGraphicString Tag = 0x19 - TagVisibleString Tag = 0x1a - TagGeneralString Tag = 0x1b - TagUniversalString Tag = 0x1c - TagCharacterString Tag = 0x1d - TagBMPString Tag = 0x1e - TagBitmask Tag = 0x1f // xxx11111b - - // HighTag indicates the start of a high-tag byte sequence - HighTag Tag = 0x1f // xxx11111b - // HighTagContinueBitmask indicates the high-tag byte sequence should continue - HighTagContinueBitmask Tag = 0x80 // 10000000b - // HighTagValueBitmask obtains the tag value from a high-tag byte sequence byte - HighTagValueBitmask Tag = 0x7f // 01111111b -) - -const ( - // LengthLongFormBitmask is the mask to apply to the length byte to see if a long-form byte sequence is used - LengthLongFormBitmask = 0x80 - // LengthValueBitmask is the mask to apply to the length byte to get the number of bytes in the long-form byte sequence - LengthValueBitmask = 0x7f - - // LengthIndefinite is returned from readLength to indicate an indefinite length - LengthIndefinite = -1 -) - -var tagMap = map[Tag]string{ - TagEOC: "EOC (End-of-Content)", - TagBoolean: "Boolean", - TagInteger: "Integer", - TagBitString: "Bit String", - TagOctetString: "Octet String", - TagNULL: "NULL", - TagObjectIdentifier: "Object Identifier", - TagObjectDescriptor: "Object Descriptor", - TagExternal: "External", - TagRealFloat: "Real (float)", - TagEnumerated: "Enumerated", - TagEmbeddedPDV: "Embedded PDV", - TagUTF8String: "UTF8 String", - TagRelativeOID: "Relative-OID", - TagSequence: "Sequence and Sequence of", - TagSet: "Set and Set OF", - TagNumericString: "Numeric String", - TagPrintableString: "Printable String", - TagT61String: "T61 String", - TagVideotexString: "Videotex String", - TagIA5String: "IA5 String", - TagUTCTime: "UTC Time", - TagGeneralizedTime: "Generalized Time", - TagGraphicString: "Graphic String", - TagVisibleString: "Visible String", - TagGeneralString: "General String", - TagUniversalString: "Universal String", - TagCharacterString: "Character String", - TagBMPString: "BMP String", -} - -type Class uint8 - -const ( - ClassUniversal Class = 0 // 00xxxxxxb - ClassApplication Class = 64 // 01xxxxxxb - ClassContext Class = 128 // 10xxxxxxb - ClassPrivate Class = 192 // 11xxxxxxb - ClassBitmask Class = 192 // 11xxxxxxb -) - -var ClassMap = map[Class]string{ - ClassUniversal: "Universal", - ClassApplication: "Application", - ClassContext: "Context", - ClassPrivate: "Private", -} - -type Type uint8 - -const ( - TypePrimitive Type = 0 // xx0xxxxxb - TypeConstructed Type = 32 // xx1xxxxxb - TypeBitmask Type = 32 // xx1xxxxxb -) - -var TypeMap = map[Type]string{ - TypePrimitive: "Primitive", - TypeConstructed: "Constructed", -} - -var Debug = false - -func PrintBytes(out io.Writer, buf []byte, indent string) { - dataLines := make([]string, (len(buf)/30)+1) - numLines := make([]string, (len(buf)/30)+1) - - for i, b := range buf { - dataLines[i/30] += fmt.Sprintf("%02x ", b) - numLines[i/30] += fmt.Sprintf("%02d ", (i+1)%100) - } - - for i := 0; i < len(dataLines); i++ { - _, _ = out.Write([]byte(indent + dataLines[i] + "\n")) - _, _ = out.Write([]byte(indent + numLines[i] + "\n\n")) - } -} - -func WritePacket(out io.Writer, p *Packet) { - printPacket(out, p, 0, false) -} - -func PrintPacket(p *Packet) { - printPacket(os.Stdout, p, 0, false) -} - -func printPacket(out io.Writer, p *Packet, indent int, printBytes bool) { - indentStr := "" - - for len(indentStr) != indent { - indentStr += " " - } - - classStr := ClassMap[p.ClassType] - - tagTypeStr := TypeMap[p.TagType] - - tagStr := fmt.Sprintf("0x%02X", p.Tag) - - if p.ClassType == ClassUniversal { - tagStr = tagMap[p.Tag] - } - - value := fmt.Sprint(p.Value) - description := "" - - if p.Description != "" { - description = p.Description + ": " - } - - _, _ = fmt.Fprintf(out, "%s%s(%s, %s, %s) Len=%d %q\n", indentStr, description, classStr, tagTypeStr, tagStr, p.Data.Len(), value) - - if printBytes { - PrintBytes(out, p.Bytes(), indentStr) - } - - for _, child := range p.Children { - printPacket(out, child, indent+1, printBytes) - } -} - -// ReadPacket reads a single Packet from the reader. -func ReadPacket(reader io.Reader) (*Packet, error) { - p, _, err := readPacket(reader) - if err != nil { - return nil, err - } - return p, nil -} - -func DecodeString(data []byte) string { - return string(data) -} - -func ParseInt64(bytes []byte) (ret int64, err error) { - if len(bytes) > 8 { - // We'll overflow an int64 in this case. - err = fmt.Errorf("integer too large") - return - } - for bytesRead := 0; bytesRead < len(bytes); bytesRead++ { - ret <<= 8 - ret |= int64(bytes[bytesRead]) - } - - // Shift up and down in order to sign extend the result. - ret <<= 64 - uint8(len(bytes))*8 - ret >>= 64 - uint8(len(bytes))*8 - return -} - -func encodeInteger(i int64) []byte { - n := int64Length(i) - out := make([]byte, n) - - var j int - for ; n > 0; n-- { - out[j] = byte(i >> uint((n-1)*8)) - j++ - } - - return out -} - -func int64Length(i int64) (numBytes int) { - numBytes = 1 - - for i > 127 { - numBytes++ - i >>= 8 - } - - for i < -128 { - numBytes++ - i >>= 8 - } - - return -} - -// DecodePacket decodes the given bytes into a single Packet -// If a decode error is encountered, nil is returned. -func DecodePacket(data []byte) *Packet { - p, _, _ := readPacket(bytes.NewBuffer(data)) - - return p -} - -// DecodePacketErr decodes the given bytes into a single Packet -// If a decode error is encountered, nil is returned. -func DecodePacketErr(data []byte) (*Packet, error) { - p, _, err := readPacket(bytes.NewBuffer(data)) - if err != nil { - return nil, err - } - return p, nil -} - -// readPacket reads a single Packet from the reader, returning the number of bytes read. -func readPacket(reader io.Reader) (*Packet, int, error) { - identifier, length, read, err := readHeader(reader) - if err != nil { - return nil, read, err - } - - p := &Packet{ - Identifier: identifier, - } - - p.Data = new(bytes.Buffer) - p.Children = make([]*Packet, 0, 2) - p.Value = nil - - if p.TagType == TypeConstructed { - // TODO: if universal, ensure tag type is allowed to be constructed - - // Track how much content we've read - contentRead := 0 - for { - if length != LengthIndefinite { - // End if we've read what we've been told to - if contentRead == length { - break - } - // Detect if a packet boundary didn't fall on the expected length - if contentRead > length { - return nil, read, fmt.Errorf("expected to read %d bytes, read %d", length, contentRead) - } - } - - // Read the next packet - child, r, err := readPacket(reader) - if err != nil { - return nil, read, err - } - contentRead += r - read += r - - // Test is this is the EOC marker for our packet - if isEOCPacket(child) { - if length == LengthIndefinite { - break - } - return nil, read, errors.New("eoc child not allowed with definite length") - } - - // Append and continue - p.AppendChild(child) - } - return p, read, nil - } - - if length == LengthIndefinite { - return nil, read, errors.New("indefinite length used with primitive type") - } - - // Read definite-length content - if MaxPacketLengthBytes > 0 && int64(length) > MaxPacketLengthBytes { - return nil, read, fmt.Errorf("length %d greater than maximum %d", length, MaxPacketLengthBytes) - } - content := make([]byte, length) - if length > 0 { - _, err := io.ReadFull(reader, content) - if err != nil { - if err == io.EOF { - return nil, read, io.ErrUnexpectedEOF - } - return nil, read, err - } - read += length - } - - if p.ClassType == ClassUniversal { - p.Data.Write(content) - p.ByteValue = content - - switch p.Tag { - case TagEOC: - case TagBoolean: - val, _ := ParseInt64(content) - - p.Value = val != 0 - case TagInteger: - p.Value, _ = ParseInt64(content) - case TagBitString: - case TagOctetString: - // the actual string encoding is not known here - // (e.g. for LDAP content is already an UTF8-encoded - // string). Return the data without further processing - p.Value = DecodeString(content) - case TagNULL: - case TagObjectIdentifier: - case TagObjectDescriptor: - case TagExternal: - case TagRealFloat: - p.Value, err = ParseReal(content) - case TagEnumerated: - p.Value, _ = ParseInt64(content) - case TagEmbeddedPDV: - case TagUTF8String: - val := DecodeString(content) - if !utf8.Valid([]byte(val)) { - err = errors.New("invalid UTF-8 string") - } else { - p.Value = val - } - case TagRelativeOID: - case TagSequence: - case TagSet: - case TagNumericString: - case TagPrintableString: - val := DecodeString(content) - if err = isPrintableString(val); err == nil { - p.Value = val - } - case TagT61String: - case TagVideotexString: - case TagIA5String: - val := DecodeString(content) - for i, c := range val { - if c >= 0x7F { - err = fmt.Errorf("invalid character for IA5String at pos %d: %c", i, c) - break - } - } - if err == nil { - p.Value = val - } - case TagUTCTime: - case TagGeneralizedTime: - p.Value, err = ParseGeneralizedTime(content) - case TagGraphicString: - case TagVisibleString: - case TagGeneralString: - case TagUniversalString: - case TagCharacterString: - case TagBMPString: - } - } else { - p.Data.Write(content) - } - - return p, read, err -} - -func isPrintableString(val string) error { - for i, c := range val { - switch { - case c >= 'a' && c <= 'z': - case c >= 'A' && c <= 'Z': - case c >= '0' && c <= '9': - default: - switch c { - case '\'', '(', ')', '+', ',', '-', '.', '=', '/', ':', '?', ' ': - default: - return fmt.Errorf("invalid character in position %d", i) - } - } - } - return nil -} - -func (p *Packet) Bytes() []byte { - var out bytes.Buffer - - out.Write(encodeIdentifier(p.Identifier)) - out.Write(encodeLength(p.Data.Len())) - out.Write(p.Data.Bytes()) - - return out.Bytes() -} - -func (p *Packet) AppendChild(child *Packet) { - p.Data.Write(child.Bytes()) - p.Children = append(p.Children, child) -} - -func Encode(classType Class, tagType Type, tag Tag, value interface{}, description string) *Packet { - p := new(Packet) - - p.ClassType = classType - p.TagType = tagType - p.Tag = tag - p.Data = new(bytes.Buffer) - - p.Children = make([]*Packet, 0, 2) - - p.Value = value - p.Description = description - - if value != nil { - v := reflect.ValueOf(value) - - if classType == ClassUniversal { - switch tag { - case TagOctetString: - sv, ok := v.Interface().(string) - - if ok { - p.Data.Write([]byte(sv)) - } - case TagEnumerated: - bv, ok := v.Interface().([]byte) - if ok { - p.Data.Write(bv) - } - case TagEmbeddedPDV: - bv, ok := v.Interface().([]byte) - if ok { - p.Data.Write(bv) - } - } - } else if classType == ClassContext { - switch tag { - case TagEnumerated: - bv, ok := v.Interface().([]byte) - if ok { - p.Data.Write(bv) - } - case TagEmbeddedPDV: - bv, ok := v.Interface().([]byte) - if ok { - p.Data.Write(bv) - } - } - } - } - return p -} - -func NewSequence(description string) *Packet { - return Encode(ClassUniversal, TypeConstructed, TagSequence, nil, description) -} - -func NewBoolean(classType Class, tagType Type, tag Tag, value bool, description string) *Packet { - intValue := int64(0) - - if value { - intValue = 1 - } - - p := Encode(classType, tagType, tag, nil, description) - - p.Value = value - p.Data.Write(encodeInteger(intValue)) - - return p -} - -// NewLDAPBoolean returns a RFC 4511-compliant Boolean packet. -func NewLDAPBoolean(classType Class, tagType Type, tag Tag, value bool, description string) *Packet { - intValue := int64(0) - - if value { - intValue = 255 - } - - p := Encode(classType, tagType, tag, nil, description) - - p.Value = value - p.Data.Write(encodeInteger(intValue)) - - return p -} - -func NewInteger(classType Class, tagType Type, tag Tag, value interface{}, description string) *Packet { - p := Encode(classType, tagType, tag, nil, description) - - p.Value = value - switch v := value.(type) { - case int: - p.Data.Write(encodeInteger(int64(v))) - case uint: - p.Data.Write(encodeInteger(int64(v))) - case int64: - p.Data.Write(encodeInteger(v)) - case uint64: - // TODO : check range or add encodeUInt... - p.Data.Write(encodeInteger(int64(v))) - case int32: - p.Data.Write(encodeInteger(int64(v))) - case uint32: - p.Data.Write(encodeInteger(int64(v))) - case int16: - p.Data.Write(encodeInteger(int64(v))) - case uint16: - p.Data.Write(encodeInteger(int64(v))) - case int8: - p.Data.Write(encodeInteger(int64(v))) - case uint8: - p.Data.Write(encodeInteger(int64(v))) - default: - // TODO : add support for big.Int ? - panic(fmt.Sprintf("Invalid type %T, expected {u|}int{64|32|16|8}", v)) - } - - return p -} - -func NewString(classType Class, tagType Type, tag Tag, value, description string) *Packet { - p := Encode(classType, tagType, tag, nil, description) - - p.Value = value - p.Data.Write([]byte(value)) - - return p -} - -func NewGeneralizedTime(classType Class, tagType Type, tag Tag, value time.Time, description string) *Packet { - p := Encode(classType, tagType, tag, nil, description) - var s string - if value.Nanosecond() != 0 { - s = value.Format(`20060102150405.000000000Z`) - } else { - s = value.Format(`20060102150405Z`) - } - p.Value = s - p.Data.Write([]byte(s)) - return p -} - -func NewReal(classType Class, tagType Type, tag Tag, value interface{}, description string) *Packet { - p := Encode(classType, tagType, tag, nil, description) - - switch v := value.(type) { - case float64: - p.Data.Write(encodeFloat(v)) - case float32: - p.Data.Write(encodeFloat(float64(v))) - default: - panic(fmt.Sprintf("Invalid type %T, expected float{64|32}", v)) - } - return p -} diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/content_int.go b/vendor/github.com/go-asn1-ber/asn1-ber/content_int.go deleted file mode 100644 index 20b500f553..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/content_int.go +++ /dev/null @@ -1,25 +0,0 @@ -package ber - -func encodeUnsignedInteger(i uint64) []byte { - n := uint64Length(i) - out := make([]byte, n) - - var j int - for ; n > 0; n-- { - out[j] = byte(i >> uint((n-1)*8)) - j++ - } - - return out -} - -func uint64Length(i uint64) (numBytes int) { - numBytes = 1 - - for i > 255 { - numBytes++ - i >>= 8 - } - - return -} diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/generalizedTime.go b/vendor/github.com/go-asn1-ber/asn1-ber/generalizedTime.go deleted file mode 100644 index 51215f0619..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/generalizedTime.go +++ /dev/null @@ -1,105 +0,0 @@ -package ber - -import ( - "bytes" - "errors" - "fmt" - "strconv" - "time" -) - -// ErrInvalidTimeFormat is returned when the generalizedTime string was not correct. -var ErrInvalidTimeFormat = errors.New("invalid time format") - -var zeroTime = time.Time{} - -// ParseGeneralizedTime parses a string value and if it conforms to -// GeneralizedTime[^0] format, will return a time.Time for that value. -// -// [^0]: https://www.itu.int/rec/T-REC-X.690-201508-I/en Section 11.7 -func ParseGeneralizedTime(v []byte) (time.Time, error) { - var format string - var fract time.Duration - - str := []byte(DecodeString(v)) - tzIndex := bytes.IndexAny(str, "Z+-") - if tzIndex < 0 { - return zeroTime, ErrInvalidTimeFormat - } - - dot := bytes.IndexAny(str, ".,") - switch dot { - case -1: - switch tzIndex { - case 10: - format = `2006010215Z` - case 12: - format = `200601021504Z` - case 14: - format = `20060102150405Z` - default: - return zeroTime, ErrInvalidTimeFormat - } - - case 10, 12: - if tzIndex < dot { - return zeroTime, ErrInvalidTimeFormat - } - // a "," is also allowed, but would not be parsed by time.Parse(): - str[dot] = '.' - - // If is omitted, then represents a fraction of an - // hour; otherwise, if and are omitted, then - // represents a fraction of a minute; otherwise, - // represents a fraction of a second. - - // parse as float from dot to timezone - f, err := strconv.ParseFloat(string(str[dot:tzIndex]), 64) - if err != nil { - return zeroTime, fmt.Errorf("failed to parse float: %s", err) - } - // ...and strip that part - str = append(str[:dot], str[tzIndex:]...) - tzIndex = dot - - if dot == 10 { - fract = time.Duration(int64(f * float64(time.Hour))) - format = `2006010215Z` - } else { - fract = time.Duration(int64(f * float64(time.Minute))) - format = `200601021504Z` - } - - case 14: - if tzIndex < dot { - return zeroTime, ErrInvalidTimeFormat - } - str[dot] = '.' - // no need for fractional seconds, time.Parse() handles that - format = `20060102150405Z` - - default: - return zeroTime, ErrInvalidTimeFormat - } - - l := len(str) - switch l - tzIndex { - case 1: - if str[l-1] != 'Z' { - return zeroTime, ErrInvalidTimeFormat - } - case 3: - format += `0700` - str = append(str, []byte("00")...) - case 5: - format += `0700` - default: - return zeroTime, ErrInvalidTimeFormat - } - - t, err := time.Parse(format, string(str)) - if err != nil { - return zeroTime, fmt.Errorf("%s: %s", ErrInvalidTimeFormat, err) - } - return t.Add(fract), nil -} diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/header.go b/vendor/github.com/go-asn1-ber/asn1-ber/header.go deleted file mode 100644 index 7dfa6b9a7d..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/header.go +++ /dev/null @@ -1,38 +0,0 @@ -package ber - -import ( - "errors" - "fmt" - "io" -) - -func readHeader(reader io.Reader) (identifier Identifier, length int, read int, err error) { - var ( - c, l int - i Identifier - ) - - if i, c, err = readIdentifier(reader); err != nil { - return Identifier{}, 0, read, err - } - identifier = i - read += c - - if l, c, err = readLength(reader); err != nil { - return Identifier{}, 0, read, err - } - length = l - read += c - - // Validate length type with identifier (x.600, 8.1.3.2.a) - if length == LengthIndefinite && identifier.TagType == TypePrimitive { - return Identifier{}, 0, read, errors.New("indefinite length used with primitive type") - } - - if length < LengthIndefinite { - err = fmt.Errorf("length cannot be less than %d", LengthIndefinite) - return - } - - return identifier, length, read, nil -} diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/identifier.go b/vendor/github.com/go-asn1-ber/asn1-ber/identifier.go deleted file mode 100644 index e8c435749a..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/identifier.go +++ /dev/null @@ -1,112 +0,0 @@ -package ber - -import ( - "errors" - "fmt" - "io" -) - -func readIdentifier(reader io.Reader) (Identifier, int, error) { - identifier := Identifier{} - read := 0 - - // identifier byte - b, err := readByte(reader) - if err != nil { - if Debug { - fmt.Printf("error reading identifier byte: %v\n", err) - } - return Identifier{}, read, err - } - read++ - - identifier.ClassType = Class(b) & ClassBitmask - identifier.TagType = Type(b) & TypeBitmask - - if tag := Tag(b) & TagBitmask; tag != HighTag { - // short-form tag - identifier.Tag = tag - return identifier, read, nil - } - - // high-tag-number tag - tagBytes := 0 - for { - b, err := readByte(reader) - if err != nil { - if Debug { - fmt.Printf("error reading high-tag-number tag byte %d: %v\n", tagBytes, err) - } - return Identifier{}, read, err - } - tagBytes++ - read++ - - // Lowest 7 bits get appended to the tag value (x.690, 8.1.2.4.2.b) - identifier.Tag <<= 7 - identifier.Tag |= Tag(b) & HighTagValueBitmask - - // First byte may not be all zeros (x.690, 8.1.2.4.2.c) - if tagBytes == 1 && identifier.Tag == 0 { - return Identifier{}, read, errors.New("invalid first high-tag-number tag byte") - } - // Overflow of int64 - // TODO: support big int tags? - if tagBytes > 9 { - return Identifier{}, read, errors.New("high-tag-number tag overflow") - } - - // Top bit of 0 means this is the last byte in the high-tag-number tag (x.690, 8.1.2.4.2.a) - if Tag(b)&HighTagContinueBitmask == 0 { - break - } - } - - return identifier, read, nil -} - -func encodeIdentifier(identifier Identifier) []byte { - b := []byte{0x0} - b[0] |= byte(identifier.ClassType) - b[0] |= byte(identifier.TagType) - - if identifier.Tag < HighTag { - // Short-form - b[0] |= byte(identifier.Tag) - } else { - // high-tag-number - b[0] |= byte(HighTag) - - tag := identifier.Tag - - b = append(b, encodeHighTag(tag)...) - } - return b -} - -func encodeHighTag(tag Tag) []byte { - // set cap=4 to hopefully avoid additional allocations - b := make([]byte, 0, 4) - for tag != 0 { - // t := last 7 bits of tag (HighTagValueBitmask = 0x7F) - t := tag & HighTagValueBitmask - - // right shift tag 7 to remove what was just pulled off - tag >>= 7 - - // if b already has entries this entry needs a continuation bit (0x80) - if len(b) != 0 { - t |= HighTagContinueBitmask - } - - b = append(b, byte(t)) - } - // reverse - // since bits were pulled off 'tag' small to high the byte slice is in reverse order. - // example: tag = 0xFF results in {0x7F, 0x01 + 0x80 (continuation bit)} - // this needs to be reversed into 0x81 0x7F - for i, j := 0, len(b)-1; i < len(b)/2; i++ { - b[i], b[j-i] = b[j-i], b[i] - } - return b -} diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/length.go b/vendor/github.com/go-asn1-ber/asn1-ber/length.go deleted file mode 100644 index 9cc195d0bd..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/length.go +++ /dev/null @@ -1,81 +0,0 @@ -package ber - -import ( - "errors" - "fmt" - "io" -) - -func readLength(reader io.Reader) (length int, read int, err error) { - // length byte - b, err := readByte(reader) - if err != nil { - if Debug { - fmt.Printf("error reading length byte: %v\n", err) - } - return 0, 0, err - } - read++ - - switch { - case b == 0xFF: - // Invalid 0xFF (x.600, 8.1.3.5.c) - return 0, read, errors.New("invalid length byte 0xff") - - case b == LengthLongFormBitmask: - // Indefinite form, we have to decode packets until we encounter an EOC packet (x.600, 8.1.3.6) - length = LengthIndefinite - - case b&LengthLongFormBitmask == 0: - // Short definite form, extract the length from the bottom 7 bits (x.600, 8.1.3.4) - length = int(b) & LengthValueBitmask - - case b&LengthLongFormBitmask != 0: - // Long definite form, extract the number of length bytes to follow from the bottom 7 bits (x.600, 8.1.3.5.b) - lengthBytes := int(b) & LengthValueBitmask - // Protect against overflow - // TODO: support big int length? - if lengthBytes > 8 { - return 0, read, errors.New("long-form length overflow") - } - - // Accumulate into a 64-bit variable - var length64 int64 - for i := 0; i < lengthBytes; i++ { - b, err = readByte(reader) - if err != nil { - if Debug { - fmt.Printf("error reading long-form length byte %d: %v\n", i, err) - } - return 0, read, err - } - read++ - - // x.600, 8.1.3.5 - length64 <<= 8 - length64 |= int64(b) - } - - // Cast to a platform-specific integer - length = int(length64) - // Ensure we didn't overflow - if int64(length) != length64 { - return 0, read, errors.New("long-form length overflow") - } - - default: - return 0, read, errors.New("invalid length byte") - } - - return length, read, nil -} - -func encodeLength(length int) []byte { - lengthBytes := encodeUnsignedInteger(uint64(length)) - if length > 127 || len(lengthBytes) > 1 { - longFormBytes := []byte{LengthLongFormBitmask | byte(len(lengthBytes))} - longFormBytes = append(longFormBytes, lengthBytes...) - lengthBytes = longFormBytes - } - return lengthBytes -} diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/real.go b/vendor/github.com/go-asn1-ber/asn1-ber/real.go deleted file mode 100644 index 610a003a73..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/real.go +++ /dev/null @@ -1,157 +0,0 @@ -package ber - -import ( - "bytes" - "errors" - "fmt" - "math" - "strconv" - "strings" -) - -func encodeFloat(v float64) []byte { - switch { - case math.IsInf(v, 1): - return []byte{0x40} - case math.IsInf(v, -1): - return []byte{0x41} - case math.IsNaN(v): - return []byte{0x42} - case v == 0.0: - if math.Signbit(v) { - return []byte{0x43} - } - return []byte{} - default: - // we take the easy part ;-) - value := []byte(strconv.FormatFloat(v, 'G', -1, 64)) - var ret []byte - if bytes.Contains(value, []byte{'E'}) { - ret = []byte{0x03} - } else { - ret = []byte{0x02} - } - ret = append(ret, value...) - return ret - } -} - -func ParseReal(v []byte) (val float64, err error) { - if len(v) == 0 { - return 0.0, nil - } - switch { - case v[0]&0x80 == 0x80: - val, err = parseBinaryFloat(v) - case v[0]&0xC0 == 0x40: - val, err = parseSpecialFloat(v) - case v[0]&0xC0 == 0x0: - val, err = parseDecimalFloat(v) - default: - return 0.0, fmt.Errorf("invalid info block") - } - if err != nil { - return 0.0, err - } - - if val == 0.0 && !math.Signbit(val) { - return 0.0, errors.New("REAL value +0 must be encoded with zero-length value block") - } - return val, nil -} - -func parseBinaryFloat(v []byte) (float64, error) { - var info byte - var buf []byte - - info, v = v[0], v[1:] - - var base int - switch info & 0x30 { - case 0x00: - base = 2 - case 0x10: - base = 8 - case 0x20: - base = 16 - case 0x30: - return 0.0, errors.New("bits 6 and 5 of information octet for REAL are equal to 11") - } - - scale := uint((info & 0x0c) >> 2) - - var expLen int - switch info & 0x03 { - case 0x00: - expLen = 1 - case 0x01: - expLen = 2 - case 0x02: - expLen = 3 - case 0x03: - expLen = int(v[0]) - if expLen > 8 { - return 0.0, errors.New("too big value of exponent") - } - v = v[1:] - } - buf, v = v[:expLen], v[expLen:] - exponent, err := ParseInt64(buf) - if err != nil { - return 0.0, err - } - - if len(v) > 8 { - return 0.0, errors.New("too big value of mantissa") - } - - mant, err := ParseInt64(v) - if err != nil { - return 0.0, err - } - mantissa := mant << scale - - if info&0x40 == 0x40 { - mantissa = -mantissa - } - - return float64(mantissa) * math.Pow(float64(base), float64(exponent)), nil -} - -func parseDecimalFloat(v []byte) (val float64, err error) { - switch v[0] & 0x3F { - case 0x01: // NR form 1 - var iVal int64 - iVal, err = strconv.ParseInt(strings.TrimLeft(string(v[1:]), " "), 10, 64) - val = float64(iVal) - case 0x02, 0x03: // NR form 2, 3 - val, err = strconv.ParseFloat(strings.Replace(strings.TrimLeft(string(v[1:]), " "), ",", ".", -1), 64) - default: - err = errors.New("incorrect NR form") - } - if err != nil { - return 0.0, err - } - - if val == 0.0 && math.Signbit(val) { - return 0.0, errors.New("REAL value -0 must be encoded as a special value") - } - return val, nil -} - -func parseSpecialFloat(v []byte) (float64, error) { - if len(v) != 1 { - return 0.0, errors.New(`encoding of "special value" must not contain exponent and mantissa`) - } - switch v[0] { - case 0x40: - return math.Inf(1), nil - case 0x41: - return math.Inf(-1), nil - case 0x42: - return math.NaN(), nil - case 0x43: - return math.Copysign(0, -1), nil - } - return 0.0, errors.New(`encoding of "special value" not from ASN.1 standard`) -} diff --git a/vendor/github.com/go-asn1-ber/asn1-ber/util.go b/vendor/github.com/go-asn1-ber/asn1-ber/util.go deleted file mode 100644 index 14dc87d7c9..0000000000 --- a/vendor/github.com/go-asn1-ber/asn1-ber/util.go +++ /dev/null @@ -1,24 +0,0 @@ -package ber - -import "io" - -func readByte(reader io.Reader) (byte, error) { - bytes := make([]byte, 1) - _, err := io.ReadFull(reader, bytes) - if err != nil { - if err == io.EOF { - return 0, io.ErrUnexpectedEOF - } - return 0, err - } - return bytes[0], nil -} - -func isEOCPacket(p *Packet) bool { - return p != nil && - p.Tag == TagEOC && - p.ClassType == ClassUniversal && - p.TagType == TypePrimitive && - len(p.ByteValue) == 0 && - len(p.Children) == 0 -} diff --git a/vendor/github.com/go-ldap/ldap/v3/LICENSE b/vendor/github.com/go-ldap/ldap/v3/LICENSE deleted file mode 100644 index 6c0ed4b387..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2011-2015 Michael Mitton (mmitton@gmail.com) -Portions copyright (c) 2015-2016 go-ldap Authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-ldap/ldap/v3/add.go b/vendor/github.com/go-ldap/ldap/v3/add.go deleted file mode 100644 index baecd787d2..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/add.go +++ /dev/null @@ -1,91 +0,0 @@ -package ldap - -import ( - "log" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// Attribute represents an LDAP attribute -type Attribute struct { - // Type is the name of the LDAP attribute - Type string - // Vals are the LDAP attribute values - Vals []string -} - -func (a *Attribute) encode() *ber.Packet { - seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Attribute") - seq.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, a.Type, "Type")) - set := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSet, nil, "AttributeValue") - for _, value := range a.Vals { - set.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, value, "Vals")) - } - seq.AppendChild(set) - return seq -} - -// AddRequest represents an LDAP AddRequest operation -type AddRequest struct { - // DN identifies the entry being added - DN string - // Attributes list the attributes of the new entry - Attributes []Attribute - // Controls hold optional controls to send with the request - Controls []Control -} - -func (req *AddRequest) appendTo(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationAddRequest, nil, "Add Request") - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.DN, "DN")) - attributes := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Attributes") - for _, attribute := range req.Attributes { - attributes.AppendChild(attribute.encode()) - } - pkt.AppendChild(attributes) - - envelope.AppendChild(pkt) - if len(req.Controls) > 0 { - envelope.AppendChild(encodeControls(req.Controls)) - } - - return nil -} - -// Attribute adds an attribute with the given type and values -func (req *AddRequest) Attribute(attrType string, attrVals []string) { - req.Attributes = append(req.Attributes, Attribute{Type: attrType, Vals: attrVals}) -} - -// NewAddRequest returns an AddRequest for the given DN, with no attributes -func NewAddRequest(dn string, controls []Control) *AddRequest { - return &AddRequest{ - DN: dn, - Controls: controls, - } - -} - -// Add performs the given AddRequest -func (l *Conn) Add(addRequest *AddRequest) error { - msgCtx, err := l.doRequest(addRequest) - if err != nil { - return err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return err - } - - if packet.Children[1].Tag == ApplicationAddResponse { - err := GetLDAPError(packet) - if err != nil { - return err - } - } else { - log.Printf("Unexpected Response: %d", packet.Children[1].Tag) - } - return nil -} diff --git a/vendor/github.com/go-ldap/ldap/v3/bind.go b/vendor/github.com/go-ldap/ldap/v3/bind.go deleted file mode 100644 index 9bc5748283..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/bind.go +++ /dev/null @@ -1,540 +0,0 @@ -package ldap - -import ( - "bytes" - "crypto/md5" - enchex "encoding/hex" - "errors" - "fmt" - "io/ioutil" - "math/rand" - "strings" - - "github.com/Azure/go-ntlmssp" - ber "github.com/go-asn1-ber/asn1-ber" -) - -// SimpleBindRequest represents a username/password bind operation -type SimpleBindRequest struct { - // Username is the name of the Directory object that the client wishes to bind as - Username string - // Password is the credentials to bind with - Password string - // Controls are optional controls to send with the bind request - Controls []Control - // AllowEmptyPassword sets whether the client allows binding with an empty password - // (normally used for unauthenticated bind). - AllowEmptyPassword bool -} - -// SimpleBindResult contains the response from the server -type SimpleBindResult struct { - Controls []Control -} - -// NewSimpleBindRequest returns a bind request -func NewSimpleBindRequest(username string, password string, controls []Control) *SimpleBindRequest { - return &SimpleBindRequest{ - Username: username, - Password: password, - Controls: controls, - AllowEmptyPassword: false, - } -} - -func (req *SimpleBindRequest) appendTo(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request") - pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version")) - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.Username, "User Name")) - pkt.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, req.Password, "Password")) - - envelope.AppendChild(pkt) - if len(req.Controls) > 0 { - envelope.AppendChild(encodeControls(req.Controls)) - } - - return nil -} - -// SimpleBind performs the simple bind operation defined in the given request -func (l *Conn) SimpleBind(simpleBindRequest *SimpleBindRequest) (*SimpleBindResult, error) { - if simpleBindRequest.Password == "" && !simpleBindRequest.AllowEmptyPassword { - return nil, NewError(ErrorEmptyPassword, errors.New("ldap: empty password not allowed by the client")) - } - - msgCtx, err := l.doRequest(simpleBindRequest) - if err != nil { - return nil, err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return nil, err - } - - result := &SimpleBindResult{ - Controls: make([]Control, 0), - } - - if len(packet.Children) == 3 { - for _, child := range packet.Children[2].Children { - decodedChild, decodeErr := DecodeControl(child) - if decodeErr != nil { - return nil, fmt.Errorf("failed to decode child control: %s", decodeErr) - } - result.Controls = append(result.Controls, decodedChild) - } - } - - err = GetLDAPError(packet) - return result, err -} - -// Bind performs a bind with the given username and password. -// -// It does not allow unauthenticated bind (i.e. empty password). Use the UnauthenticatedBind method -// for that. -func (l *Conn) Bind(username, password string) error { - req := &SimpleBindRequest{ - Username: username, - Password: password, - AllowEmptyPassword: false, - } - _, err := l.SimpleBind(req) - return err -} - -// UnauthenticatedBind performs an unauthenticated bind. -// -// A username may be provided for trace (e.g. logging) purpose only, but it is normally not -// authenticated or otherwise validated by the LDAP server. -// -// See https://tools.ietf.org/html/rfc4513#section-5.1.2 . -// See https://tools.ietf.org/html/rfc4513#section-6.3.1 . -func (l *Conn) UnauthenticatedBind(username string) error { - req := &SimpleBindRequest{ - Username: username, - Password: "", - AllowEmptyPassword: true, - } - _, err := l.SimpleBind(req) - return err -} - -// DigestMD5BindRequest represents a digest-md5 bind operation -type DigestMD5BindRequest struct { - Host string - // Username is the name of the Directory object that the client wishes to bind as - Username string - // Password is the credentials to bind with - Password string - // Controls are optional controls to send with the bind request - Controls []Control -} - -func (req *DigestMD5BindRequest) appendTo(envelope *ber.Packet) error { - request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request") - request.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version")) - request.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "User Name")) - - auth := ber.Encode(ber.ClassContext, ber.TypeConstructed, 3, "", "authentication") - auth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "DIGEST-MD5", "SASL Mech")) - request.AppendChild(auth) - envelope.AppendChild(request) - if len(req.Controls) > 0 { - envelope.AppendChild(encodeControls(req.Controls)) - } - return nil -} - -// DigestMD5BindResult contains the response from the server -type DigestMD5BindResult struct { - Controls []Control -} - -// MD5Bind performs a digest-md5 bind with the given host, username and password. -func (l *Conn) MD5Bind(host, username, password string) error { - req := &DigestMD5BindRequest{ - Host: host, - Username: username, - Password: password, - } - _, err := l.DigestMD5Bind(req) - return err -} - -// DigestMD5Bind performs the digest-md5 bind operation defined in the given request -func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*DigestMD5BindResult, error) { - if digestMD5BindRequest.Password == "" { - return nil, NewError(ErrorEmptyPassword, errors.New("ldap: empty password not allowed by the client")) - } - - msgCtx, err := l.doRequest(digestMD5BindRequest) - if err != nil { - return nil, err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return nil, err - } - l.Debug.Printf("%d: got response %p", msgCtx.id, packet) - if l.Debug { - if err = addLDAPDescriptions(packet); err != nil { - return nil, err - } - ber.PrintPacket(packet) - } - - result := &DigestMD5BindResult{ - Controls: make([]Control, 0), - } - var params map[string]string - if len(packet.Children) == 2 { - if len(packet.Children[1].Children) == 4 { - child := packet.Children[1].Children[0] - if child.Tag != ber.TagEnumerated { - return result, GetLDAPError(packet) - } - if child.Value.(int64) != 14 { - return result, GetLDAPError(packet) - } - child = packet.Children[1].Children[3] - if child.Tag != ber.TagObjectDescriptor { - return result, GetLDAPError(packet) - } - if child.Data == nil { - return result, GetLDAPError(packet) - } - data, _ := ioutil.ReadAll(child.Data) - params, err = parseParams(string(data)) - if err != nil { - return result, fmt.Errorf("parsing digest-challenge: %s", err) - } - } - } - - if params != nil { - resp := computeResponse( - params, - "ldap/"+strings.ToLower(digestMD5BindRequest.Host), - digestMD5BindRequest.Username, - digestMD5BindRequest.Password, - ) - packet = ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") - packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) - - request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request") - request.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version")) - request.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "User Name")) - - auth := ber.Encode(ber.ClassContext, ber.TypeConstructed, 3, "", "authentication") - auth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "DIGEST-MD5", "SASL Mech")) - auth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, resp, "Credentials")) - request.AppendChild(auth) - packet.AppendChild(request) - msgCtx, err = l.sendMessage(packet) - if err != nil { - return nil, fmt.Errorf("send message: %s", err) - } - defer l.finishMessage(msgCtx) - packetResponse, ok := <-msgCtx.responses - if !ok { - return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed")) - } - packet, err = packetResponse.ReadPacket() - l.Debug.Printf("%d: got response %p", msgCtx.id, packet) - if err != nil { - return nil, fmt.Errorf("read packet: %s", err) - } - } - - err = GetLDAPError(packet) - return result, err -} - -func parseParams(str string) (map[string]string, error) { - m := make(map[string]string) - var key, value string - var state int - for i := 0; i <= len(str); i++ { - switch state { - case 0: //reading key - if i == len(str) { - return nil, fmt.Errorf("syntax error on %d", i) - } - if str[i] != '=' { - key += string(str[i]) - continue - } - state = 1 - case 1: //reading value - if i == len(str) { - m[key] = value - break - } - switch str[i] { - case ',': - m[key] = value - state = 0 - key = "" - value = "" - case '"': - if value != "" { - return nil, fmt.Errorf("syntax error on %d", i) - } - state = 2 - default: - value += string(str[i]) - } - case 2: //inside quotes - if i == len(str) { - return nil, fmt.Errorf("syntax error on %d", i) - } - if str[i] != '"' { - value += string(str[i]) - } else { - state = 1 - } - } - } - return m, nil -} - -func computeResponse(params map[string]string, uri, username, password string) string { - nc := "00000001" - qop := "auth" - cnonce := enchex.EncodeToString(randomBytes(16)) - x := username + ":" + params["realm"] + ":" + password - y := md5Hash([]byte(x)) - - a1 := bytes.NewBuffer(y) - a1.WriteString(":" + params["nonce"] + ":" + cnonce) - if len(params["authzid"]) > 0 { - a1.WriteString(":" + params["authzid"]) - } - a2 := bytes.NewBuffer([]byte("AUTHENTICATE")) - a2.WriteString(":" + uri) - ha1 := enchex.EncodeToString(md5Hash(a1.Bytes())) - ha2 := enchex.EncodeToString(md5Hash(a2.Bytes())) - - kd := ha1 - kd += ":" + params["nonce"] - kd += ":" + nc - kd += ":" + cnonce - kd += ":" + qop - kd += ":" + ha2 - resp := enchex.EncodeToString(md5Hash([]byte(kd))) - return fmt.Sprintf( - `username="%s",realm="%s",nonce="%s",cnonce="%s",nc=00000001,qop=%s,digest-uri="%s",response=%s`, - username, - params["realm"], - params["nonce"], - cnonce, - qop, - uri, - resp, - ) -} - -func md5Hash(b []byte) []byte { - hasher := md5.New() - hasher.Write(b) - return hasher.Sum(nil) -} - -func randomBytes(len int) []byte { - b := make([]byte, len) - for i := 0; i < len; i++ { - b[i] = byte(rand.Intn(256)) - } - return b -} - -var externalBindRequest = requestFunc(func(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request") - pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version")) - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "User Name")) - - saslAuth := ber.Encode(ber.ClassContext, ber.TypeConstructed, 3, "", "authentication") - saslAuth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "EXTERNAL", "SASL Mech")) - saslAuth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "SASL Cred")) - - pkt.AppendChild(saslAuth) - - envelope.AppendChild(pkt) - - return nil -}) - -// ExternalBind performs SASL/EXTERNAL authentication. -// -// Use ldap.DialURL("ldapi://") to connect to the Unix socket before ExternalBind. -// -// See https://tools.ietf.org/html/rfc4422#appendix-A -func (l *Conn) ExternalBind() error { - msgCtx, err := l.doRequest(externalBindRequest) - if err != nil { - return err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return err - } - - return GetLDAPError(packet) -} - -// NTLMBind performs an NTLMSSP bind leveraging https://github.com/Azure/go-ntlmssp - -// NTLMBindRequest represents an NTLMSSP bind operation -type NTLMBindRequest struct { - // Domain is the AD Domain to authenticate too. If not specified, it will be grabbed from the NTLMSSP Challenge - Domain string - // Username is the name of the Directory object that the client wishes to bind as - Username string - // Password is the credentials to bind with - Password string - // Hash is the hex NTLM hash to bind with. Password or hash must be provided - Hash string - // Controls are optional controls to send with the bind request - Controls []Control -} - -func (req *NTLMBindRequest) appendTo(envelope *ber.Packet) error { - request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request") - request.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version")) - request.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "User Name")) - - // generate an NTLMSSP Negotiation message for the specified domain (it can be blank) - negMessage, err := ntlmssp.NewNegotiateMessage(req.Domain, "") - if err != nil { - return fmt.Errorf("err creating negmessage: %s", err) - } - - // append the generated NTLMSSP message as a TagEnumerated BER value - auth := ber.Encode(ber.ClassContext, ber.TypePrimitive, ber.TagEnumerated, negMessage, "authentication") - request.AppendChild(auth) - envelope.AppendChild(request) - if len(req.Controls) > 0 { - envelope.AppendChild(encodeControls(req.Controls)) - } - return nil -} - -// NTLMBindResult contains the response from the server -type NTLMBindResult struct { - Controls []Control -} - -// NTLMBind performs an NTLMSSP Bind with the given domain, username and password -func (l *Conn) NTLMBind(domain, username, password string) error { - req := &NTLMBindRequest{ - Domain: domain, - Username: username, - Password: password, - } - _, err := l.NTLMChallengeBind(req) - return err -} - -// NTLMBindWithHash performs an NTLM Bind with an NTLM hash instead of plaintext password (pass-the-hash) -func (l *Conn) NTLMBindWithHash(domain, username, hash string) error { - req := &NTLMBindRequest{ - Domain: domain, - Username: username, - Hash: hash, - } - _, err := l.NTLMChallengeBind(req) - return err -} - -// NTLMChallengeBind performs the NTLMSSP bind operation defined in the given request -func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindResult, error) { - if ntlmBindRequest.Password == "" && ntlmBindRequest.Hash == "" { - return nil, NewError(ErrorEmptyPassword, errors.New("ldap: empty password not allowed by the client")) - } - - msgCtx, err := l.doRequest(ntlmBindRequest) - if err != nil { - return nil, err - } - defer l.finishMessage(msgCtx) - packet, err := l.readPacket(msgCtx) - if err != nil { - return nil, err - } - l.Debug.Printf("%d: got response %p", msgCtx.id, packet) - if l.Debug { - if err = addLDAPDescriptions(packet); err != nil { - return nil, err - } - ber.PrintPacket(packet) - } - result := &NTLMBindResult{ - Controls: make([]Control, 0), - } - var ntlmsspChallenge []byte - - // now find the NTLM Response Message - if len(packet.Children) == 2 { - if len(packet.Children[1].Children) == 3 { - child := packet.Children[1].Children[1] - ntlmsspChallenge = child.ByteValue - // Check to make sure we got the right message. It will always start with NTLMSSP - if len(ntlmsspChallenge) < 7 || !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) { - return result, GetLDAPError(packet) - } - l.Debug.Printf("%d: found ntlmssp challenge", msgCtx.id) - } - } - if ntlmsspChallenge != nil { - var err error - var responseMessage []byte - // generate a response message to the challenge with the given Username/Password if password is provided - if ntlmBindRequest.Password != "" { - responseMessage, err = ntlmssp.ProcessChallenge(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Password) - } else if ntlmBindRequest.Hash != "" { - responseMessage, err = ntlmssp.ProcessChallengeWithHash(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Hash) - } else { - err = fmt.Errorf("need a password or hash to generate reply") - } - if err != nil { - return result, fmt.Errorf("parsing ntlm-challenge: %s", err) - } - packet = ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") - packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) - - request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request") - request.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version")) - request.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "User Name")) - - // append the challenge response message as a TagEmbeddedPDV BER value - auth := ber.Encode(ber.ClassContext, ber.TypePrimitive, ber.TagEmbeddedPDV, responseMessage, "authentication") - - request.AppendChild(auth) - packet.AppendChild(request) - msgCtx, err = l.sendMessage(packet) - if err != nil { - return nil, fmt.Errorf("send message: %s", err) - } - defer l.finishMessage(msgCtx) - packetResponse, ok := <-msgCtx.responses - if !ok { - return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed")) - } - packet, err = packetResponse.ReadPacket() - l.Debug.Printf("%d: got response %p", msgCtx.id, packet) - if err != nil { - return nil, fmt.Errorf("read packet: %s", err) - } - - } - - err = GetLDAPError(packet) - return result, err -} diff --git a/vendor/github.com/go-ldap/ldap/v3/client.go b/vendor/github.com/go-ldap/ldap/v3/client.go deleted file mode 100644 index 1fa4ad5aa6..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/client.go +++ /dev/null @@ -1,32 +0,0 @@ -package ldap - -import ( - "crypto/tls" - "time" -) - -// Client knows how to interact with an LDAP server -type Client interface { - Start() - StartTLS(*tls.Config) error - Close() - IsClosing() bool - SetTimeout(time.Duration) - - Bind(username, password string) error - UnauthenticatedBind(username string) error - SimpleBind(*SimpleBindRequest) (*SimpleBindResult, error) - ExternalBind() error - - Add(*AddRequest) error - Del(*DelRequest) error - Modify(*ModifyRequest) error - ModifyDN(*ModifyDNRequest) error - ModifyWithResult(*ModifyRequest) (*ModifyResult, error) - - Compare(dn, attribute, value string) (bool, error) - PasswordModify(*PasswordModifyRequest) (*PasswordModifyResult, error) - - Search(*SearchRequest) (*SearchResult, error) - SearchWithPaging(searchRequest *SearchRequest, pagingSize uint32) (*SearchResult, error) -} diff --git a/vendor/github.com/go-ldap/ldap/v3/compare.go b/vendor/github.com/go-ldap/ldap/v3/compare.go deleted file mode 100644 index cd43e4c53d..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/compare.go +++ /dev/null @@ -1,61 +0,0 @@ -package ldap - -import ( - "fmt" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// CompareRequest represents an LDAP CompareRequest operation. -type CompareRequest struct { - DN string - Attribute string - Value string -} - -func (req *CompareRequest) appendTo(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationCompareRequest, nil, "Compare Request") - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.DN, "DN")) - - ava := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "AttributeValueAssertion") - ava.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.Attribute, "AttributeDesc")) - ava.AppendChild(ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.Value, "AssertionValue")) - - pkt.AppendChild(ava) - - envelope.AppendChild(pkt) - - return nil -} - -// Compare checks to see if the attribute of the dn matches value. Returns true if it does otherwise -// false with any error that occurs if any. -func (l *Conn) Compare(dn, attribute, value string) (bool, error) { - msgCtx, err := l.doRequest(&CompareRequest{ - DN: dn, - Attribute: attribute, - Value: value}) - if err != nil { - return false, err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return false, err - } - - if packet.Children[1].Tag == ApplicationCompareResponse { - err := GetLDAPError(packet) - - switch { - case IsErrorWithCode(err, LDAPResultCompareTrue): - return true, nil - case IsErrorWithCode(err, LDAPResultCompareFalse): - return false, nil - default: - return false, err - } - } - return false, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag) -} diff --git a/vendor/github.com/go-ldap/ldap/v3/conn.go b/vendor/github.com/go-ldap/ldap/v3/conn.go deleted file mode 100644 index ae5e19af88..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/conn.go +++ /dev/null @@ -1,581 +0,0 @@ -package ldap - -import ( - "bufio" - "crypto/tls" - "errors" - "fmt" - "log" - "net" - "net/url" - "sync" - "sync/atomic" - "time" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -const ( - // MessageQuit causes the processMessages loop to exit - MessageQuit = 0 - // MessageRequest sends a request to the server - MessageRequest = 1 - // MessageResponse receives a response from the server - MessageResponse = 2 - // MessageFinish indicates the client considers a particular message ID to be finished - MessageFinish = 3 - // MessageTimeout indicates the client-specified timeout for a particular message ID has been reached - MessageTimeout = 4 -) - -const ( - // DefaultLdapPort default ldap port for pure TCP connection - DefaultLdapPort = "389" - // DefaultLdapsPort default ldap port for SSL connection - DefaultLdapsPort = "636" -) - -// PacketResponse contains the packet or error encountered reading a response -type PacketResponse struct { - // Packet is the packet read from the server - Packet *ber.Packet - // Error is an error encountered while reading - Error error -} - -// ReadPacket returns the packet or an error -func (pr *PacketResponse) ReadPacket() (*ber.Packet, error) { - if (pr == nil) || (pr.Packet == nil && pr.Error == nil) { - return nil, NewError(ErrorNetwork, errors.New("ldap: could not retrieve response")) - } - return pr.Packet, pr.Error -} - -type messageContext struct { - id int64 - // close(done) should only be called from finishMessage() - done chan struct{} - // close(responses) should only be called from processMessages(), and only sent to from sendResponse() - responses chan *PacketResponse -} - -// sendResponse should only be called within the processMessages() loop which -// is also responsible for closing the responses channel. -func (msgCtx *messageContext) sendResponse(packet *PacketResponse) { - select { - case msgCtx.responses <- packet: - // Successfully sent packet to message handler. - case <-msgCtx.done: - // The request handler is done and will not receive more - // packets. - } -} - -type messagePacket struct { - Op int - MessageID int64 - Packet *ber.Packet - Context *messageContext -} - -type sendMessageFlags uint - -const ( - startTLS sendMessageFlags = 1 << iota -) - -// Conn represents an LDAP Connection -type Conn struct { - // requestTimeout is loaded atomically - // so we need to ensure 64-bit alignment on 32-bit platforms. - requestTimeout int64 - conn net.Conn - isTLS bool - closing uint32 - closeErr atomic.Value - isStartingTLS bool - Debug debugging - chanConfirm chan struct{} - messageContexts map[int64]*messageContext - chanMessage chan *messagePacket - chanMessageID chan int64 - wgClose sync.WaitGroup - outstandingRequests uint - messageMutex sync.Mutex -} - -var _ Client = &Conn{} - -// DefaultTimeout is a package-level variable that sets the timeout value -// used for the Dial and DialTLS methods. -// -// WARNING: since this is a package-level variable, setting this value from -// multiple places will probably result in undesired behaviour. -var DefaultTimeout = 60 * time.Second - -// DialOpt configures DialContext. -type DialOpt func(*DialContext) - -// DialWithDialer updates net.Dialer in DialContext. -func DialWithDialer(d *net.Dialer) DialOpt { - return func(dc *DialContext) { - dc.d = d - } -} - -// DialWithTLSConfig updates tls.Config in DialContext. -func DialWithTLSConfig(tc *tls.Config) DialOpt { - return func(dc *DialContext) { - dc.tc = tc - } -} - -// DialWithTLSDialer is a wrapper for DialWithTLSConfig with the option to -// specify a net.Dialer to for example define a timeout or a custom resolver. -func DialWithTLSDialer(tlsConfig *tls.Config, dialer *net.Dialer) DialOpt { - return func(dc *DialContext) { - dc.tc = tlsConfig - dc.d = dialer - } -} - -// DialContext contains necessary parameters to dial the given ldap URL. -type DialContext struct { - d *net.Dialer - tc *tls.Config -} - -func (dc *DialContext) dial(u *url.URL) (net.Conn, error) { - if u.Scheme == "ldapi" { - if u.Path == "" || u.Path == "/" { - u.Path = "/var/run/slapd/ldapi" - } - return dc.d.Dial("unix", u.Path) - } - - host, port, err := net.SplitHostPort(u.Host) - if err != nil { - // we assume that error is due to missing port - host = u.Host - port = "" - } - - switch u.Scheme { - case "ldap": - if port == "" { - port = DefaultLdapPort - } - return dc.d.Dial("tcp", net.JoinHostPort(host, port)) - case "ldaps": - if port == "" { - port = DefaultLdapsPort - } - return tls.DialWithDialer(dc.d, "tcp", net.JoinHostPort(host, port), dc.tc) - } - - return nil, fmt.Errorf("Unknown scheme '%s'", u.Scheme) -} - -// Dial connects to the given address on the given network using net.Dial -// and then returns a new Conn for the connection. -// @deprecated Use DialURL instead. -func Dial(network, addr string) (*Conn, error) { - c, err := net.DialTimeout(network, addr, DefaultTimeout) - if err != nil { - return nil, NewError(ErrorNetwork, err) - } - conn := NewConn(c, false) - conn.Start() - return conn, nil -} - -// DialTLS connects to the given address on the given network using tls.Dial -// and then returns a new Conn for the connection. -// @deprecated Use DialURL instead. -func DialTLS(network, addr string, config *tls.Config) (*Conn, error) { - c, err := tls.DialWithDialer(&net.Dialer{Timeout: DefaultTimeout}, network, addr, config) - if err != nil { - return nil, NewError(ErrorNetwork, err) - } - conn := NewConn(c, true) - conn.Start() - return conn, nil -} - -// DialURL connects to the given ldap URL. -// The following schemas are supported: ldap://, ldaps://, ldapi://. -// On success a new Conn for the connection is returned. -func DialURL(addr string, opts ...DialOpt) (*Conn, error) { - u, err := url.Parse(addr) - if err != nil { - return nil, NewError(ErrorNetwork, err) - } - - var dc DialContext - for _, opt := range opts { - opt(&dc) - } - if dc.d == nil { - dc.d = &net.Dialer{Timeout: DefaultTimeout} - } - - c, err := dc.dial(u) - if err != nil { - return nil, NewError(ErrorNetwork, err) - } - - conn := NewConn(c, u.Scheme == "ldaps") - conn.Start() - return conn, nil -} - -// NewConn returns a new Conn using conn for network I/O. -func NewConn(conn net.Conn, isTLS bool) *Conn { - return &Conn{ - conn: conn, - chanConfirm: make(chan struct{}), - chanMessageID: make(chan int64), - chanMessage: make(chan *messagePacket, 10), - messageContexts: map[int64]*messageContext{}, - requestTimeout: 0, - isTLS: isTLS, - } -} - -// Start initializes goroutines to read responses and process messages -func (l *Conn) Start() { - l.wgClose.Add(1) - go l.reader() - go l.processMessages() -} - -// IsClosing returns whether or not we're currently closing. -func (l *Conn) IsClosing() bool { - return atomic.LoadUint32(&l.closing) == 1 -} - -// setClosing sets the closing value to true -func (l *Conn) setClosing() bool { - return atomic.CompareAndSwapUint32(&l.closing, 0, 1) -} - -// Close closes the connection. -func (l *Conn) Close() { - l.messageMutex.Lock() - defer l.messageMutex.Unlock() - - if l.setClosing() { - l.Debug.Printf("Sending quit message and waiting for confirmation") - l.chanMessage <- &messagePacket{Op: MessageQuit} - <-l.chanConfirm - close(l.chanMessage) - - l.Debug.Printf("Closing network connection") - if err := l.conn.Close(); err != nil { - log.Println(err) - } - - l.wgClose.Done() - } - l.wgClose.Wait() -} - -// SetTimeout sets the time after a request is sent that a MessageTimeout triggers -func (l *Conn) SetTimeout(timeout time.Duration) { - if timeout > 0 { - atomic.StoreInt64(&l.requestTimeout, int64(timeout)) - } -} - -// Returns the next available messageID -func (l *Conn) nextMessageID() int64 { - if messageID, ok := <-l.chanMessageID; ok { - return messageID - } - return 0 -} - -// StartTLS sends the command to start a TLS session and then creates a new TLS Client -func (l *Conn) StartTLS(config *tls.Config) error { - if l.isTLS { - return NewError(ErrorNetwork, errors.New("ldap: already encrypted")) - } - - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") - packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) - request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationExtendedRequest, nil, "Start TLS") - request.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, "1.3.6.1.4.1.1466.20037", "TLS Extended Command")) - packet.AppendChild(request) - l.Debug.PrintPacket(packet) - - msgCtx, err := l.sendMessageWithFlags(packet, startTLS) - if err != nil { - return err - } - defer l.finishMessage(msgCtx) - - l.Debug.Printf("%d: waiting for response", msgCtx.id) - - packetResponse, ok := <-msgCtx.responses - if !ok { - return NewError(ErrorNetwork, errors.New("ldap: response channel closed")) - } - packet, err = packetResponse.ReadPacket() - l.Debug.Printf("%d: got response %p", msgCtx.id, packet) - if err != nil { - return err - } - - if l.Debug { - if err := addLDAPDescriptions(packet); err != nil { - l.Close() - return err - } - l.Debug.PrintPacket(packet) - } - - if err := GetLDAPError(packet); err == nil { - conn := tls.Client(l.conn, config) - - if connErr := conn.Handshake(); connErr != nil { - l.Close() - return NewError(ErrorNetwork, fmt.Errorf("TLS handshake failed (%v)", connErr)) - } - - l.isTLS = true - l.conn = conn - } else { - return err - } - go l.reader() - - return nil -} - -// TLSConnectionState returns the client's TLS connection state. -// The return values are their zero values if StartTLS did -// not succeed. -func (l *Conn) TLSConnectionState() (state tls.ConnectionState, ok bool) { - tc, ok := l.conn.(*tls.Conn) - if !ok { - return - } - return tc.ConnectionState(), true -} - -func (l *Conn) sendMessage(packet *ber.Packet) (*messageContext, error) { - return l.sendMessageWithFlags(packet, 0) -} - -func (l *Conn) sendMessageWithFlags(packet *ber.Packet, flags sendMessageFlags) (*messageContext, error) { - if l.IsClosing() { - return nil, NewError(ErrorNetwork, errors.New("ldap: connection closed")) - } - l.messageMutex.Lock() - l.Debug.Printf("flags&startTLS = %d", flags&startTLS) - if l.isStartingTLS { - l.messageMutex.Unlock() - return nil, NewError(ErrorNetwork, errors.New("ldap: connection is in startls phase")) - } - if flags&startTLS != 0 { - if l.outstandingRequests != 0 { - l.messageMutex.Unlock() - return nil, NewError(ErrorNetwork, errors.New("ldap: cannot StartTLS with outstanding requests")) - } - l.isStartingTLS = true - } - l.outstandingRequests++ - - l.messageMutex.Unlock() - - responses := make(chan *PacketResponse) - messageID := packet.Children[0].Value.(int64) - message := &messagePacket{ - Op: MessageRequest, - MessageID: messageID, - Packet: packet, - Context: &messageContext{ - id: messageID, - done: make(chan struct{}), - responses: responses, - }, - } - if !l.sendProcessMessage(message) { - if l.IsClosing() { - return nil, NewError(ErrorNetwork, errors.New("ldap: connection closed")) - } - return nil, NewError(ErrorNetwork, errors.New("ldap: could not send message for unknown reason")) - } - return message.Context, nil -} - -func (l *Conn) finishMessage(msgCtx *messageContext) { - close(msgCtx.done) - - if l.IsClosing() { - return - } - - l.messageMutex.Lock() - l.outstandingRequests-- - if l.isStartingTLS { - l.isStartingTLS = false - } - l.messageMutex.Unlock() - - message := &messagePacket{ - Op: MessageFinish, - MessageID: msgCtx.id, - } - l.sendProcessMessage(message) -} - -func (l *Conn) sendProcessMessage(message *messagePacket) bool { - l.messageMutex.Lock() - defer l.messageMutex.Unlock() - if l.IsClosing() { - return false - } - l.chanMessage <- message - return true -} - -func (l *Conn) processMessages() { - defer func() { - if err := recover(); err != nil { - log.Printf("ldap: recovered panic in processMessages: %v", err) - } - for messageID, msgCtx := range l.messageContexts { - // If we are closing due to an error, inform anyone who - // is waiting about the error. - if l.IsClosing() && l.closeErr.Load() != nil { - msgCtx.sendResponse(&PacketResponse{Error: l.closeErr.Load().(error)}) - } - l.Debug.Printf("Closing channel for MessageID %d", messageID) - close(msgCtx.responses) - delete(l.messageContexts, messageID) - } - close(l.chanMessageID) - close(l.chanConfirm) - }() - - var messageID int64 = 1 - for { - select { - case l.chanMessageID <- messageID: - messageID++ - case message := <-l.chanMessage: - switch message.Op { - case MessageQuit: - l.Debug.Printf("Shutting down - quit message received") - return - case MessageRequest: - // Add to message list and write to network - l.Debug.Printf("Sending message %d", message.MessageID) - - buf := message.Packet.Bytes() - _, err := l.conn.Write(buf) - if err != nil { - l.Debug.Printf("Error Sending Message: %s", err.Error()) - message.Context.sendResponse(&PacketResponse{Error: fmt.Errorf("unable to send request: %s", err)}) - close(message.Context.responses) - break - } - - // Only add to messageContexts if we were able to - // successfully write the message. - l.messageContexts[message.MessageID] = message.Context - - // Add timeout if defined - requestTimeout := time.Duration(atomic.LoadInt64(&l.requestTimeout)) - if requestTimeout > 0 { - go func() { - defer func() { - if err := recover(); err != nil { - log.Printf("ldap: recovered panic in RequestTimeout: %v", err) - } - }() - time.Sleep(requestTimeout) - timeoutMessage := &messagePacket{ - Op: MessageTimeout, - MessageID: message.MessageID, - } - l.sendProcessMessage(timeoutMessage) - }() - } - case MessageResponse: - l.Debug.Printf("Receiving message %d", message.MessageID) - if msgCtx, ok := l.messageContexts[message.MessageID]; ok { - msgCtx.sendResponse(&PacketResponse{message.Packet, nil}) - } else { - log.Printf("Received unexpected message %d, %v", message.MessageID, l.IsClosing()) - l.Debug.PrintPacket(message.Packet) - } - case MessageTimeout: - // Handle the timeout by closing the channel - // All reads will return immediately - if msgCtx, ok := l.messageContexts[message.MessageID]; ok { - l.Debug.Printf("Receiving message timeout for %d", message.MessageID) - msgCtx.sendResponse(&PacketResponse{message.Packet, NewError(ErrorNetwork, errors.New("ldap: connection timed out"))}) - delete(l.messageContexts, message.MessageID) - close(msgCtx.responses) - } - case MessageFinish: - l.Debug.Printf("Finished message %d", message.MessageID) - if msgCtx, ok := l.messageContexts[message.MessageID]; ok { - delete(l.messageContexts, message.MessageID) - close(msgCtx.responses) - } - } - } - } -} - -func (l *Conn) reader() { - cleanstop := false - defer func() { - if err := recover(); err != nil { - log.Printf("ldap: recovered panic in reader: %v", err) - } - if !cleanstop { - l.Close() - } - }() - - bufConn := bufio.NewReader(l.conn) - for { - if cleanstop { - l.Debug.Printf("reader clean stopping (without closing the connection)") - return - } - packet, err := ber.ReadPacket(bufConn) - if err != nil { - // A read error is expected here if we are closing the connection... - if !l.IsClosing() { - l.closeErr.Store(fmt.Errorf("unable to read LDAP response packet: %s", err)) - l.Debug.Printf("reader error: %s", err) - } - return - } - if err := addLDAPDescriptions(packet); err != nil { - l.Debug.Printf("descriptions error: %s", err) - } - if len(packet.Children) == 0 { - l.Debug.Printf("Received bad ldap packet") - continue - } - l.messageMutex.Lock() - if l.isStartingTLS { - cleanstop = true - } - l.messageMutex.Unlock() - message := &messagePacket{ - Op: MessageResponse, - MessageID: packet.Children[0].Value.(int64), - Packet: packet, - } - if !l.sendProcessMessage(message) { - return - } - } -} diff --git a/vendor/github.com/go-ldap/ldap/v3/control.go b/vendor/github.com/go-ldap/ldap/v3/control.go deleted file mode 100644 index 64fb002ad9..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/control.go +++ /dev/null @@ -1,528 +0,0 @@ -package ldap - -import ( - "fmt" - "strconv" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -const ( - // ControlTypePaging - https://www.ietf.org/rfc/rfc2696.txt - ControlTypePaging = "1.2.840.113556.1.4.319" - // ControlTypeBeheraPasswordPolicy - https://tools.ietf.org/html/draft-behera-ldap-password-policy-10 - ControlTypeBeheraPasswordPolicy = "1.3.6.1.4.1.42.2.27.8.5.1" - // ControlTypeVChuPasswordMustChange - https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00 - ControlTypeVChuPasswordMustChange = "2.16.840.1.113730.3.4.4" - // ControlTypeVChuPasswordWarning - https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00 - ControlTypeVChuPasswordWarning = "2.16.840.1.113730.3.4.5" - // ControlTypeManageDsaIT - https://tools.ietf.org/html/rfc3296 - ControlTypeManageDsaIT = "2.16.840.1.113730.3.4.2" - // ControlTypeWhoAmI - https://tools.ietf.org/html/rfc4532 - ControlTypeWhoAmI = "1.3.6.1.4.1.4203.1.11.3" - - // ControlTypeMicrosoftNotification - https://msdn.microsoft.com/en-us/library/aa366983(v=vs.85).aspx - ControlTypeMicrosoftNotification = "1.2.840.113556.1.4.528" - // ControlTypeMicrosoftShowDeleted - https://msdn.microsoft.com/en-us/library/aa366989(v=vs.85).aspx - ControlTypeMicrosoftShowDeleted = "1.2.840.113556.1.4.417" - // ControlTypeMicrosoftServerLinkTTL - https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/f4f523a8-abc0-4b3a-a471-6b2fef135481?redirectedfrom=MSDN - ControlTypeMicrosoftServerLinkTTL = "1.2.840.113556.1.4.2309" -) - -// ControlTypeMap maps controls to text descriptions -var ControlTypeMap = map[string]string{ - ControlTypePaging: "Paging", - ControlTypeBeheraPasswordPolicy: "Password Policy - Behera Draft", - ControlTypeManageDsaIT: "Manage DSA IT", - ControlTypeMicrosoftNotification: "Change Notification - Microsoft", - ControlTypeMicrosoftShowDeleted: "Show Deleted Objects - Microsoft", - ControlTypeMicrosoftServerLinkTTL: "Return TTL-DNs for link values with associated expiry times - Microsoft", -} - -// Control defines an interface controls provide to encode and describe themselves -type Control interface { - // GetControlType returns the OID - GetControlType() string - // Encode returns the ber packet representation - Encode() *ber.Packet - // String returns a human-readable description - String() string -} - -// ControlString implements the Control interface for simple controls -type ControlString struct { - ControlType string - Criticality bool - ControlValue string -} - -// GetControlType returns the OID -func (c *ControlString) GetControlType() string { - return c.ControlType -} - -// Encode returns the ber packet representation -func (c *ControlString) Encode() *ber.Packet { - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control") - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, c.ControlType, "Control Type ("+ControlTypeMap[c.ControlType]+")")) - if c.Criticality { - packet.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, c.Criticality, "Criticality")) - } - if c.ControlValue != "" { - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, string(c.ControlValue), "Control Value")) - } - return packet -} - -// String returns a human-readable description -func (c *ControlString) String() string { - return fmt.Sprintf("Control Type: %s (%q) Criticality: %t Control Value: %s", ControlTypeMap[c.ControlType], c.ControlType, c.Criticality, c.ControlValue) -} - -// ControlPaging implements the paging control described in https://www.ietf.org/rfc/rfc2696.txt -type ControlPaging struct { - // PagingSize indicates the page size - PagingSize uint32 - // Cookie is an opaque value returned by the server to track a paging cursor - Cookie []byte -} - -// GetControlType returns the OID -func (c *ControlPaging) GetControlType() string { - return ControlTypePaging -} - -// Encode returns the ber packet representation -func (c *ControlPaging) Encode() *ber.Packet { - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control") - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypePaging, "Control Type ("+ControlTypeMap[ControlTypePaging]+")")) - - p2 := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, nil, "Control Value (Paging)") - seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Search Control Value") - seq.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, int64(c.PagingSize), "Paging Size")) - cookie := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, nil, "Cookie") - cookie.Value = c.Cookie - cookie.Data.Write(c.Cookie) - seq.AppendChild(cookie) - p2.AppendChild(seq) - - packet.AppendChild(p2) - return packet -} - -// String returns a human-readable description -func (c *ControlPaging) String() string { - return fmt.Sprintf( - "Control Type: %s (%q) Criticality: %t PagingSize: %d Cookie: %q", - ControlTypeMap[ControlTypePaging], - ControlTypePaging, - false, - c.PagingSize, - c.Cookie) -} - -// SetCookie stores the given cookie in the paging control -func (c *ControlPaging) SetCookie(cookie []byte) { - c.Cookie = cookie -} - -// ControlBeheraPasswordPolicy implements the control described in https://tools.ietf.org/html/draft-behera-ldap-password-policy-10 -type ControlBeheraPasswordPolicy struct { - // Expire contains the number of seconds before a password will expire - Expire int64 - // Grace indicates the remaining number of times a user will be allowed to authenticate with an expired password - Grace int64 - // Error indicates the error code - Error int8 - // ErrorString is a human readable error - ErrorString string -} - -// GetControlType returns the OID -func (c *ControlBeheraPasswordPolicy) GetControlType() string { - return ControlTypeBeheraPasswordPolicy -} - -// Encode returns the ber packet representation -func (c *ControlBeheraPasswordPolicy) Encode() *ber.Packet { - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control") - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeBeheraPasswordPolicy, "Control Type ("+ControlTypeMap[ControlTypeBeheraPasswordPolicy]+")")) - - return packet -} - -// String returns a human-readable description -func (c *ControlBeheraPasswordPolicy) String() string { - return fmt.Sprintf( - "Control Type: %s (%q) Criticality: %t Expire: %d Grace: %d Error: %d, ErrorString: %s", - ControlTypeMap[ControlTypeBeheraPasswordPolicy], - ControlTypeBeheraPasswordPolicy, - false, - c.Expire, - c.Grace, - c.Error, - c.ErrorString) -} - -// ControlVChuPasswordMustChange implements the control described in https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00 -type ControlVChuPasswordMustChange struct { - // MustChange indicates if the password is required to be changed - MustChange bool -} - -// GetControlType returns the OID -func (c *ControlVChuPasswordMustChange) GetControlType() string { - return ControlTypeVChuPasswordMustChange -} - -// Encode returns the ber packet representation -func (c *ControlVChuPasswordMustChange) Encode() *ber.Packet { - return nil -} - -// String returns a human-readable description -func (c *ControlVChuPasswordMustChange) String() string { - return fmt.Sprintf( - "Control Type: %s (%q) Criticality: %t MustChange: %v", - ControlTypeMap[ControlTypeVChuPasswordMustChange], - ControlTypeVChuPasswordMustChange, - false, - c.MustChange) -} - -// ControlVChuPasswordWarning implements the control described in https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00 -type ControlVChuPasswordWarning struct { - // Expire indicates the time in seconds until the password expires - Expire int64 -} - -// GetControlType returns the OID -func (c *ControlVChuPasswordWarning) GetControlType() string { - return ControlTypeVChuPasswordWarning -} - -// Encode returns the ber packet representation -func (c *ControlVChuPasswordWarning) Encode() *ber.Packet { - return nil -} - -// String returns a human-readable description -func (c *ControlVChuPasswordWarning) String() string { - return fmt.Sprintf( - "Control Type: %s (%q) Criticality: %t Expire: %b", - ControlTypeMap[ControlTypeVChuPasswordWarning], - ControlTypeVChuPasswordWarning, - false, - c.Expire) -} - -// ControlManageDsaIT implements the control described in https://tools.ietf.org/html/rfc3296 -type ControlManageDsaIT struct { - // Criticality indicates if this control is required - Criticality bool -} - -// GetControlType returns the OID -func (c *ControlManageDsaIT) GetControlType() string { - return ControlTypeManageDsaIT -} - -// Encode returns the ber packet representation -func (c *ControlManageDsaIT) Encode() *ber.Packet { - //FIXME - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control") - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeManageDsaIT, "Control Type ("+ControlTypeMap[ControlTypeManageDsaIT]+")")) - if c.Criticality { - packet.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, c.Criticality, "Criticality")) - } - return packet -} - -// String returns a human-readable description -func (c *ControlManageDsaIT) String() string { - return fmt.Sprintf( - "Control Type: %s (%q) Criticality: %t", - ControlTypeMap[ControlTypeManageDsaIT], - ControlTypeManageDsaIT, - c.Criticality) -} - -// NewControlManageDsaIT returns a ControlManageDsaIT control -func NewControlManageDsaIT(Criticality bool) *ControlManageDsaIT { - return &ControlManageDsaIT{Criticality: Criticality} -} - -// ControlMicrosoftNotification implements the control described in https://msdn.microsoft.com/en-us/library/aa366983(v=vs.85).aspx -type ControlMicrosoftNotification struct{} - -// GetControlType returns the OID -func (c *ControlMicrosoftNotification) GetControlType() string { - return ControlTypeMicrosoftNotification -} - -// Encode returns the ber packet representation -func (c *ControlMicrosoftNotification) Encode() *ber.Packet { - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control") - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeMicrosoftNotification, "Control Type ("+ControlTypeMap[ControlTypeMicrosoftNotification]+")")) - - return packet -} - -// String returns a human-readable description -func (c *ControlMicrosoftNotification) String() string { - return fmt.Sprintf( - "Control Type: %s (%q)", - ControlTypeMap[ControlTypeMicrosoftNotification], - ControlTypeMicrosoftNotification) -} - -// NewControlMicrosoftNotification returns a ControlMicrosoftNotification control -func NewControlMicrosoftNotification() *ControlMicrosoftNotification { - return &ControlMicrosoftNotification{} -} - -// ControlMicrosoftShowDeleted implements the control described in https://msdn.microsoft.com/en-us/library/aa366989(v=vs.85).aspx -type ControlMicrosoftShowDeleted struct{} - -// GetControlType returns the OID -func (c *ControlMicrosoftShowDeleted) GetControlType() string { - return ControlTypeMicrosoftShowDeleted -} - -// Encode returns the ber packet representation -func (c *ControlMicrosoftShowDeleted) Encode() *ber.Packet { - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control") - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeMicrosoftShowDeleted, "Control Type ("+ControlTypeMap[ControlTypeMicrosoftShowDeleted]+")")) - - return packet -} - -// String returns a human-readable description -func (c *ControlMicrosoftShowDeleted) String() string { - return fmt.Sprintf( - "Control Type: %s (%q)", - ControlTypeMap[ControlTypeMicrosoftShowDeleted], - ControlTypeMicrosoftShowDeleted) -} - -// NewControlMicrosoftShowDeleted returns a ControlMicrosoftShowDeleted control -func NewControlMicrosoftShowDeleted() *ControlMicrosoftShowDeleted { - return &ControlMicrosoftShowDeleted{} -} - -// ControlMicrosoftServerLinkTTL implements the control described in https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/f4f523a8-abc0-4b3a-a471-6b2fef135481?redirectedfrom=MSDN -type ControlMicrosoftServerLinkTTL struct{} - -// GetControlType returns the OID -func (c *ControlMicrosoftServerLinkTTL) GetControlType() string { - return ControlTypeMicrosoftServerLinkTTL -} - -// Encode returns the ber packet representation -func (c *ControlMicrosoftServerLinkTTL) Encode() *ber.Packet { - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control") - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeMicrosoftServerLinkTTL, "Control Type ("+ControlTypeMap[ControlTypeMicrosoftServerLinkTTL]+")")) - - return packet -} - -// String returns a human-readable description -func (c *ControlMicrosoftServerLinkTTL) String() string { - return fmt.Sprintf( - "Control Type: %s (%q)", - ControlTypeMap[ControlTypeMicrosoftServerLinkTTL], - ControlTypeMicrosoftServerLinkTTL) -} - -// NewControlMicrosoftServerLinkTTL returns a ControlMicrosoftServerLinkTTL control -func NewControlMicrosoftServerLinkTTL() *ControlMicrosoftServerLinkTTL { - return &ControlMicrosoftServerLinkTTL{} -} - -// FindControl returns the first control of the given type in the list, or nil -func FindControl(controls []Control, controlType string) Control { - for _, c := range controls { - if c.GetControlType() == controlType { - return c - } - } - return nil -} - -// DecodeControl returns a control read from the given packet, or nil if no recognized control can be made -func DecodeControl(packet *ber.Packet) (Control, error) { - var ( - ControlType = "" - Criticality = false - value *ber.Packet - ) - - switch len(packet.Children) { - case 0: - // at least one child is required for control type - return nil, fmt.Errorf("at least one child is required for control type") - - case 1: - // just type, no criticality or value - packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")" - ControlType = packet.Children[0].Value.(string) - - case 2: - packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")" - ControlType = packet.Children[0].Value.(string) - - // Children[1] could be criticality or value (both are optional) - // duck-type on whether this is a boolean - if _, ok := packet.Children[1].Value.(bool); ok { - packet.Children[1].Description = "Criticality" - Criticality = packet.Children[1].Value.(bool) - } else { - packet.Children[1].Description = "Control Value" - value = packet.Children[1] - } - - case 3: - packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")" - ControlType = packet.Children[0].Value.(string) - - packet.Children[1].Description = "Criticality" - Criticality = packet.Children[1].Value.(bool) - - packet.Children[2].Description = "Control Value" - value = packet.Children[2] - - default: - // more than 3 children is invalid - return nil, fmt.Errorf("more than 3 children is invalid for controls") - } - - switch ControlType { - case ControlTypeManageDsaIT: - return NewControlManageDsaIT(Criticality), nil - case ControlTypePaging: - value.Description += " (Paging)" - c := new(ControlPaging) - if value.Value != nil { - valueChildren, err := ber.DecodePacketErr(value.Data.Bytes()) - if err != nil { - return nil, fmt.Errorf("failed to decode data bytes: %s", err) - } - value.Data.Truncate(0) - value.Value = nil - value.AppendChild(valueChildren) - } - value = value.Children[0] - value.Description = "Search Control Value" - value.Children[0].Description = "Paging Size" - value.Children[1].Description = "Cookie" - c.PagingSize = uint32(value.Children[0].Value.(int64)) - c.Cookie = value.Children[1].Data.Bytes() - value.Children[1].Value = c.Cookie - return c, nil - case ControlTypeBeheraPasswordPolicy: - value.Description += " (Password Policy - Behera)" - c := NewControlBeheraPasswordPolicy() - if value.Value != nil { - valueChildren, err := ber.DecodePacketErr(value.Data.Bytes()) - if err != nil { - return nil, fmt.Errorf("failed to decode data bytes: %s", err) - } - value.Data.Truncate(0) - value.Value = nil - value.AppendChild(valueChildren) - } - - sequence := value.Children[0] - - for _, child := range sequence.Children { - if child.Tag == 0 { - //Warning - warningPacket := child.Children[0] - val, err := ber.ParseInt64(warningPacket.Data.Bytes()) - if err != nil { - return nil, fmt.Errorf("failed to decode data bytes: %s", err) - } - if warningPacket.Tag == 0 { - //timeBeforeExpiration - c.Expire = val - warningPacket.Value = c.Expire - } else if warningPacket.Tag == 1 { - //graceAuthNsRemaining - c.Grace = val - warningPacket.Value = c.Grace - } - } else if child.Tag == 1 { - // Error - bs := child.Data.Bytes() - if len(bs) != 1 || bs[0] > 8 { - return nil, fmt.Errorf("failed to decode data bytes: %s", "invalid PasswordPolicyResponse enum value") - } - val := int8(bs[0]) - c.Error = val - child.Value = c.Error - c.ErrorString = BeheraPasswordPolicyErrorMap[c.Error] - } - } - return c, nil - case ControlTypeVChuPasswordMustChange: - c := &ControlVChuPasswordMustChange{MustChange: true} - return c, nil - case ControlTypeVChuPasswordWarning: - c := &ControlVChuPasswordWarning{Expire: -1} - expireStr := ber.DecodeString(value.Data.Bytes()) - - expire, err := strconv.ParseInt(expireStr, 10, 64) - if err != nil { - return nil, fmt.Errorf("failed to parse value as int: %s", err) - } - c.Expire = expire - value.Value = c.Expire - - return c, nil - case ControlTypeMicrosoftNotification: - return NewControlMicrosoftNotification(), nil - case ControlTypeMicrosoftShowDeleted: - return NewControlMicrosoftShowDeleted(), nil - case ControlTypeMicrosoftServerLinkTTL: - return NewControlMicrosoftServerLinkTTL(), nil - default: - c := new(ControlString) - c.ControlType = ControlType - c.Criticality = Criticality - if value != nil { - c.ControlValue = value.Value.(string) - } - return c, nil - } -} - -// NewControlString returns a generic control -func NewControlString(controlType string, criticality bool, controlValue string) *ControlString { - return &ControlString{ - ControlType: controlType, - Criticality: criticality, - ControlValue: controlValue, - } -} - -// NewControlPaging returns a paging control -func NewControlPaging(pagingSize uint32) *ControlPaging { - return &ControlPaging{PagingSize: pagingSize} -} - -// NewControlBeheraPasswordPolicy returns a ControlBeheraPasswordPolicy -func NewControlBeheraPasswordPolicy() *ControlBeheraPasswordPolicy { - return &ControlBeheraPasswordPolicy{ - Expire: -1, - Grace: -1, - Error: -1, - } -} - -func encodeControls(controls []Control) *ber.Packet { - packet := ber.Encode(ber.ClassContext, ber.TypeConstructed, 0, nil, "Controls") - for _, control := range controls { - packet.AppendChild(control.Encode()) - } - return packet -} diff --git a/vendor/github.com/go-ldap/ldap/v3/debug.go b/vendor/github.com/go-ldap/ldap/v3/debug.go deleted file mode 100644 index d0a8fc150b..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/debug.go +++ /dev/null @@ -1,30 +0,0 @@ -package ldap - -import ( - "log" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// debugging type -// - has a Printf method to write the debug output -type debugging bool - -// Enable controls debugging mode. -func (debug *debugging) Enable(b bool) { - *debug = debugging(b) -} - -// Printf writes debug output. -func (debug debugging) Printf(format string, args ...interface{}) { - if debug { - log.Printf(format, args...) - } -} - -// PrintPacket dumps a packet. -func (debug debugging) PrintPacket(packet *ber.Packet) { - if debug { - ber.WritePacket(log.Writer(), packet) - } -} diff --git a/vendor/github.com/go-ldap/ldap/v3/del.go b/vendor/github.com/go-ldap/ldap/v3/del.go deleted file mode 100644 index 6e98726775..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/del.go +++ /dev/null @@ -1,59 +0,0 @@ -package ldap - -import ( - "log" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// DelRequest implements an LDAP deletion request -type DelRequest struct { - // DN is the name of the directory entry to delete - DN string - // Controls hold optional controls to send with the request - Controls []Control -} - -func (req *DelRequest) appendTo(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypePrimitive, ApplicationDelRequest, req.DN, "Del Request") - pkt.Data.Write([]byte(req.DN)) - - envelope.AppendChild(pkt) - if len(req.Controls) > 0 { - envelope.AppendChild(encodeControls(req.Controls)) - } - - return nil -} - -// NewDelRequest creates a delete request for the given DN and controls -func NewDelRequest(DN string, Controls []Control) *DelRequest { - return &DelRequest{ - DN: DN, - Controls: Controls, - } -} - -// Del executes the given delete request -func (l *Conn) Del(delRequest *DelRequest) error { - msgCtx, err := l.doRequest(delRequest) - if err != nil { - return err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return err - } - - if packet.Children[1].Tag == ApplicationDelResponse { - err := GetLDAPError(packet) - if err != nil { - return err - } - } else { - log.Printf("Unexpected Response: %d", packet.Children[1].Tag) - } - return nil -} diff --git a/vendor/github.com/go-ldap/ldap/v3/dn.go b/vendor/github.com/go-ldap/ldap/v3/dn.go deleted file mode 100644 index 2b4cede977..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/dn.go +++ /dev/null @@ -1,270 +0,0 @@ -package ldap - -import ( - "bytes" - enchex "encoding/hex" - "errors" - "fmt" - "strings" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// AttributeTypeAndValue represents an attributeTypeAndValue from https://tools.ietf.org/html/rfc4514 -type AttributeTypeAndValue struct { - // Type is the attribute type - Type string - // Value is the attribute value - Value string -} - -// RelativeDN represents a relativeDistinguishedName from https://tools.ietf.org/html/rfc4514 -type RelativeDN struct { - Attributes []*AttributeTypeAndValue -} - -// DN represents a distinguishedName from https://tools.ietf.org/html/rfc4514 -type DN struct { - RDNs []*RelativeDN -} - -// ParseDN returns a distinguishedName or an error. -// The function respects https://tools.ietf.org/html/rfc4514 -func ParseDN(str string) (*DN, error) { - dn := new(DN) - dn.RDNs = make([]*RelativeDN, 0) - rdn := new(RelativeDN) - rdn.Attributes = make([]*AttributeTypeAndValue, 0) - buffer := bytes.Buffer{} - attribute := new(AttributeTypeAndValue) - escaping := false - - unescapedTrailingSpaces := 0 - stringFromBuffer := func() string { - s := buffer.String() - s = s[0 : len(s)-unescapedTrailingSpaces] - buffer.Reset() - unescapedTrailingSpaces = 0 - return s - } - - for i := 0; i < len(str); i++ { - char := str[i] - switch { - case escaping: - unescapedTrailingSpaces = 0 - escaping = false - switch char { - case ' ', '"', '#', '+', ',', ';', '<', '=', '>', '\\': - buffer.WriteByte(char) - continue - } - // Not a special character, assume hex encoded octet - if len(str) == i+1 { - return nil, errors.New("got corrupted escaped character") - } - - dst := []byte{0} - n, err := enchex.Decode([]byte(dst), []byte(str[i:i+2])) - if err != nil { - return nil, fmt.Errorf("failed to decode escaped character: %s", err) - } else if n != 1 { - return nil, fmt.Errorf("expected 1 byte when un-escaping, got %d", n) - } - buffer.WriteByte(dst[0]) - i++ - case char == '\\': - unescapedTrailingSpaces = 0 - escaping = true - case char == '=': - attribute.Type = stringFromBuffer() - // Special case: If the first character in the value is # the - // following data is BER encoded so we can just fast forward - // and decode. - if len(str) > i+1 && str[i+1] == '#' { - i += 2 - index := strings.IndexAny(str[i:], ",+") - data := str - if index > 0 { - data = str[i : i+index] - } else { - data = str[i:] - } - rawBER, err := enchex.DecodeString(data) - if err != nil { - return nil, fmt.Errorf("failed to decode BER encoding: %s", err) - } - packet, err := ber.DecodePacketErr(rawBER) - if err != nil { - return nil, fmt.Errorf("failed to decode BER packet: %s", err) - } - buffer.WriteString(packet.Data.String()) - i += len(data) - 1 - } - case char == ',' || char == '+': - // We're done with this RDN or value, push it - if len(attribute.Type) == 0 { - return nil, errors.New("incomplete type, value pair") - } - attribute.Value = stringFromBuffer() - rdn.Attributes = append(rdn.Attributes, attribute) - attribute = new(AttributeTypeAndValue) - if char == ',' { - dn.RDNs = append(dn.RDNs, rdn) - rdn = new(RelativeDN) - rdn.Attributes = make([]*AttributeTypeAndValue, 0) - } - case char == ' ' && buffer.Len() == 0: - // ignore unescaped leading spaces - continue - default: - if char == ' ' { - // Track unescaped spaces in case they are trailing and we need to remove them - unescapedTrailingSpaces++ - } else { - // Reset if we see a non-space char - unescapedTrailingSpaces = 0 - } - buffer.WriteByte(char) - } - } - if buffer.Len() > 0 { - if len(attribute.Type) == 0 { - return nil, errors.New("DN ended with incomplete type, value pair") - } - attribute.Value = stringFromBuffer() - rdn.Attributes = append(rdn.Attributes, attribute) - dn.RDNs = append(dn.RDNs, rdn) - } - return dn, nil -} - -// Equal returns true if the DNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch). -// Returns true if they have the same number of relative distinguished names -// and corresponding relative distinguished names (by position) are the same. -func (d *DN) Equal(other *DN) bool { - if len(d.RDNs) != len(other.RDNs) { - return false - } - for i := range d.RDNs { - if !d.RDNs[i].Equal(other.RDNs[i]) { - return false - } - } - return true -} - -// AncestorOf returns true if the other DN consists of at least one RDN followed by all the RDNs of the current DN. -// "ou=widgets,o=acme.com" is an ancestor of "ou=sprockets,ou=widgets,o=acme.com" -// "ou=widgets,o=acme.com" is not an ancestor of "ou=sprockets,ou=widgets,o=foo.com" -// "ou=widgets,o=acme.com" is not an ancestor of "ou=widgets,o=acme.com" -func (d *DN) AncestorOf(other *DN) bool { - if len(d.RDNs) >= len(other.RDNs) { - return false - } - // Take the last `len(d.RDNs)` RDNs from the other DN to compare against - otherRDNs := other.RDNs[len(other.RDNs)-len(d.RDNs):] - for i := range d.RDNs { - if !d.RDNs[i].Equal(otherRDNs[i]) { - return false - } - } - return true -} - -// Equal returns true if the RelativeDNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch). -// Relative distinguished names are the same if and only if they have the same number of AttributeTypeAndValues -// and each attribute of the first RDN is the same as the attribute of the second RDN with the same attribute type. -// The order of attributes is not significant. -// Case of attribute types is not significant. -func (r *RelativeDN) Equal(other *RelativeDN) bool { - if len(r.Attributes) != len(other.Attributes) { - return false - } - return r.hasAllAttributes(other.Attributes) && other.hasAllAttributes(r.Attributes) -} - -func (r *RelativeDN) hasAllAttributes(attrs []*AttributeTypeAndValue) bool { - for _, attr := range attrs { - found := false - for _, myattr := range r.Attributes { - if myattr.Equal(attr) { - found = true - break - } - } - if !found { - return false - } - } - return true -} - -// Equal returns true if the AttributeTypeAndValue is equivalent to the specified AttributeTypeAndValue -// Case of the attribute type is not significant -func (a *AttributeTypeAndValue) Equal(other *AttributeTypeAndValue) bool { - return strings.EqualFold(a.Type, other.Type) && a.Value == other.Value -} - -// Equal returns true if the DNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch). -// Returns true if they have the same number of relative distinguished names -// and corresponding relative distinguished names (by position) are the same. -// Case of the attribute type and value is not significant -func (d *DN) EqualFold(other *DN) bool { - if len(d.RDNs) != len(other.RDNs) { - return false - } - for i := range d.RDNs { - if !d.RDNs[i].EqualFold(other.RDNs[i]) { - return false - } - } - return true -} - -// AncestorOfFold returns true if the other DN consists of at least one RDN followed by all the RDNs of the current DN. -// Case of the attribute type and value is not significant -func (d *DN) AncestorOfFold(other *DN) bool { - if len(d.RDNs) >= len(other.RDNs) { - return false - } - // Take the last `len(d.RDNs)` RDNs from the other DN to compare against - otherRDNs := other.RDNs[len(other.RDNs)-len(d.RDNs):] - for i := range d.RDNs { - if !d.RDNs[i].EqualFold(otherRDNs[i]) { - return false - } - } - return true -} - -// Equal returns true if the RelativeDNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch). -// Case of the attribute type is not significant -func (r *RelativeDN) EqualFold(other *RelativeDN) bool { - if len(r.Attributes) != len(other.Attributes) { - return false - } - return r.hasAllAttributesFold(other.Attributes) && other.hasAllAttributesFold(r.Attributes) -} - -func (r *RelativeDN) hasAllAttributesFold(attrs []*AttributeTypeAndValue) bool { - for _, attr := range attrs { - found := false - for _, myattr := range r.Attributes { - if myattr.EqualFold(attr) { - found = true - break - } - } - if !found { - return false - } - } - return true -} - -// EqualFold returns true if the AttributeTypeAndValue is equivalent to the specified AttributeTypeAndValue -// Case of the attribute type and value is not significant -func (a *AttributeTypeAndValue) EqualFold(other *AttributeTypeAndValue) bool { - return strings.EqualFold(a.Type, other.Type) && strings.EqualFold(a.Value, other.Value) -} diff --git a/vendor/github.com/go-ldap/ldap/v3/doc.go b/vendor/github.com/go-ldap/ldap/v3/doc.go deleted file mode 100644 index f20d39bc99..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package ldap provides basic LDAP v3 functionality. -*/ -package ldap diff --git a/vendor/github.com/go-ldap/ldap/v3/error.go b/vendor/github.com/go-ldap/ldap/v3/error.go deleted file mode 100644 index 3cdb7b318c..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/error.go +++ /dev/null @@ -1,253 +0,0 @@ -package ldap - -import ( - "fmt" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// LDAP Result Codes -const ( - LDAPResultSuccess = 0 - LDAPResultOperationsError = 1 - LDAPResultProtocolError = 2 - LDAPResultTimeLimitExceeded = 3 - LDAPResultSizeLimitExceeded = 4 - LDAPResultCompareFalse = 5 - LDAPResultCompareTrue = 6 - LDAPResultAuthMethodNotSupported = 7 - LDAPResultStrongAuthRequired = 8 - LDAPResultReferral = 10 - LDAPResultAdminLimitExceeded = 11 - LDAPResultUnavailableCriticalExtension = 12 - LDAPResultConfidentialityRequired = 13 - LDAPResultSaslBindInProgress = 14 - LDAPResultNoSuchAttribute = 16 - LDAPResultUndefinedAttributeType = 17 - LDAPResultInappropriateMatching = 18 - LDAPResultConstraintViolation = 19 - LDAPResultAttributeOrValueExists = 20 - LDAPResultInvalidAttributeSyntax = 21 - LDAPResultNoSuchObject = 32 - LDAPResultAliasProblem = 33 - LDAPResultInvalidDNSyntax = 34 - LDAPResultIsLeaf = 35 - LDAPResultAliasDereferencingProblem = 36 - LDAPResultInappropriateAuthentication = 48 - LDAPResultInvalidCredentials = 49 - LDAPResultInsufficientAccessRights = 50 - LDAPResultBusy = 51 - LDAPResultUnavailable = 52 - LDAPResultUnwillingToPerform = 53 - LDAPResultLoopDetect = 54 - LDAPResultSortControlMissing = 60 - LDAPResultOffsetRangeError = 61 - LDAPResultNamingViolation = 64 - LDAPResultObjectClassViolation = 65 - LDAPResultNotAllowedOnNonLeaf = 66 - LDAPResultNotAllowedOnRDN = 67 - LDAPResultEntryAlreadyExists = 68 - LDAPResultObjectClassModsProhibited = 69 - LDAPResultResultsTooLarge = 70 - LDAPResultAffectsMultipleDSAs = 71 - LDAPResultVirtualListViewErrorOrControlError = 76 - LDAPResultOther = 80 - LDAPResultServerDown = 81 - LDAPResultLocalError = 82 - LDAPResultEncodingError = 83 - LDAPResultDecodingError = 84 - LDAPResultTimeout = 85 - LDAPResultAuthUnknown = 86 - LDAPResultFilterError = 87 - LDAPResultUserCanceled = 88 - LDAPResultParamError = 89 - LDAPResultNoMemory = 90 - LDAPResultConnectError = 91 - LDAPResultNotSupported = 92 - LDAPResultControlNotFound = 93 - LDAPResultNoResultsReturned = 94 - LDAPResultMoreResultsToReturn = 95 - LDAPResultClientLoop = 96 - LDAPResultReferralLimitExceeded = 97 - LDAPResultInvalidResponse = 100 - LDAPResultAmbiguousResponse = 101 - LDAPResultTLSNotSupported = 112 - LDAPResultIntermediateResponse = 113 - LDAPResultUnknownType = 114 - LDAPResultCanceled = 118 - LDAPResultNoSuchOperation = 119 - LDAPResultTooLate = 120 - LDAPResultCannotCancel = 121 - LDAPResultAssertionFailed = 122 - LDAPResultAuthorizationDenied = 123 - LDAPResultSyncRefreshRequired = 4096 - - ErrorNetwork = 200 - ErrorFilterCompile = 201 - ErrorFilterDecompile = 202 - ErrorDebugging = 203 - ErrorUnexpectedMessage = 204 - ErrorUnexpectedResponse = 205 - ErrorEmptyPassword = 206 -) - -// LDAPResultCodeMap contains string descriptions for LDAP error codes -var LDAPResultCodeMap = map[uint16]string{ - LDAPResultSuccess: "Success", - LDAPResultOperationsError: "Operations Error", - LDAPResultProtocolError: "Protocol Error", - LDAPResultTimeLimitExceeded: "Time Limit Exceeded", - LDAPResultSizeLimitExceeded: "Size Limit Exceeded", - LDAPResultCompareFalse: "Compare False", - LDAPResultCompareTrue: "Compare True", - LDAPResultAuthMethodNotSupported: "Auth Method Not Supported", - LDAPResultStrongAuthRequired: "Strong Auth Required", - LDAPResultReferral: "Referral", - LDAPResultAdminLimitExceeded: "Admin Limit Exceeded", - LDAPResultUnavailableCriticalExtension: "Unavailable Critical Extension", - LDAPResultConfidentialityRequired: "Confidentiality Required", - LDAPResultSaslBindInProgress: "Sasl Bind In Progress", - LDAPResultNoSuchAttribute: "No Such Attribute", - LDAPResultUndefinedAttributeType: "Undefined Attribute Type", - LDAPResultInappropriateMatching: "Inappropriate Matching", - LDAPResultConstraintViolation: "Constraint Violation", - LDAPResultAttributeOrValueExists: "Attribute Or Value Exists", - LDAPResultInvalidAttributeSyntax: "Invalid Attribute Syntax", - LDAPResultNoSuchObject: "No Such Object", - LDAPResultAliasProblem: "Alias Problem", - LDAPResultInvalidDNSyntax: "Invalid DN Syntax", - LDAPResultIsLeaf: "Is Leaf", - LDAPResultAliasDereferencingProblem: "Alias Dereferencing Problem", - LDAPResultInappropriateAuthentication: "Inappropriate Authentication", - LDAPResultInvalidCredentials: "Invalid Credentials", - LDAPResultInsufficientAccessRights: "Insufficient Access Rights", - LDAPResultBusy: "Busy", - LDAPResultUnavailable: "Unavailable", - LDAPResultUnwillingToPerform: "Unwilling To Perform", - LDAPResultLoopDetect: "Loop Detect", - LDAPResultSortControlMissing: "Sort Control Missing", - LDAPResultOffsetRangeError: "Result Offset Range Error", - LDAPResultNamingViolation: "Naming Violation", - LDAPResultObjectClassViolation: "Object Class Violation", - LDAPResultResultsTooLarge: "Results Too Large", - LDAPResultNotAllowedOnNonLeaf: "Not Allowed On Non Leaf", - LDAPResultNotAllowedOnRDN: "Not Allowed On RDN", - LDAPResultEntryAlreadyExists: "Entry Already Exists", - LDAPResultObjectClassModsProhibited: "Object Class Mods Prohibited", - LDAPResultAffectsMultipleDSAs: "Affects Multiple DSAs", - LDAPResultVirtualListViewErrorOrControlError: "Failed because of a problem related to the virtual list view", - LDAPResultOther: "Other", - LDAPResultServerDown: "Cannot establish a connection", - LDAPResultLocalError: "An error occurred", - LDAPResultEncodingError: "LDAP encountered an error while encoding", - LDAPResultDecodingError: "LDAP encountered an error while decoding", - LDAPResultTimeout: "LDAP timeout while waiting for a response from the server", - LDAPResultAuthUnknown: "The auth method requested in a bind request is unknown", - LDAPResultFilterError: "An error occurred while encoding the given search filter", - LDAPResultUserCanceled: "The user canceled the operation", - LDAPResultParamError: "An invalid parameter was specified", - LDAPResultNoMemory: "Out of memory error", - LDAPResultConnectError: "A connection to the server could not be established", - LDAPResultNotSupported: "An attempt has been made to use a feature not supported LDAP", - LDAPResultControlNotFound: "The controls required to perform the requested operation were not found", - LDAPResultNoResultsReturned: "No results were returned from the server", - LDAPResultMoreResultsToReturn: "There are more results in the chain of results", - LDAPResultClientLoop: "A loop has been detected. For example when following referrals", - LDAPResultReferralLimitExceeded: "The referral hop limit has been exceeded", - LDAPResultCanceled: "Operation was canceled", - LDAPResultNoSuchOperation: "Server has no knowledge of the operation requested for cancellation", - LDAPResultTooLate: "Too late to cancel the outstanding operation", - LDAPResultCannotCancel: "The identified operation does not support cancellation or the cancel operation cannot be performed", - LDAPResultAssertionFailed: "An assertion control given in the LDAP operation evaluated to false causing the operation to not be performed", - LDAPResultSyncRefreshRequired: "Refresh Required", - LDAPResultInvalidResponse: "Invalid Response", - LDAPResultAmbiguousResponse: "Ambiguous Response", - LDAPResultTLSNotSupported: "Tls Not Supported", - LDAPResultIntermediateResponse: "Intermediate Response", - LDAPResultUnknownType: "Unknown Type", - LDAPResultAuthorizationDenied: "Authorization Denied", - - ErrorNetwork: "Network Error", - ErrorFilterCompile: "Filter Compile Error", - ErrorFilterDecompile: "Filter Decompile Error", - ErrorDebugging: "Debugging Error", - ErrorUnexpectedMessage: "Unexpected Message", - ErrorUnexpectedResponse: "Unexpected Response", - ErrorEmptyPassword: "Empty password not allowed by the client", -} - -// Error holds LDAP error information -type Error struct { - // Err is the underlying error - Err error - // ResultCode is the LDAP error code - ResultCode uint16 - // MatchedDN is the matchedDN returned if any - MatchedDN string - // Packet is the returned packet if any - Packet *ber.Packet -} - -func (e *Error) Error() string { - return fmt.Sprintf("LDAP Result Code %d %q: %s", e.ResultCode, LDAPResultCodeMap[e.ResultCode], e.Err.Error()) -} - -// GetLDAPError creates an Error out of a BER packet representing a LDAPResult -// The return is an error object. It can be casted to a Error structure. -// This function returns nil if resultCode in the LDAPResult sequence is success(0). -func GetLDAPError(packet *ber.Packet) error { - if packet == nil { - return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("Empty packet")} - } - - if len(packet.Children) >= 2 { - response := packet.Children[1] - if response == nil { - return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("Empty response in packet"), Packet: packet} - } - if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed && len(response.Children) >= 3 { - resultCode := uint16(response.Children[0].Value.(int64)) - if resultCode == 0 { // No error - return nil - } - return &Error{ - ResultCode: resultCode, - MatchedDN: response.Children[1].Value.(string), - Err: fmt.Errorf("%s", response.Children[2].Value.(string)), - Packet: packet, - } - } - } - - return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("Invalid packet format"), Packet: packet} -} - -// NewError creates an LDAP error with the given code and underlying error -func NewError(resultCode uint16, err error) error { - return &Error{ResultCode: resultCode, Err: err} -} - -// IsErrorAnyOf returns true if the given error is an LDAP error with any one of the given result codes -func IsErrorAnyOf(err error, codes ...uint16) bool { - if err == nil { - return false - } - - serverError, ok := err.(*Error) - if !ok { - return false - } - - for _, code := range codes { - if serverError.ResultCode == code { - return true - } - } - - return false -} - -// IsErrorWithCode returns true if the given error is an LDAP error with the given result code -func IsErrorWithCode(err error, desiredResultCode uint16) bool { - return IsErrorAnyOf(err, desiredResultCode) -} diff --git a/vendor/github.com/go-ldap/ldap/v3/filter.go b/vendor/github.com/go-ldap/ldap/v3/filter.go deleted file mode 100644 index 73505e79b6..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/filter.go +++ /dev/null @@ -1,487 +0,0 @@ -package ldap - -import ( - "bytes" - hexpac "encoding/hex" - "errors" - "fmt" - "io" - "strings" - "unicode" - "unicode/utf8" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// Filter choices -const ( - FilterAnd = 0 - FilterOr = 1 - FilterNot = 2 - FilterEqualityMatch = 3 - FilterSubstrings = 4 - FilterGreaterOrEqual = 5 - FilterLessOrEqual = 6 - FilterPresent = 7 - FilterApproxMatch = 8 - FilterExtensibleMatch = 9 -) - -// FilterMap contains human readable descriptions of Filter choices -var FilterMap = map[uint64]string{ - FilterAnd: "And", - FilterOr: "Or", - FilterNot: "Not", - FilterEqualityMatch: "Equality Match", - FilterSubstrings: "Substrings", - FilterGreaterOrEqual: "Greater Or Equal", - FilterLessOrEqual: "Less Or Equal", - FilterPresent: "Present", - FilterApproxMatch: "Approx Match", - FilterExtensibleMatch: "Extensible Match", -} - -// SubstringFilter options -const ( - FilterSubstringsInitial = 0 - FilterSubstringsAny = 1 - FilterSubstringsFinal = 2 -) - -// FilterSubstringsMap contains human readable descriptions of SubstringFilter choices -var FilterSubstringsMap = map[uint64]string{ - FilterSubstringsInitial: "Substrings Initial", - FilterSubstringsAny: "Substrings Any", - FilterSubstringsFinal: "Substrings Final", -} - -// MatchingRuleAssertion choices -const ( - MatchingRuleAssertionMatchingRule = 1 - MatchingRuleAssertionType = 2 - MatchingRuleAssertionMatchValue = 3 - MatchingRuleAssertionDNAttributes = 4 -) - -// MatchingRuleAssertionMap contains human readable descriptions of MatchingRuleAssertion choices -var MatchingRuleAssertionMap = map[uint64]string{ - MatchingRuleAssertionMatchingRule: "Matching Rule Assertion Matching Rule", - MatchingRuleAssertionType: "Matching Rule Assertion Type", - MatchingRuleAssertionMatchValue: "Matching Rule Assertion Match Value", - MatchingRuleAssertionDNAttributes: "Matching Rule Assertion DN Attributes", -} - -var _SymbolAny = []byte{'*'} - -// CompileFilter converts a string representation of a filter into a BER-encoded packet -func CompileFilter(filter string) (*ber.Packet, error) { - if len(filter) == 0 || filter[0] != '(' { - return nil, NewError(ErrorFilterCompile, errors.New("ldap: filter does not start with an '('")) - } - packet, pos, err := compileFilter(filter, 1) - if err != nil { - return nil, err - } - switch { - case pos > len(filter): - return nil, NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter")) - case pos < len(filter): - return nil, NewError(ErrorFilterCompile, errors.New("ldap: finished compiling filter with extra at end: "+fmt.Sprint(filter[pos:]))) - } - return packet, nil -} - -// DecompileFilter converts a packet representation of a filter into a string representation -func DecompileFilter(packet *ber.Packet) (_ string, err error) { - defer func() { - if r := recover(); r != nil { - err = NewError(ErrorFilterDecompile, errors.New("ldap: error decompiling filter")) - } - }() - - buf := bytes.NewBuffer(nil) - buf.WriteByte('(') - childStr := "" - - switch packet.Tag { - case FilterAnd: - buf.WriteByte('&') - for _, child := range packet.Children { - childStr, err = DecompileFilter(child) - if err != nil { - return - } - buf.WriteString(childStr) - } - case FilterOr: - buf.WriteByte('|') - for _, child := range packet.Children { - childStr, err = DecompileFilter(child) - if err != nil { - return - } - buf.WriteString(childStr) - } - case FilterNot: - buf.WriteByte('!') - childStr, err = DecompileFilter(packet.Children[0]) - if err != nil { - return - } - buf.WriteString(childStr) - - case FilterSubstrings: - buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes())) - buf.WriteByte('=') - for i, child := range packet.Children[1].Children { - if i == 0 && child.Tag != FilterSubstringsInitial { - buf.Write(_SymbolAny) - } - buf.WriteString(EscapeFilter(ber.DecodeString(child.Data.Bytes()))) - if child.Tag != FilterSubstringsFinal { - buf.Write(_SymbolAny) - } - } - case FilterEqualityMatch: - buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes())) - buf.WriteByte('=') - buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes()))) - case FilterGreaterOrEqual: - buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes())) - buf.WriteString(">=") - buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes()))) - case FilterLessOrEqual: - buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes())) - buf.WriteString("<=") - buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes()))) - case FilterPresent: - buf.WriteString(ber.DecodeString(packet.Data.Bytes())) - buf.WriteString("=*") - case FilterApproxMatch: - buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes())) - buf.WriteString("~=") - buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes()))) - case FilterExtensibleMatch: - attr := "" - dnAttributes := false - matchingRule := "" - value := "" - - for _, child := range packet.Children { - switch child.Tag { - case MatchingRuleAssertionMatchingRule: - matchingRule = ber.DecodeString(child.Data.Bytes()) - case MatchingRuleAssertionType: - attr = ber.DecodeString(child.Data.Bytes()) - case MatchingRuleAssertionMatchValue: - value = ber.DecodeString(child.Data.Bytes()) - case MatchingRuleAssertionDNAttributes: - dnAttributes = child.Value.(bool) - } - } - - if len(attr) > 0 { - buf.WriteString(attr) - } - if dnAttributes { - buf.WriteString(":dn") - } - if len(matchingRule) > 0 { - buf.WriteString(":") - buf.WriteString(matchingRule) - } - buf.WriteString(":=") - buf.WriteString(EscapeFilter(value)) - } - - buf.WriteByte(')') - - return buf.String(), nil -} - -func compileFilterSet(filter string, pos int, parent *ber.Packet) (int, error) { - for pos < len(filter) && filter[pos] == '(' { - child, newPos, err := compileFilter(filter, pos+1) - if err != nil { - return pos, err - } - pos = newPos - parent.AppendChild(child) - } - if pos == len(filter) { - return pos, NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter")) - } - - return pos + 1, nil -} - -func compileFilter(filter string, pos int) (*ber.Packet, int, error) { - var ( - packet *ber.Packet - err error - ) - - defer func() { - if r := recover(); r != nil { - err = NewError(ErrorFilterCompile, errors.New("ldap: error compiling filter")) - } - }() - newPos := pos - - currentRune, currentWidth := utf8.DecodeRuneInString(filter[newPos:]) - - switch currentRune { - case utf8.RuneError: - return nil, 0, NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", newPos)) - case '(': - packet, newPos, err = compileFilter(filter, pos+currentWidth) - newPos++ - return packet, newPos, err - case '&': - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterAnd, nil, FilterMap[FilterAnd]) - newPos, err = compileFilterSet(filter, pos+currentWidth, packet) - return packet, newPos, err - case '|': - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterOr, nil, FilterMap[FilterOr]) - newPos, err = compileFilterSet(filter, pos+currentWidth, packet) - return packet, newPos, err - case '!': - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterNot, nil, FilterMap[FilterNot]) - var child *ber.Packet - child, newPos, err = compileFilter(filter, pos+currentWidth) - packet.AppendChild(child) - return packet, newPos, err - default: - const ( - stateReadingAttr = 0 - stateReadingExtensibleMatchingRule = 1 - stateReadingCondition = 2 - ) - - state := stateReadingAttr - attribute := bytes.NewBuffer(nil) - extensibleDNAttributes := false - extensibleMatchingRule := bytes.NewBuffer(nil) - condition := bytes.NewBuffer(nil) - - for newPos < len(filter) { - remainingFilter := filter[newPos:] - currentRune, currentWidth = utf8.DecodeRuneInString(remainingFilter) - if currentRune == ')' { - break - } - if currentRune == utf8.RuneError { - return packet, newPos, NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", newPos)) - } - - switch state { - case stateReadingAttr: - switch { - // Extensible rule, with only DN-matching - case currentRune == ':' && strings.HasPrefix(remainingFilter, ":dn:="): - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterExtensibleMatch, nil, FilterMap[FilterExtensibleMatch]) - extensibleDNAttributes = true - state = stateReadingCondition - newPos += 5 - - // Extensible rule, with DN-matching and a matching OID - case currentRune == ':' && strings.HasPrefix(remainingFilter, ":dn:"): - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterExtensibleMatch, nil, FilterMap[FilterExtensibleMatch]) - extensibleDNAttributes = true - state = stateReadingExtensibleMatchingRule - newPos += 4 - - // Extensible rule, with attr only - case currentRune == ':' && strings.HasPrefix(remainingFilter, ":="): - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterExtensibleMatch, nil, FilterMap[FilterExtensibleMatch]) - state = stateReadingCondition - newPos += 2 - - // Extensible rule, with no DN attribute matching - case currentRune == ':': - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterExtensibleMatch, nil, FilterMap[FilterExtensibleMatch]) - state = stateReadingExtensibleMatchingRule - newPos++ - - // Equality condition - case currentRune == '=': - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterEqualityMatch, nil, FilterMap[FilterEqualityMatch]) - state = stateReadingCondition - newPos++ - - // Greater-than or equal - case currentRune == '>' && strings.HasPrefix(remainingFilter, ">="): - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterGreaterOrEqual, nil, FilterMap[FilterGreaterOrEqual]) - state = stateReadingCondition - newPos += 2 - - // Less-than or equal - case currentRune == '<' && strings.HasPrefix(remainingFilter, "<="): - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterLessOrEqual, nil, FilterMap[FilterLessOrEqual]) - state = stateReadingCondition - newPos += 2 - - // Approx - case currentRune == '~' && strings.HasPrefix(remainingFilter, "~="): - packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterApproxMatch, nil, FilterMap[FilterApproxMatch]) - state = stateReadingCondition - newPos += 2 - - // Still reading the attribute name - default: - attribute.WriteRune(currentRune) - newPos += currentWidth - } - - case stateReadingExtensibleMatchingRule: - switch { - - // Matching rule OID is done - case currentRune == ':' && strings.HasPrefix(remainingFilter, ":="): - state = stateReadingCondition - newPos += 2 - - // Still reading the matching rule oid - default: - extensibleMatchingRule.WriteRune(currentRune) - newPos += currentWidth - } - - case stateReadingCondition: - // append to the condition - condition.WriteRune(currentRune) - newPos += currentWidth - } - } - - if newPos == len(filter) { - err = NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter")) - return packet, newPos, err - } - if packet == nil { - err = NewError(ErrorFilterCompile, errors.New("ldap: error parsing filter")) - return packet, newPos, err - } - - switch { - case packet.Tag == FilterExtensibleMatch: - // MatchingRuleAssertion ::= SEQUENCE { - // matchingRule [1] MatchingRuleID OPTIONAL, - // type [2] AttributeDescription OPTIONAL, - // matchValue [3] AssertionValue, - // dnAttributes [4] BOOLEAN DEFAULT FALSE - // } - - // Include the matching rule oid, if specified - if extensibleMatchingRule.Len() > 0 { - packet.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, MatchingRuleAssertionMatchingRule, extensibleMatchingRule.String(), MatchingRuleAssertionMap[MatchingRuleAssertionMatchingRule])) - } - - // Include the attribute, if specified - if attribute.Len() > 0 { - packet.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, MatchingRuleAssertionType, attribute.String(), MatchingRuleAssertionMap[MatchingRuleAssertionType])) - } - - // Add the value (only required child) - encodedString, encodeErr := decodeEscapedSymbols(condition.Bytes()) - if encodeErr != nil { - return packet, newPos, encodeErr - } - packet.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, MatchingRuleAssertionMatchValue, encodedString, MatchingRuleAssertionMap[MatchingRuleAssertionMatchValue])) - - // Defaults to false, so only include in the sequence if true - if extensibleDNAttributes { - packet.AppendChild(ber.NewBoolean(ber.ClassContext, ber.TypePrimitive, MatchingRuleAssertionDNAttributes, extensibleDNAttributes, MatchingRuleAssertionMap[MatchingRuleAssertionDNAttributes])) - } - - case packet.Tag == FilterEqualityMatch && bytes.Equal(condition.Bytes(), _SymbolAny): - packet = ber.NewString(ber.ClassContext, ber.TypePrimitive, FilterPresent, attribute.String(), FilterMap[FilterPresent]) - case packet.Tag == FilterEqualityMatch && bytes.Index(condition.Bytes(), _SymbolAny) > -1: - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, attribute.String(), "Attribute")) - packet.Tag = FilterSubstrings - packet.Description = FilterMap[uint64(packet.Tag)] - seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Substrings") - parts := bytes.Split(condition.Bytes(), _SymbolAny) - for i, part := range parts { - if len(part) == 0 { - continue - } - var tag ber.Tag - switch i { - case 0: - tag = FilterSubstringsInitial - case len(parts) - 1: - tag = FilterSubstringsFinal - default: - tag = FilterSubstringsAny - } - encodedString, encodeErr := decodeEscapedSymbols(part) - if encodeErr != nil { - return packet, newPos, encodeErr - } - seq.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, tag, encodedString, FilterSubstringsMap[uint64(tag)])) - } - packet.AppendChild(seq) - default: - encodedString, encodeErr := decodeEscapedSymbols(condition.Bytes()) - if encodeErr != nil { - return packet, newPos, encodeErr - } - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, attribute.String(), "Attribute")) - packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, encodedString, "Condition")) - } - - newPos += currentWidth - return packet, newPos, err - } -} - -// Convert from "ABC\xx\xx\xx" form to literal bytes for transport -func decodeEscapedSymbols(src []byte) (string, error) { - - var ( - buffer bytes.Buffer - offset int - reader = bytes.NewReader(src) - byteHex []byte - byteVal []byte - ) - - for { - runeVal, runeSize, err := reader.ReadRune() - if err == io.EOF { - return buffer.String(), nil - } else if err != nil { - return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: failed to read filter: %v", err)) - } else if runeVal == unicode.ReplacementChar { - return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", offset)) - } - - if runeVal == '\\' { - // http://tools.ietf.org/search/rfc4515 - // \ (%x5C) is not a valid character unless it is followed by two HEX characters due to not - // being a member of UTF1SUBSET. - if byteHex == nil { - byteHex = make([]byte, 2) - byteVal = make([]byte, 1) - } - - if _, err := io.ReadFull(reader, byteHex); err != nil { - if err == io.ErrUnexpectedEOF { - return "", NewError(ErrorFilterCompile, errors.New("ldap: missing characters for escape in filter")) - } - return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: invalid characters for escape in filter: %v", err)) - } - - if _, err := hexpac.Decode(byteVal, byteHex); err != nil { - return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: invalid characters for escape in filter: %v", err)) - } - - buffer.Write(byteVal) - } else { - buffer.WriteRune(runeVal) - } - - offset += runeSize - } -} diff --git a/vendor/github.com/go-ldap/ldap/v3/ldap.go b/vendor/github.com/go-ldap/ldap/v3/ldap.go deleted file mode 100644 index 7ae6dfe2cc..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/ldap.go +++ /dev/null @@ -1,339 +0,0 @@ -package ldap - -import ( - "fmt" - "io/ioutil" - "os" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// LDAP Application Codes -const ( - ApplicationBindRequest = 0 - ApplicationBindResponse = 1 - ApplicationUnbindRequest = 2 - ApplicationSearchRequest = 3 - ApplicationSearchResultEntry = 4 - ApplicationSearchResultDone = 5 - ApplicationModifyRequest = 6 - ApplicationModifyResponse = 7 - ApplicationAddRequest = 8 - ApplicationAddResponse = 9 - ApplicationDelRequest = 10 - ApplicationDelResponse = 11 - ApplicationModifyDNRequest = 12 - ApplicationModifyDNResponse = 13 - ApplicationCompareRequest = 14 - ApplicationCompareResponse = 15 - ApplicationAbandonRequest = 16 - ApplicationSearchResultReference = 19 - ApplicationExtendedRequest = 23 - ApplicationExtendedResponse = 24 -) - -// ApplicationMap contains human readable descriptions of LDAP Application Codes -var ApplicationMap = map[uint8]string{ - ApplicationBindRequest: "Bind Request", - ApplicationBindResponse: "Bind Response", - ApplicationUnbindRequest: "Unbind Request", - ApplicationSearchRequest: "Search Request", - ApplicationSearchResultEntry: "Search Result Entry", - ApplicationSearchResultDone: "Search Result Done", - ApplicationModifyRequest: "Modify Request", - ApplicationModifyResponse: "Modify Response", - ApplicationAddRequest: "Add Request", - ApplicationAddResponse: "Add Response", - ApplicationDelRequest: "Del Request", - ApplicationDelResponse: "Del Response", - ApplicationModifyDNRequest: "Modify DN Request", - ApplicationModifyDNResponse: "Modify DN Response", - ApplicationCompareRequest: "Compare Request", - ApplicationCompareResponse: "Compare Response", - ApplicationAbandonRequest: "Abandon Request", - ApplicationSearchResultReference: "Search Result Reference", - ApplicationExtendedRequest: "Extended Request", - ApplicationExtendedResponse: "Extended Response", -} - -// Ldap Behera Password Policy Draft 10 (https://tools.ietf.org/html/draft-behera-ldap-password-policy-10) -const ( - BeheraPasswordExpired = 0 - BeheraAccountLocked = 1 - BeheraChangeAfterReset = 2 - BeheraPasswordModNotAllowed = 3 - BeheraMustSupplyOldPassword = 4 - BeheraInsufficientPasswordQuality = 5 - BeheraPasswordTooShort = 6 - BeheraPasswordTooYoung = 7 - BeheraPasswordInHistory = 8 -) - -// BeheraPasswordPolicyErrorMap contains human readable descriptions of Behera Password Policy error codes -var BeheraPasswordPolicyErrorMap = map[int8]string{ - BeheraPasswordExpired: "Password expired", - BeheraAccountLocked: "Account locked", - BeheraChangeAfterReset: "Password must be changed", - BeheraPasswordModNotAllowed: "Policy prevents password modification", - BeheraMustSupplyOldPassword: "Policy requires old password in order to change password", - BeheraInsufficientPasswordQuality: "Password fails quality checks", - BeheraPasswordTooShort: "Password is too short for policy", - BeheraPasswordTooYoung: "Password has been changed too recently", - BeheraPasswordInHistory: "New password is in list of old passwords", -} - -// Adds descriptions to an LDAP Response packet for debugging -func addLDAPDescriptions(packet *ber.Packet) (err error) { - defer func() { - if r := recover(); r != nil { - err = NewError(ErrorDebugging, fmt.Errorf("ldap: cannot process packet to add descriptions: %s", r)) - } - }() - packet.Description = "LDAP Response" - packet.Children[0].Description = "Message ID" - - application := uint8(packet.Children[1].Tag) - packet.Children[1].Description = ApplicationMap[application] - - switch application { - case ApplicationBindRequest: - err = addRequestDescriptions(packet) - case ApplicationBindResponse: - err = addDefaultLDAPResponseDescriptions(packet) - case ApplicationUnbindRequest: - err = addRequestDescriptions(packet) - case ApplicationSearchRequest: - err = addRequestDescriptions(packet) - case ApplicationSearchResultEntry: - packet.Children[1].Children[0].Description = "Object Name" - packet.Children[1].Children[1].Description = "Attributes" - for _, child := range packet.Children[1].Children[1].Children { - child.Description = "Attribute" - child.Children[0].Description = "Attribute Name" - child.Children[1].Description = "Attribute Values" - for _, grandchild := range child.Children[1].Children { - grandchild.Description = "Attribute Value" - } - } - if len(packet.Children) == 3 { - err = addControlDescriptions(packet.Children[2]) - } - case ApplicationSearchResultDone: - err = addDefaultLDAPResponseDescriptions(packet) - case ApplicationModifyRequest: - err = addRequestDescriptions(packet) - case ApplicationModifyResponse: - case ApplicationAddRequest: - err = addRequestDescriptions(packet) - case ApplicationAddResponse: - case ApplicationDelRequest: - err = addRequestDescriptions(packet) - case ApplicationDelResponse: - case ApplicationModifyDNRequest: - err = addRequestDescriptions(packet) - case ApplicationModifyDNResponse: - case ApplicationCompareRequest: - err = addRequestDescriptions(packet) - case ApplicationCompareResponse: - case ApplicationAbandonRequest: - err = addRequestDescriptions(packet) - case ApplicationSearchResultReference: - case ApplicationExtendedRequest: - err = addRequestDescriptions(packet) - case ApplicationExtendedResponse: - } - - return err -} - -func addControlDescriptions(packet *ber.Packet) error { - packet.Description = "Controls" - for _, child := range packet.Children { - var value *ber.Packet - controlType := "" - child.Description = "Control" - switch len(child.Children) { - case 0: - // at least one child is required for control type - return fmt.Errorf("at least one child is required for control type") - - case 1: - // just type, no criticality or value - controlType = child.Children[0].Value.(string) - child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")" - - case 2: - controlType = child.Children[0].Value.(string) - child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")" - // Children[1] could be criticality or value (both are optional) - // duck-type on whether this is a boolean - if _, ok := child.Children[1].Value.(bool); ok { - child.Children[1].Description = "Criticality" - } else { - child.Children[1].Description = "Control Value" - value = child.Children[1] - } - - case 3: - // criticality and value present - controlType = child.Children[0].Value.(string) - child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")" - child.Children[1].Description = "Criticality" - child.Children[2].Description = "Control Value" - value = child.Children[2] - - default: - // more than 3 children is invalid - return fmt.Errorf("more than 3 children for control packet found") - } - - if value == nil { - continue - } - switch controlType { - case ControlTypePaging: - value.Description += " (Paging)" - if value.Value != nil { - valueChildren, err := ber.DecodePacketErr(value.Data.Bytes()) - if err != nil { - return fmt.Errorf("failed to decode data bytes: %s", err) - } - value.Data.Truncate(0) - value.Value = nil - valueChildren.Children[1].Value = valueChildren.Children[1].Data.Bytes() - value.AppendChild(valueChildren) - } - value.Children[0].Description = "Real Search Control Value" - value.Children[0].Children[0].Description = "Paging Size" - value.Children[0].Children[1].Description = "Cookie" - - case ControlTypeBeheraPasswordPolicy: - value.Description += " (Password Policy - Behera Draft)" - if value.Value != nil { - valueChildren, err := ber.DecodePacketErr(value.Data.Bytes()) - if err != nil { - return fmt.Errorf("failed to decode data bytes: %s", err) - } - value.Data.Truncate(0) - value.Value = nil - value.AppendChild(valueChildren) - } - sequence := value.Children[0] - for _, child := range sequence.Children { - if child.Tag == 0 { - //Warning - warningPacket := child.Children[0] - val, err := ber.ParseInt64(warningPacket.Data.Bytes()) - if err != nil { - return fmt.Errorf("failed to decode data bytes: %s", err) - } - if warningPacket.Tag == 0 { - //timeBeforeExpiration - value.Description += " (TimeBeforeExpiration)" - warningPacket.Value = val - } else if warningPacket.Tag == 1 { - //graceAuthNsRemaining - value.Description += " (GraceAuthNsRemaining)" - warningPacket.Value = val - } - } else if child.Tag == 1 { - // Error - bs := child.Data.Bytes() - if len(bs) != 1 || bs[0] > 8 { - return fmt.Errorf("failed to decode data bytes: %s", "invalid PasswordPolicyResponse enum value") - } - val := int8(bs[0]) - child.Description = "Error" - child.Value = val - } - } - } - } - return nil -} - -func addRequestDescriptions(packet *ber.Packet) error { - packet.Description = "LDAP Request" - packet.Children[0].Description = "Message ID" - packet.Children[1].Description = ApplicationMap[uint8(packet.Children[1].Tag)] - if len(packet.Children) == 3 { - return addControlDescriptions(packet.Children[2]) - } - return nil -} - -func addDefaultLDAPResponseDescriptions(packet *ber.Packet) error { - resultCode := uint16(LDAPResultSuccess) - matchedDN := "" - description := "Success" - if err := GetLDAPError(packet); err != nil { - resultCode = err.(*Error).ResultCode - matchedDN = err.(*Error).MatchedDN - description = "Error Message" - } - - packet.Children[1].Children[0].Description = "Result Code (" + LDAPResultCodeMap[resultCode] + ")" - packet.Children[1].Children[1].Description = "Matched DN (" + matchedDN + ")" - packet.Children[1].Children[2].Description = description - if len(packet.Children[1].Children) > 3 { - packet.Children[1].Children[3].Description = "Referral" - } - if len(packet.Children) == 3 { - return addControlDescriptions(packet.Children[2]) - } - return nil -} - -// DebugBinaryFile reads and prints packets from the given filename -func DebugBinaryFile(fileName string) error { - file, err := ioutil.ReadFile(fileName) - if err != nil { - return NewError(ErrorDebugging, err) - } - ber.PrintBytes(os.Stdout, file, "") - packet, err := ber.DecodePacketErr(file) - if err != nil { - return fmt.Errorf("failed to decode packet: %s", err) - } - if err := addLDAPDescriptions(packet); err != nil { - return err - } - ber.PrintPacket(packet) - - return nil -} - -var hex = "0123456789abcdef" - -func mustEscape(c byte) bool { - return c > 0x7f || c == '(' || c == ')' || c == '\\' || c == '*' || c == 0 -} - -// EscapeFilter escapes from the provided LDAP filter string the special -// characters in the set `()*\` and those out of the range 0 < c < 0x80, -// as defined in RFC4515. -func EscapeFilter(filter string) string { - escape := 0 - for i := 0; i < len(filter); i++ { - if mustEscape(filter[i]) { - escape++ - } - } - if escape == 0 { - return filter - } - buf := make([]byte, len(filter)+escape*2) - for i, j := 0, 0; i < len(filter); i++ { - c := filter[i] - if mustEscape(c) { - buf[j+0] = '\\' - buf[j+1] = hex[c>>4] - buf[j+2] = hex[c&0xf] - j += 3 - } else { - buf[j] = c - j++ - } - } - return string(buf) -} diff --git a/vendor/github.com/go-ldap/ldap/v3/moddn.go b/vendor/github.com/go-ldap/ldap/v3/moddn.go deleted file mode 100644 index 71cdcd0ba8..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/moddn.go +++ /dev/null @@ -1,100 +0,0 @@ -package ldap - -import ( - "log" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// ModifyDNRequest holds the request to modify a DN -type ModifyDNRequest struct { - DN string - NewRDN string - DeleteOldRDN bool - NewSuperior string - // Controls hold optional controls to send with the request - Controls []Control -} - -// NewModifyDNRequest creates a new request which can be passed to ModifyDN(). -// -// To move an object in the tree, set the "newSup" to the new parent entry DN. Use an -// empty string for just changing the object's RDN. -// -// For moving the object without renaming, the "rdn" must be the first -// RDN of the given DN. -// -// A call like -// mdnReq := NewModifyDNRequest("uid=someone,dc=example,dc=org", "uid=newname", true, "") -// will setup the request to just rename uid=someone,dc=example,dc=org to -// uid=newname,dc=example,dc=org. -func NewModifyDNRequest(dn string, rdn string, delOld bool, newSup string) *ModifyDNRequest { - return &ModifyDNRequest{ - DN: dn, - NewRDN: rdn, - DeleteOldRDN: delOld, - NewSuperior: newSup, - } -} - -// NewModifyDNWithControlsRequest creates a new request which can be passed to ModifyDN() -// and also allows setting LDAP request controls. -// -// Refer NewModifyDNRequest for other parameters -func NewModifyDNWithControlsRequest(dn string, rdn string, delOld bool, - newSup string, controls []Control) *ModifyDNRequest { - return &ModifyDNRequest{ - DN: dn, - NewRDN: rdn, - DeleteOldRDN: delOld, - NewSuperior: newSup, - Controls: controls, - } -} - -func (req *ModifyDNRequest) appendTo(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationModifyDNRequest, nil, "Modify DN Request") - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.DN, "DN")) - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.NewRDN, "New RDN")) - if req.DeleteOldRDN { - buf := []byte{0xff} - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, string(buf), "Delete old RDN")) - } else { - pkt.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, req.DeleteOldRDN, "Delete old RDN")) - } - if req.NewSuperior != "" { - pkt.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, req.NewSuperior, "New Superior")) - } - - envelope.AppendChild(pkt) - if len(req.Controls) > 0 { - envelope.AppendChild(encodeControls(req.Controls)) - } - - return nil -} - -// ModifyDN renames the given DN and optionally move to another base (when the "newSup" argument -// to NewModifyDNRequest() is not ""). -func (l *Conn) ModifyDN(m *ModifyDNRequest) error { - msgCtx, err := l.doRequest(m) - if err != nil { - return err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return err - } - - if packet.Children[1].Tag == ApplicationModifyDNResponse { - err := GetLDAPError(packet) - if err != nil { - return err - } - } else { - log.Printf("Unexpected Response: %d", packet.Children[1].Tag) - } - return nil -} diff --git a/vendor/github.com/go-ldap/ldap/v3/modify.go b/vendor/github.com/go-ldap/ldap/v3/modify.go deleted file mode 100644 index 1821413de9..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/modify.go +++ /dev/null @@ -1,177 +0,0 @@ -package ldap - -import ( - "errors" - "log" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// Change operation choices -const ( - AddAttribute = 0 - DeleteAttribute = 1 - ReplaceAttribute = 2 - IncrementAttribute = 3 // (https://tools.ietf.org/html/rfc4525) -) - -// PartialAttribute for a ModifyRequest as defined in https://tools.ietf.org/html/rfc4511 -type PartialAttribute struct { - // Type is the type of the partial attribute - Type string - // Vals are the values of the partial attribute - Vals []string -} - -func (p *PartialAttribute) encode() *ber.Packet { - seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "PartialAttribute") - seq.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, p.Type, "Type")) - set := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSet, nil, "AttributeValue") - for _, value := range p.Vals { - set.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, value, "Vals")) - } - seq.AppendChild(set) - return seq -} - -// Change for a ModifyRequest as defined in https://tools.ietf.org/html/rfc4511 -type Change struct { - // Operation is the type of change to be made - Operation uint - // Modification is the attribute to be modified - Modification PartialAttribute -} - -func (c *Change) encode() *ber.Packet { - change := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Change") - change.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagEnumerated, uint64(c.Operation), "Operation")) - change.AppendChild(c.Modification.encode()) - return change -} - -// ModifyRequest as defined in https://tools.ietf.org/html/rfc4511 -type ModifyRequest struct { - // DN is the distinguishedName of the directory entry to modify - DN string - // Changes contain the attributes to modify - Changes []Change - // Controls hold optional controls to send with the request - Controls []Control -} - -// Add appends the given attribute to the list of changes to be made -func (req *ModifyRequest) Add(attrType string, attrVals []string) { - req.appendChange(AddAttribute, attrType, attrVals) -} - -// Delete appends the given attribute to the list of changes to be made -func (req *ModifyRequest) Delete(attrType string, attrVals []string) { - req.appendChange(DeleteAttribute, attrType, attrVals) -} - -// Replace appends the given attribute to the list of changes to be made -func (req *ModifyRequest) Replace(attrType string, attrVals []string) { - req.appendChange(ReplaceAttribute, attrType, attrVals) -} - -// Increment appends the given attribute to the list of changes to be made -func (req *ModifyRequest) Increment(attrType string, attrVal string) { - req.appendChange(IncrementAttribute, attrType, []string{attrVal}) -} - -func (req *ModifyRequest) appendChange(operation uint, attrType string, attrVals []string) { - req.Changes = append(req.Changes, Change{operation, PartialAttribute{Type: attrType, Vals: attrVals}}) -} - -func (req *ModifyRequest) appendTo(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationModifyRequest, nil, "Modify Request") - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.DN, "DN")) - changes := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Changes") - for _, change := range req.Changes { - changes.AppendChild(change.encode()) - } - pkt.AppendChild(changes) - - envelope.AppendChild(pkt) - if len(req.Controls) > 0 { - envelope.AppendChild(encodeControls(req.Controls)) - } - - return nil -} - -// NewModifyRequest creates a modify request for the given DN -func NewModifyRequest(dn string, controls []Control) *ModifyRequest { - return &ModifyRequest{ - DN: dn, - Controls: controls, - } -} - -// Modify performs the ModifyRequest -func (l *Conn) Modify(modifyRequest *ModifyRequest) error { - msgCtx, err := l.doRequest(modifyRequest) - if err != nil { - return err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return err - } - - if packet.Children[1].Tag == ApplicationModifyResponse { - err := GetLDAPError(packet) - if err != nil { - return err - } - } else { - log.Printf("Unexpected Response: %d", packet.Children[1].Tag) - } - return nil -} - -// ModifyResult holds the server's response to a modify request -type ModifyResult struct { - // Controls are the returned controls - Controls []Control -} - -// ModifyWithResult performs the ModifyRequest and returns the result -func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, error) { - msgCtx, err := l.doRequest(modifyRequest) - if err != nil { - return nil, err - } - defer l.finishMessage(msgCtx) - - result := &ModifyResult{ - Controls: make([]Control, 0), - } - - l.Debug.Printf("%d: waiting for response", msgCtx.id) - packet, err := l.readPacket(msgCtx) - if err != nil { - return nil, err - } - - switch packet.Children[1].Tag { - case ApplicationModifyResponse: - err := GetLDAPError(packet) - if err != nil { - return nil, err - } - if len(packet.Children) == 3 { - for _, child := range packet.Children[2].Children { - decodedChild, err := DecodeControl(child) - if err != nil { - return nil, errors.New("failed to decode child control: " + err.Error()) - } - result.Controls = append(result.Controls, decodedChild) - } - } - } - l.Debug.Printf("%d: returning", msgCtx.id) - return result, nil -} diff --git a/vendor/github.com/go-ldap/ldap/v3/passwdmodify.go b/vendor/github.com/go-ldap/ldap/v3/passwdmodify.go deleted file mode 100644 index 62a110843d..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/passwdmodify.go +++ /dev/null @@ -1,126 +0,0 @@ -package ldap - -import ( - "fmt" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -const ( - passwordModifyOID = "1.3.6.1.4.1.4203.1.11.1" -) - -// PasswordModifyRequest implements the Password Modify Extended Operation as defined in https://www.ietf.org/rfc/rfc3062.txt -type PasswordModifyRequest struct { - // UserIdentity is an optional string representation of the user associated with the request. - // This string may or may not be an LDAPDN [RFC2253]. - // If no UserIdentity field is present, the request acts up upon the password of the user currently associated with the LDAP session - UserIdentity string - // OldPassword, if present, contains the user's current password - OldPassword string - // NewPassword, if present, contains the desired password for this user - NewPassword string -} - -// PasswordModifyResult holds the server response to a PasswordModifyRequest -type PasswordModifyResult struct { - // GeneratedPassword holds a password generated by the server, if present - GeneratedPassword string - // Referral are the returned referral - Referral string -} - -func (req *PasswordModifyRequest) appendTo(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationExtendedRequest, nil, "Password Modify Extended Operation") - pkt.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, passwordModifyOID, "Extended Request Name: Password Modify OID")) - - extendedRequestValue := ber.Encode(ber.ClassContext, ber.TypePrimitive, 1, nil, "Extended Request Value: Password Modify Request") - passwordModifyRequestValue := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Password Modify Request") - if req.UserIdentity != "" { - passwordModifyRequestValue.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, req.UserIdentity, "User Identity")) - } - if req.OldPassword != "" { - passwordModifyRequestValue.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 1, req.OldPassword, "Old Password")) - } - if req.NewPassword != "" { - passwordModifyRequestValue.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 2, req.NewPassword, "New Password")) - } - extendedRequestValue.AppendChild(passwordModifyRequestValue) - - pkt.AppendChild(extendedRequestValue) - - envelope.AppendChild(pkt) - - return nil -} - -// NewPasswordModifyRequest creates a new PasswordModifyRequest -// -// According to the RFC 3602 (https://tools.ietf.org/html/rfc3062): -// userIdentity is a string representing the user associated with the request. -// This string may or may not be an LDAPDN (RFC 2253). -// If userIdentity is empty then the operation will act on the user associated -// with the session. -// -// oldPassword is the current user's password, it can be empty or it can be -// needed depending on the session user access rights (usually an administrator -// can change a user's password without knowing the current one) and the -// password policy (see pwdSafeModify password policy's attribute) -// -// newPassword is the desired user's password. If empty the server can return -// an error or generate a new password that will be available in the -// PasswordModifyResult.GeneratedPassword -// -func NewPasswordModifyRequest(userIdentity string, oldPassword string, newPassword string) *PasswordModifyRequest { - return &PasswordModifyRequest{ - UserIdentity: userIdentity, - OldPassword: oldPassword, - NewPassword: newPassword, - } -} - -// PasswordModify performs the modification request -func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*PasswordModifyResult, error) { - msgCtx, err := l.doRequest(passwordModifyRequest) - if err != nil { - return nil, err - } - defer l.finishMessage(msgCtx) - - packet, err := l.readPacket(msgCtx) - if err != nil { - return nil, err - } - - result := &PasswordModifyResult{} - - if packet.Children[1].Tag == ApplicationExtendedResponse { - err := GetLDAPError(packet) - if err != nil { - if IsErrorWithCode(err, LDAPResultReferral) { - for _, child := range packet.Children[1].Children { - if child.Tag == 3 { - result.Referral = child.Children[0].Value.(string) - } - } - } - return result, err - } - } else { - return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag)) - } - - extendedResponse := packet.Children[1] - for _, child := range extendedResponse.Children { - if child.Tag == 11 { - passwordModifyResponseValue := ber.DecodePacket(child.Data.Bytes()) - if len(passwordModifyResponseValue.Children) == 1 { - if passwordModifyResponseValue.Children[0].Tag == 0 { - result.GeneratedPassword = ber.DecodeString(passwordModifyResponseValue.Children[0].Data.Bytes()) - } - } - } - } - - return result, nil -} diff --git a/vendor/github.com/go-ldap/ldap/v3/request.go b/vendor/github.com/go-ldap/ldap/v3/request.go deleted file mode 100644 index 4ea31e9040..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/request.go +++ /dev/null @@ -1,71 +0,0 @@ -package ldap - -import ( - "errors" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -var ( - errRespChanClosed = errors.New("ldap: response channel closed") - errCouldNotRetMsg = errors.New("ldap: could not retrieve message") - ErrNilConnection = errors.New("ldap: conn is nil, expected net.Conn") -) - -type request interface { - appendTo(*ber.Packet) error -} - -type requestFunc func(*ber.Packet) error - -func (f requestFunc) appendTo(p *ber.Packet) error { - return f(p) -} - -func (l *Conn) doRequest(req request) (*messageContext, error) { - if l == nil || l.conn == nil { - return nil, ErrNilConnection - } - - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") - packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) - if err := req.appendTo(packet); err != nil { - return nil, err - } - - if l.Debug { - l.Debug.PrintPacket(packet) - } - - msgCtx, err := l.sendMessage(packet) - if err != nil { - return nil, err - } - l.Debug.Printf("%d: returning", msgCtx.id) - return msgCtx, nil -} - -func (l *Conn) readPacket(msgCtx *messageContext) (*ber.Packet, error) { - l.Debug.Printf("%d: waiting for response", msgCtx.id) - packetResponse, ok := <-msgCtx.responses - if !ok { - return nil, NewError(ErrorNetwork, errRespChanClosed) - } - packet, err := packetResponse.ReadPacket() - l.Debug.Printf("%d: got response %p", msgCtx.id, packet) - if err != nil { - return nil, err - } - - if packet == nil { - return nil, NewError(ErrorNetwork, errCouldNotRetMsg) - } - - if l.Debug { - if err = addLDAPDescriptions(packet); err != nil { - return nil, err - } - l.Debug.PrintPacket(packet) - } - return packet, nil -} diff --git a/vendor/github.com/go-ldap/ldap/v3/search.go b/vendor/github.com/go-ldap/ldap/v3/search.go deleted file mode 100644 index 915e420384..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/search.go +++ /dev/null @@ -1,427 +0,0 @@ -package ldap - -import ( - "errors" - "fmt" - "sort" - "strings" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -// scope choices -const ( - ScopeBaseObject = 0 - ScopeSingleLevel = 1 - ScopeWholeSubtree = 2 -) - -// ScopeMap contains human readable descriptions of scope choices -var ScopeMap = map[int]string{ - ScopeBaseObject: "Base Object", - ScopeSingleLevel: "Single Level", - ScopeWholeSubtree: "Whole Subtree", -} - -// derefAliases -const ( - NeverDerefAliases = 0 - DerefInSearching = 1 - DerefFindingBaseObj = 2 - DerefAlways = 3 -) - -// DerefMap contains human readable descriptions of derefAliases choices -var DerefMap = map[int]string{ - NeverDerefAliases: "NeverDerefAliases", - DerefInSearching: "DerefInSearching", - DerefFindingBaseObj: "DerefFindingBaseObj", - DerefAlways: "DerefAlways", -} - -// NewEntry returns an Entry object with the specified distinguished name and attribute key-value pairs. -// The map of attributes is accessed in alphabetical order of the keys in order to ensure that, for the -// same input map of attributes, the output entry will contain the same order of attributes -func NewEntry(dn string, attributes map[string][]string) *Entry { - var attributeNames []string - for attributeName := range attributes { - attributeNames = append(attributeNames, attributeName) - } - sort.Strings(attributeNames) - - var encodedAttributes []*EntryAttribute - for _, attributeName := range attributeNames { - encodedAttributes = append(encodedAttributes, NewEntryAttribute(attributeName, attributes[attributeName])) - } - return &Entry{ - DN: dn, - Attributes: encodedAttributes, - } -} - -// Entry represents a single search result entry -type Entry struct { - // DN is the distinguished name of the entry - DN string - // Attributes are the returned attributes for the entry - Attributes []*EntryAttribute -} - -// GetAttributeValues returns the values for the named attribute, or an empty list -func (e *Entry) GetAttributeValues(attribute string) []string { - for _, attr := range e.Attributes { - if attr.Name == attribute { - return attr.Values - } - } - return []string{} -} - -// GetEqualFoldAttributeValues returns the values for the named attribute, or an -// empty list. Attribute matching is done with strings.EqualFold. -func (e *Entry) GetEqualFoldAttributeValues(attribute string) []string { - for _, attr := range e.Attributes { - if strings.EqualFold(attribute, attr.Name) { - return attr.Values - } - } - return []string{} -} - -// GetRawAttributeValues returns the byte values for the named attribute, or an empty list -func (e *Entry) GetRawAttributeValues(attribute string) [][]byte { - for _, attr := range e.Attributes { - if attr.Name == attribute { - return attr.ByteValues - } - } - return [][]byte{} -} - -// GetEqualFoldRawAttributeValues returns the byte values for the named attribute, or an empty list -func (e *Entry) GetEqualFoldRawAttributeValues(attribute string) [][]byte { - for _, attr := range e.Attributes { - if strings.EqualFold(attr.Name, attribute) { - return attr.ByteValues - } - } - return [][]byte{} -} - -// GetAttributeValue returns the first value for the named attribute, or "" -func (e *Entry) GetAttributeValue(attribute string) string { - values := e.GetAttributeValues(attribute) - if len(values) == 0 { - return "" - } - return values[0] -} - -// GetEqualFoldAttributeValue returns the first value for the named attribute, or "". -// Attribute comparison is done with strings.EqualFold. -func (e *Entry) GetEqualFoldAttributeValue(attribute string) string { - values := e.GetEqualFoldAttributeValues(attribute) - if len(values) == 0 { - return "" - } - return values[0] -} - -// GetRawAttributeValue returns the first value for the named attribute, or an empty slice -func (e *Entry) GetRawAttributeValue(attribute string) []byte { - values := e.GetRawAttributeValues(attribute) - if len(values) == 0 { - return []byte{} - } - return values[0] -} - -// GetEqualFoldRawAttributeValue returns the first value for the named attribute, or an empty slice -func (e *Entry) GetEqualFoldRawAttributeValue(attribute string) []byte { - values := e.GetEqualFoldRawAttributeValues(attribute) - if len(values) == 0 { - return []byte{} - } - return values[0] -} - -// Print outputs a human-readable description -func (e *Entry) Print() { - fmt.Printf("DN: %s\n", e.DN) - for _, attr := range e.Attributes { - attr.Print() - } -} - -// PrettyPrint outputs a human-readable description indenting -func (e *Entry) PrettyPrint(indent int) { - fmt.Printf("%sDN: %s\n", strings.Repeat(" ", indent), e.DN) - for _, attr := range e.Attributes { - attr.PrettyPrint(indent + 2) - } -} - -// NewEntryAttribute returns a new EntryAttribute with the desired key-value pair -func NewEntryAttribute(name string, values []string) *EntryAttribute { - var bytes [][]byte - for _, value := range values { - bytes = append(bytes, []byte(value)) - } - return &EntryAttribute{ - Name: name, - Values: values, - ByteValues: bytes, - } -} - -// EntryAttribute holds a single attribute -type EntryAttribute struct { - // Name is the name of the attribute - Name string - // Values contain the string values of the attribute - Values []string - // ByteValues contain the raw values of the attribute - ByteValues [][]byte -} - -// Print outputs a human-readable description -func (e *EntryAttribute) Print() { - fmt.Printf("%s: %s\n", e.Name, e.Values) -} - -// PrettyPrint outputs a human-readable description with indenting -func (e *EntryAttribute) PrettyPrint(indent int) { - fmt.Printf("%s%s: %s\n", strings.Repeat(" ", indent), e.Name, e.Values) -} - -// SearchResult holds the server's response to a search request -type SearchResult struct { - // Entries are the returned entries - Entries []*Entry - // Referrals are the returned referrals - Referrals []string - // Controls are the returned controls - Controls []Control -} - -// Print outputs a human-readable description -func (s *SearchResult) Print() { - for _, entry := range s.Entries { - entry.Print() - } -} - -// PrettyPrint outputs a human-readable description with indenting -func (s *SearchResult) PrettyPrint(indent int) { - for _, entry := range s.Entries { - entry.PrettyPrint(indent) - } -} - -// SearchRequest represents a search request to send to the server -type SearchRequest struct { - BaseDN string - Scope int - DerefAliases int - SizeLimit int - TimeLimit int - TypesOnly bool - Filter string - Attributes []string - Controls []Control -} - -func (req *SearchRequest) appendTo(envelope *ber.Packet) error { - pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationSearchRequest, nil, "Search Request") - pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.BaseDN, "Base DN")) - pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagEnumerated, uint64(req.Scope), "Scope")) - pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagEnumerated, uint64(req.DerefAliases), "Deref Aliases")) - pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, uint64(req.SizeLimit), "Size Limit")) - pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, uint64(req.TimeLimit), "Time Limit")) - pkt.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, req.TypesOnly, "Types Only")) - // compile and encode filter - filterPacket, err := CompileFilter(req.Filter) - if err != nil { - return err - } - pkt.AppendChild(filterPacket) - // encode attributes - attributesPacket := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Attributes") - for _, attribute := range req.Attributes { - attributesPacket.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, attribute, "Attribute")) - } - pkt.AppendChild(attributesPacket) - - envelope.AppendChild(pkt) - if len(req.Controls) > 0 { - envelope.AppendChild(encodeControls(req.Controls)) - } - - return nil -} - -// NewSearchRequest creates a new search request -func NewSearchRequest( - BaseDN string, - Scope, DerefAliases, SizeLimit, TimeLimit int, - TypesOnly bool, - Filter string, - Attributes []string, - Controls []Control, -) *SearchRequest { - return &SearchRequest{ - BaseDN: BaseDN, - Scope: Scope, - DerefAliases: DerefAliases, - SizeLimit: SizeLimit, - TimeLimit: TimeLimit, - TypesOnly: TypesOnly, - Filter: Filter, - Attributes: Attributes, - Controls: Controls, - } -} - -// SearchWithPaging accepts a search request and desired page size in order to execute LDAP queries to fulfill the -// search request. All paged LDAP query responses will be buffered and the final result will be returned atomically. -// The following four cases are possible given the arguments: -// - given SearchRequest missing a control of type ControlTypePaging: we will add one with the desired paging size -// - given SearchRequest contains a control of type ControlTypePaging that isn't actually a ControlPaging: fail without issuing any queries -// - given SearchRequest contains a control of type ControlTypePaging with pagingSize equal to the size requested: no change to the search request -// - given SearchRequest contains a control of type ControlTypePaging with pagingSize not equal to the size requested: fail without issuing any queries -// A requested pagingSize of 0 is interpreted as no limit by LDAP servers. -func (l *Conn) SearchWithPaging(searchRequest *SearchRequest, pagingSize uint32) (*SearchResult, error) { - var pagingControl *ControlPaging - - control := FindControl(searchRequest.Controls, ControlTypePaging) - if control == nil { - pagingControl = NewControlPaging(pagingSize) - searchRequest.Controls = append(searchRequest.Controls, pagingControl) - } else { - castControl, ok := control.(*ControlPaging) - if !ok { - return nil, fmt.Errorf("expected paging control to be of type *ControlPaging, got %v", control) - } - if castControl.PagingSize != pagingSize { - return nil, fmt.Errorf("paging size given in search request (%d) conflicts with size given in search call (%d)", castControl.PagingSize, pagingSize) - } - pagingControl = castControl - } - - searchResult := new(SearchResult) - for { - result, err := l.Search(searchRequest) - l.Debug.Printf("Looking for Paging Control...") - if err != nil { - return searchResult, err - } - if result == nil { - return searchResult, NewError(ErrorNetwork, errors.New("ldap: packet not received")) - } - - for _, entry := range result.Entries { - searchResult.Entries = append(searchResult.Entries, entry) - } - for _, referral := range result.Referrals { - searchResult.Referrals = append(searchResult.Referrals, referral) - } - for _, control := range result.Controls { - searchResult.Controls = append(searchResult.Controls, control) - } - - l.Debug.Printf("Looking for Paging Control...") - pagingResult := FindControl(result.Controls, ControlTypePaging) - if pagingResult == nil { - pagingControl = nil - l.Debug.Printf("Could not find paging control. Breaking...") - break - } - - cookie := pagingResult.(*ControlPaging).Cookie - if len(cookie) == 0 { - pagingControl = nil - l.Debug.Printf("Could not find cookie. Breaking...") - break - } - pagingControl.SetCookie(cookie) - } - - if pagingControl != nil { - l.Debug.Printf("Abandoning Paging...") - pagingControl.PagingSize = 0 - l.Search(searchRequest) - } - - return searchResult, nil -} - -// Search performs the given search request -func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) { - msgCtx, err := l.doRequest(searchRequest) - if err != nil { - return nil, err - } - defer l.finishMessage(msgCtx) - - result := &SearchResult{ - Entries: make([]*Entry, 0), - Referrals: make([]string, 0), - Controls: make([]Control, 0)} - - for { - packet, err := l.readPacket(msgCtx) - if err != nil { - return result, err - } - - switch packet.Children[1].Tag { - case 4: - entry := &Entry{ - DN: packet.Children[1].Children[0].Value.(string), - Attributes: unpackAttributes(packet.Children[1].Children[1].Children), - } - result.Entries = append(result.Entries, entry) - case 5: - err := GetLDAPError(packet) - if err != nil { - return result, err - } - if len(packet.Children) == 3 { - for _, child := range packet.Children[2].Children { - decodedChild, err := DecodeControl(child) - if err != nil { - return result, fmt.Errorf("failed to decode child control: %s", err) - } - result.Controls = append(result.Controls, decodedChild) - } - } - return result, nil - case 19: - result.Referrals = append(result.Referrals, packet.Children[1].Children[0].Value.(string)) - } - } -} - -// unpackAttributes will extract all given LDAP attributes and it's values -// from the ber.Packet -func unpackAttributes(children []*ber.Packet) []*EntryAttribute { - entries := make([]*EntryAttribute, len(children)) - for i, child := range children { - length := len(child.Children[1].Children) - entry := &EntryAttribute{ - Name: child.Children[0].Value.(string), - // pre-allocate the slice since we can determine - // the number of attributes at this point - Values: make([]string, length), - ByteValues: make([][]byte, length), - } - - for i, value := range child.Children[1].Children { - entry.ByteValues[i] = value.ByteValue - entry.Values[i] = value.Value.(string) - } - entries[i] = entry - } - - return entries -} diff --git a/vendor/github.com/go-ldap/ldap/v3/unbind.go b/vendor/github.com/go-ldap/ldap/v3/unbind.go deleted file mode 100644 index 6c411cd1d3..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/unbind.go +++ /dev/null @@ -1,37 +0,0 @@ -package ldap - -import ( - "errors" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -var ErrConnUnbound = NewError(ErrorNetwork, errors.New("ldap: connection is closed")) - -type unbindRequest struct{} - -func (unbindRequest) appendTo(envelope *ber.Packet) error { - envelope.AppendChild(ber.Encode(ber.ClassApplication, ber.TypePrimitive, ApplicationUnbindRequest, nil, ApplicationMap[ApplicationUnbindRequest])) - return nil -} - -// Unbind will perform an unbind request. The Unbind operation -// should be thought of as the "quit" operation. -// See https://datatracker.ietf.org/doc/html/rfc4511#section-4.3 -func (l *Conn) Unbind() error { - if l.IsClosing() { - return ErrConnUnbound - } - - _, err := l.doRequest(unbindRequest{}) - if err != nil { - return err - } - - // Sending an unbindRequest will make the connection unusable. - // Pending requests will fail with: - // LDAP Result Code 200 "Network Error": ldap: response channel closed - l.Close() - - return nil -} diff --git a/vendor/github.com/go-ldap/ldap/v3/whoami.go b/vendor/github.com/go-ldap/ldap/v3/whoami.go deleted file mode 100644 index 10c523d082..0000000000 --- a/vendor/github.com/go-ldap/ldap/v3/whoami.go +++ /dev/null @@ -1,91 +0,0 @@ -package ldap - -// This file contains the "Who Am I?" extended operation as specified in rfc 4532 -// -// https://tools.ietf.org/html/rfc4532 - -import ( - "errors" - "fmt" - - ber "github.com/go-asn1-ber/asn1-ber" -) - -type whoAmIRequest bool - -// WhoAmIResult is returned by the WhoAmI() call -type WhoAmIResult struct { - AuthzID string -} - -func (r whoAmIRequest) encode() (*ber.Packet, error) { - request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationExtendedRequest, nil, "Who Am I? Extended Operation") - request.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, ControlTypeWhoAmI, "Extended Request Name: Who Am I? OID")) - return request, nil -} - -// WhoAmI returns the authzId the server thinks we are, you may pass controls -// like a Proxied Authorization control -func (l *Conn) WhoAmI(controls []Control) (*WhoAmIResult, error) { - packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") - packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) - req := whoAmIRequest(true) - encodedWhoAmIRequest, err := req.encode() - if err != nil { - return nil, err - } - packet.AppendChild(encodedWhoAmIRequest) - - if len(controls) != 0 { - packet.AppendChild(encodeControls(controls)) - } - - l.Debug.PrintPacket(packet) - - msgCtx, err := l.sendMessage(packet) - if err != nil { - return nil, err - } - defer l.finishMessage(msgCtx) - - result := &WhoAmIResult{} - - l.Debug.Printf("%d: waiting for response", msgCtx.id) - packetResponse, ok := <-msgCtx.responses - if !ok { - return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed")) - } - packet, err = packetResponse.ReadPacket() - l.Debug.Printf("%d: got response %p", msgCtx.id, packet) - if err != nil { - return nil, err - } - - if packet == nil { - return nil, NewError(ErrorNetwork, errors.New("ldap: could not retrieve message")) - } - - if l.Debug { - if err := addLDAPDescriptions(packet); err != nil { - return nil, err - } - ber.PrintPacket(packet) - } - - if packet.Children[1].Tag == ApplicationExtendedResponse { - if err := GetLDAPError(packet); err != nil { - return nil, err - } - } else { - return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("Unexpected Response: %d", packet.Children[1].Tag)) - } - - extendedResponse := packet.Children[1] - for _, child := range extendedResponse.Children { - if child.Tag == 11 { - result.AuthzID = ber.DecodeString(child.Data.Bytes()) - } - } - - return result, nil -} diff --git a/vendor/github.com/go-openapi/errors/.gitattributes b/vendor/github.com/go-openapi/errors/.gitattributes new file mode 100644 index 0000000000..a0717e4b3b --- /dev/null +++ b/vendor/github.com/go-openapi/errors/.gitattributes @@ -0,0 +1 @@ +*.go text eol=lf \ No newline at end of file diff --git a/vendor/github.com/go-openapi/errors/.gitignore b/vendor/github.com/go-openapi/errors/.gitignore new file mode 100644 index 0000000000..dd91ed6a04 --- /dev/null +++ b/vendor/github.com/go-openapi/errors/.gitignore @@ -0,0 +1,2 @@ +secrets.yml +coverage.out diff --git a/vendor/github.com/go-openapi/errors/.golangci.yml b/vendor/github.com/go-openapi/errors/.golangci.yml new file mode 100644 index 0000000000..4e1fc0c7d4 --- /dev/null +++ b/vendor/github.com/go-openapi/errors/.golangci.yml @@ -0,0 +1,48 @@ +linters-settings: + govet: + check-shadowing: true + golint: + min-confidence: 0 + gocyclo: + min-complexity: 30 + maligned: + suggest-new: true + dupl: + threshold: 100 + goconst: + min-len: 2 + min-occurrences: 4 +linters: + enable-all: true + disable: + - maligned + - lll + - gochecknoglobals + - godox + - gocognit + - whitespace + - wsl + - funlen + - gochecknoglobals + - gochecknoinits + - scopelint + - wrapcheck + - exhaustivestruct + - exhaustive + - nlreturn + - testpackage + - gci + - gofumpt + - goerr113 + - gomnd + - tparallel + - nestif + - godot + - errorlint + - paralleltest + - tparallel + - cyclop + - errname + - varnamelen + - exhaustruct + - maintidx diff --git a/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..9322b065e3 --- /dev/null +++ b/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at ivan+abuse@flanders.co.nz. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/errors/LICENSE b/vendor/github.com/go-openapi/errors/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/vendor/github.com/go-openapi/errors/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-openapi/errors/README.md b/vendor/github.com/go-openapi/errors/README.md new file mode 100644 index 0000000000..4aac049e60 --- /dev/null +++ b/vendor/github.com/go-openapi/errors/README.md @@ -0,0 +1,11 @@ +# OpenAPI errors + +[![Build Status](https://travis-ci.org/go-openapi/errors.svg?branch=master)](https://travis-ci.org/go-openapi/errors) +[![codecov](https://codecov.io/gh/go-openapi/errors/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/errors) +[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) +[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/errors/master/LICENSE) +[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/errors.svg)](https://pkg.go.dev/github.com/go-openapi/errors) +[![GolangCI](https://golangci.com/badges/github.com/go-openapi/errors.svg)](https://golangci.com) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/errors)](https://goreportcard.com/report/github.com/go-openapi/errors) + +Shared errors and error interface used throughout the various libraries found in the go-openapi toolkit. diff --git a/vendor/github.com/go-openapi/errors/api.go b/vendor/github.com/go-openapi/errors/api.go new file mode 100644 index 0000000000..77f1f92c5e --- /dev/null +++ b/vendor/github.com/go-openapi/errors/api.go @@ -0,0 +1,182 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package errors + +import ( + "encoding/json" + "fmt" + "net/http" + "reflect" + "strings" +) + +// DefaultHTTPCode is used when the error Code cannot be used as an HTTP code. +var DefaultHTTPCode = http.StatusUnprocessableEntity + +// Error represents a error interface all swagger framework errors implement +type Error interface { + error + Code() int32 +} + +type apiError struct { + code int32 + message string +} + +func (a *apiError) Error() string { + return a.message +} + +func (a *apiError) Code() int32 { + return a.code +} + +// MarshalJSON implements the JSON encoding interface +func (a apiError) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]interface{}{ + "code": a.code, + "message": a.message, + }) +} + +// New creates a new API error with a code and a message +func New(code int32, message string, args ...interface{}) Error { + if len(args) > 0 { + return &apiError{code, fmt.Sprintf(message, args...)} + } + return &apiError{code, message} +} + +// NotFound creates a new not found error +func NotFound(message string, args ...interface{}) Error { + if message == "" { + message = "Not found" + } + return New(http.StatusNotFound, fmt.Sprintf(message, args...)) +} + +// NotImplemented creates a new not implemented error +func NotImplemented(message string) Error { + return New(http.StatusNotImplemented, message) +} + +// MethodNotAllowedError represents an error for when the path matches but the method doesn't +type MethodNotAllowedError struct { + code int32 + Allowed []string + message string +} + +func (m *MethodNotAllowedError) Error() string { + return m.message +} + +// Code the error code +func (m *MethodNotAllowedError) Code() int32 { + return m.code +} + +// MarshalJSON implements the JSON encoding interface +func (m MethodNotAllowedError) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]interface{}{ + "code": m.code, + "message": m.message, + "allowed": m.Allowed, + }) +} + +func errorAsJSON(err Error) []byte { + //nolint:errchkjson + b, _ := json.Marshal(struct { + Code int32 `json:"code"` + Message string `json:"message"` + }{err.Code(), err.Error()}) + return b +} + +func flattenComposite(errs *CompositeError) *CompositeError { + var res []error + for _, er := range errs.Errors { + switch e := er.(type) { + case *CompositeError: + if len(e.Errors) > 0 { + flat := flattenComposite(e) + if len(flat.Errors) > 0 { + res = append(res, flat.Errors...) + } + } + default: + if e != nil { + res = append(res, e) + } + } + } + return CompositeValidationError(res...) +} + +// MethodNotAllowed creates a new method not allowed error +func MethodNotAllowed(requested string, allow []string) Error { + msg := fmt.Sprintf("method %s is not allowed, but [%s] are", requested, strings.Join(allow, ",")) + return &MethodNotAllowedError{code: http.StatusMethodNotAllowed, Allowed: allow, message: msg} +} + +// ServeError the error handler interface implementation +func ServeError(rw http.ResponseWriter, r *http.Request, err error) { + rw.Header().Set("Content-Type", "application/json") + switch e := err.(type) { + case *CompositeError: + er := flattenComposite(e) + // strips composite errors to first element only + if len(er.Errors) > 0 { + ServeError(rw, r, er.Errors[0]) + } else { + // guard against empty CompositeError (invalid construct) + ServeError(rw, r, nil) + } + case *MethodNotAllowedError: + rw.Header().Add("Allow", strings.Join(e.Allowed, ",")) + rw.WriteHeader(asHTTPCode(int(e.Code()))) + if r == nil || r.Method != http.MethodHead { + _, _ = rw.Write(errorAsJSON(e)) + } + case Error: + value := reflect.ValueOf(e) + if value.Kind() == reflect.Ptr && value.IsNil() { + rw.WriteHeader(http.StatusInternalServerError) + _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error"))) + return + } + rw.WriteHeader(asHTTPCode(int(e.Code()))) + if r == nil || r.Method != http.MethodHead { + _, _ = rw.Write(errorAsJSON(e)) + } + case nil: + rw.WriteHeader(http.StatusInternalServerError) + _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error"))) + default: + rw.WriteHeader(http.StatusInternalServerError) + if r == nil || r.Method != http.MethodHead { + _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, err.Error()))) + } + } +} + +func asHTTPCode(input int) int { + if input >= 600 { + return DefaultHTTPCode + } + return input +} diff --git a/vendor/github.com/go-openapi/errors/auth.go b/vendor/github.com/go-openapi/errors/auth.go new file mode 100644 index 0000000000..0545b501bd --- /dev/null +++ b/vendor/github.com/go-openapi/errors/auth.go @@ -0,0 +1,22 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package errors + +import "net/http" + +// Unauthenticated returns an unauthenticated error +func Unauthenticated(scheme string) Error { + return New(http.StatusUnauthorized, "unauthenticated for %s", scheme) +} diff --git a/vendor/github.com/go-openapi/errors/doc.go b/vendor/github.com/go-openapi/errors/doc.go new file mode 100644 index 0000000000..af01190ce6 --- /dev/null +++ b/vendor/github.com/go-openapi/errors/doc.go @@ -0,0 +1,26 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* +Package errors provides an Error interface and several concrete types +implementing this interface to manage API errors and JSON-schema validation +errors. + +A middleware handler ServeError() is provided to serve the errors types +it defines. + +It is used throughout the various go-openapi toolkit libraries +(https://github.com/go-openapi). +*/ +package errors diff --git a/vendor/github.com/go-openapi/errors/headers.go b/vendor/github.com/go-openapi/errors/headers.go new file mode 100644 index 0000000000..dfebe8f95f --- /dev/null +++ b/vendor/github.com/go-openapi/errors/headers.go @@ -0,0 +1,103 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package errors + +import ( + "encoding/json" + "fmt" + "net/http" +) + +// Validation represents a failure of a precondition +type Validation struct { + code int32 + Name string + In string + Value interface{} + message string + Values []interface{} +} + +func (e *Validation) Error() string { + return e.message +} + +// Code the error code +func (e *Validation) Code() int32 { + return e.code +} + +// MarshalJSON implements the JSON encoding interface +func (e Validation) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]interface{}{ + "code": e.code, + "message": e.message, + "in": e.In, + "name": e.Name, + "value": e.Value, + "values": e.Values, + }) +} + +// ValidateName sets the name for a validation or updates it for a nested property +func (e *Validation) ValidateName(name string) *Validation { + if name != "" { + if e.Name == "" { + e.Name = name + e.message = name + e.message + } else { + e.Name = name + "." + e.Name + e.message = name + "." + e.message + } + } + return e +} + +const ( + contentTypeFail = `unsupported media type %q, only %v are allowed` + responseFormatFail = `unsupported media type requested, only %v are available` +) + +// InvalidContentType error for an invalid content type +func InvalidContentType(value string, allowed []string) *Validation { + values := make([]interface{}, 0, len(allowed)) + for _, v := range allowed { + values = append(values, v) + } + return &Validation{ + code: http.StatusUnsupportedMediaType, + Name: "Content-Type", + In: "header", + Value: value, + Values: values, + message: fmt.Sprintf(contentTypeFail, value, allowed), + } +} + +// InvalidResponseFormat error for an unacceptable response format request +func InvalidResponseFormat(value string, allowed []string) *Validation { + values := make([]interface{}, 0, len(allowed)) + for _, v := range allowed { + values = append(values, v) + } + return &Validation{ + code: http.StatusNotAcceptable, + Name: "Accept", + In: "header", + Value: value, + Values: values, + message: fmt.Sprintf(responseFormatFail, allowed), + } +} diff --git a/vendor/github.com/go-openapi/errors/middleware.go b/vendor/github.com/go-openapi/errors/middleware.go new file mode 100644 index 0000000000..963472d1f3 --- /dev/null +++ b/vendor/github.com/go-openapi/errors/middleware.go @@ -0,0 +1,50 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package errors + +import ( + "bytes" + "fmt" + "strings" +) + +// APIVerificationFailed is an error that contains all the missing info for a mismatched section +// between the api registrations and the api spec +type APIVerificationFailed struct { + Section string `json:"section,omitempty"` + MissingSpecification []string `json:"missingSpecification,omitempty"` + MissingRegistration []string `json:"missingRegistration,omitempty"` +} + +func (v *APIVerificationFailed) Error() string { + buf := bytes.NewBuffer(nil) + + hasRegMissing := len(v.MissingRegistration) > 0 + hasSpecMissing := len(v.MissingSpecification) > 0 + + if hasRegMissing { + buf.WriteString(fmt.Sprintf("missing [%s] %s registrations", strings.Join(v.MissingRegistration, ", "), v.Section)) + } + + if hasRegMissing && hasSpecMissing { + buf.WriteString("\n") + } + + if hasSpecMissing { + buf.WriteString(fmt.Sprintf("missing from spec file [%s] %s", strings.Join(v.MissingSpecification, ", "), v.Section)) + } + + return buf.String() +} diff --git a/vendor/github.com/go-openapi/errors/parsing.go b/vendor/github.com/go-openapi/errors/parsing.go new file mode 100644 index 0000000000..5096e1ea7b --- /dev/null +++ b/vendor/github.com/go-openapi/errors/parsing.go @@ -0,0 +1,78 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package errors + +import ( + "encoding/json" + "fmt" +) + +// ParseError represents a parsing error +type ParseError struct { + code int32 + Name string + In string + Value string + Reason error + message string +} + +func (e *ParseError) Error() string { + return e.message +} + +// Code returns the http status code for this error +func (e *ParseError) Code() int32 { + return e.code +} + +// MarshalJSON implements the JSON encoding interface +func (e ParseError) MarshalJSON() ([]byte, error) { + var reason string + if e.Reason != nil { + reason = e.Reason.Error() + } + return json.Marshal(map[string]interface{}{ + "code": e.code, + "message": e.message, + "in": e.In, + "name": e.Name, + "value": e.Value, + "reason": reason, + }) +} + +const ( + parseErrorTemplContent = `parsing %s %s from %q failed, because %s` + parseErrorTemplContentNoIn = `parsing %s from %q failed, because %s` +) + +// NewParseError creates a new parse error +func NewParseError(name, in, value string, reason error) *ParseError { + var msg string + if in == "" { + msg = fmt.Sprintf(parseErrorTemplContentNoIn, name, value, reason) + } else { + msg = fmt.Sprintf(parseErrorTemplContent, name, in, value, reason) + } + return &ParseError{ + code: 400, + Name: name, + In: in, + Value: value, + Reason: reason, + message: msg, + } +} diff --git a/vendor/github.com/go-openapi/errors/schema.go b/vendor/github.com/go-openapi/errors/schema.go new file mode 100644 index 0000000000..da5f6c78cb --- /dev/null +++ b/vendor/github.com/go-openapi/errors/schema.go @@ -0,0 +1,611 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package errors + +import ( + "encoding/json" + "fmt" + "strings" +) + +const ( + invalidType = "%s is an invalid type name" + typeFail = "%s in %s must be of type %s" + typeFailWithData = "%s in %s must be of type %s: %q" + typeFailWithError = "%s in %s must be of type %s, because: %s" + requiredFail = "%s in %s is required" + readOnlyFail = "%s in %s is readOnly" + tooLongMessage = "%s in %s should be at most %d chars long" + tooShortMessage = "%s in %s should be at least %d chars long" + patternFail = "%s in %s should match '%s'" + enumFail = "%s in %s should be one of %v" + multipleOfFail = "%s in %s should be a multiple of %v" + maxIncFail = "%s in %s should be less than or equal to %v" + maxExcFail = "%s in %s should be less than %v" + minIncFail = "%s in %s should be greater than or equal to %v" + minExcFail = "%s in %s should be greater than %v" + uniqueFail = "%s in %s shouldn't contain duplicates" + maxItemsFail = "%s in %s should have at most %d items" + minItemsFail = "%s in %s should have at least %d items" + typeFailNoIn = "%s must be of type %s" + typeFailWithDataNoIn = "%s must be of type %s: %q" + typeFailWithErrorNoIn = "%s must be of type %s, because: %s" + requiredFailNoIn = "%s is required" + readOnlyFailNoIn = "%s is readOnly" + tooLongMessageNoIn = "%s should be at most %d chars long" + tooShortMessageNoIn = "%s should be at least %d chars long" + patternFailNoIn = "%s should match '%s'" + enumFailNoIn = "%s should be one of %v" + multipleOfFailNoIn = "%s should be a multiple of %v" + maxIncFailNoIn = "%s should be less than or equal to %v" + maxExcFailNoIn = "%s should be less than %v" + minIncFailNoIn = "%s should be greater than or equal to %v" + minExcFailNoIn = "%s should be greater than %v" + uniqueFailNoIn = "%s shouldn't contain duplicates" + maxItemsFailNoIn = "%s should have at most %d items" + minItemsFailNoIn = "%s should have at least %d items" + noAdditionalItems = "%s in %s can't have additional items" + noAdditionalItemsNoIn = "%s can't have additional items" + tooFewProperties = "%s in %s should have at least %d properties" + tooFewPropertiesNoIn = "%s should have at least %d properties" + tooManyProperties = "%s in %s should have at most %d properties" + tooManyPropertiesNoIn = "%s should have at most %d properties" + unallowedProperty = "%s.%s in %s is a forbidden property" + unallowedPropertyNoIn = "%s.%s is a forbidden property" + failedAllPatternProps = "%s.%s in %s failed all pattern properties" + failedAllPatternPropsNoIn = "%s.%s failed all pattern properties" + multipleOfMustBePositive = "factor MultipleOf declared for %s must be positive: %v" +) + +// All code responses can be used to differentiate errors for different handling +// by the consuming program +const ( + // CompositeErrorCode remains 422 for backwards-compatibility + // and to separate it from validation errors with cause + CompositeErrorCode = 422 + // InvalidTypeCode is used for any subclass of invalid types + InvalidTypeCode = 600 + iota + RequiredFailCode + TooLongFailCode + TooShortFailCode + PatternFailCode + EnumFailCode + MultipleOfFailCode + MaxFailCode + MinFailCode + UniqueFailCode + MaxItemsFailCode + MinItemsFailCode + NoAdditionalItemsCode + TooFewPropertiesCode + TooManyPropertiesCode + UnallowedPropertyCode + FailedAllPatternPropsCode + MultipleOfMustBePositiveCode + ReadOnlyFailCode +) + +// CompositeError is an error that groups several errors together +type CompositeError struct { + Errors []error + code int32 + message string +} + +// Code for this error +func (c *CompositeError) Code() int32 { + return c.code +} + +func (c *CompositeError) Error() string { + if len(c.Errors) > 0 { + msgs := []string{c.message + ":"} + for _, e := range c.Errors { + msgs = append(msgs, e.Error()) + } + return strings.Join(msgs, "\n") + } + return c.message +} + +// MarshalJSON implements the JSON encoding interface +func (c CompositeError) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]interface{}{ + "code": c.code, + "message": c.message, + "errors": c.Errors, + }) +} + +// CompositeValidationError an error to wrap a bunch of other errors +func CompositeValidationError(errors ...error) *CompositeError { + return &CompositeError{ + code: CompositeErrorCode, + Errors: append([]error{}, errors...), + message: "validation failure list", + } +} + +// ValidateName recursively sets the name for all validations or updates them for nested properties +func (c *CompositeError) ValidateName(name string) *CompositeError { + for i, e := range c.Errors { + if ve, ok := e.(*Validation); ok { + c.Errors[i] = ve.ValidateName(name) + } else if ce, ok := e.(*CompositeError); ok { + c.Errors[i] = ce.ValidateName(name) + } + } + + return c +} + +// FailedAllPatternProperties an error for when the property doesn't match a pattern +func FailedAllPatternProperties(name, in, key string) *Validation { + msg := fmt.Sprintf(failedAllPatternProps, name, key, in) + if in == "" { + msg = fmt.Sprintf(failedAllPatternPropsNoIn, name, key) + } + return &Validation{ + code: FailedAllPatternPropsCode, + Name: name, + In: in, + Value: key, + message: msg, + } +} + +// PropertyNotAllowed an error for when the property doesn't match a pattern +func PropertyNotAllowed(name, in, key string) *Validation { + msg := fmt.Sprintf(unallowedProperty, name, key, in) + if in == "" { + msg = fmt.Sprintf(unallowedPropertyNoIn, name, key) + } + return &Validation{ + code: UnallowedPropertyCode, + Name: name, + In: in, + Value: key, + message: msg, + } +} + +// TooFewProperties an error for an object with too few properties +func TooFewProperties(name, in string, n int64) *Validation { + msg := fmt.Sprintf(tooFewProperties, name, in, n) + if in == "" { + msg = fmt.Sprintf(tooFewPropertiesNoIn, name, n) + } + return &Validation{ + code: TooFewPropertiesCode, + Name: name, + In: in, + Value: n, + message: msg, + } +} + +// TooManyProperties an error for an object with too many properties +func TooManyProperties(name, in string, n int64) *Validation { + msg := fmt.Sprintf(tooManyProperties, name, in, n) + if in == "" { + msg = fmt.Sprintf(tooManyPropertiesNoIn, name, n) + } + return &Validation{ + code: TooManyPropertiesCode, + Name: name, + In: in, + Value: n, + message: msg, + } +} + +// AdditionalItemsNotAllowed an error for invalid additional items +func AdditionalItemsNotAllowed(name, in string) *Validation { + msg := fmt.Sprintf(noAdditionalItems, name, in) + if in == "" { + msg = fmt.Sprintf(noAdditionalItemsNoIn, name) + } + return &Validation{ + code: NoAdditionalItemsCode, + Name: name, + In: in, + message: msg, + } +} + +// InvalidCollectionFormat another flavor of invalid type error +func InvalidCollectionFormat(name, in, format string) *Validation { + return &Validation{ + code: InvalidTypeCode, + Name: name, + In: in, + Value: format, + message: fmt.Sprintf("the collection format %q is not supported for the %s param %q", format, in, name), + } +} + +// InvalidTypeName an error for when the type is invalid +func InvalidTypeName(typeName string) *Validation { + return &Validation{ + code: InvalidTypeCode, + Value: typeName, + message: fmt.Sprintf(invalidType, typeName), + } +} + +// InvalidType creates an error for when the type is invalid +func InvalidType(name, in, typeName string, value interface{}) *Validation { + var message string + + if in != "" { + switch value.(type) { + case string: + message = fmt.Sprintf(typeFailWithData, name, in, typeName, value) + case error: + message = fmt.Sprintf(typeFailWithError, name, in, typeName, value) + default: + message = fmt.Sprintf(typeFail, name, in, typeName) + } + } else { + switch value.(type) { + case string: + message = fmt.Sprintf(typeFailWithDataNoIn, name, typeName, value) + case error: + message = fmt.Sprintf(typeFailWithErrorNoIn, name, typeName, value) + default: + message = fmt.Sprintf(typeFailNoIn, name, typeName) + } + } + + return &Validation{ + code: InvalidTypeCode, + Name: name, + In: in, + Value: value, + message: message, + } + +} + +// DuplicateItems error for when an array contains duplicates +func DuplicateItems(name, in string) *Validation { + msg := fmt.Sprintf(uniqueFail, name, in) + if in == "" { + msg = fmt.Sprintf(uniqueFailNoIn, name) + } + return &Validation{ + code: UniqueFailCode, + Name: name, + In: in, + message: msg, + } +} + +// TooManyItems error for when an array contains too many items +func TooManyItems(name, in string, max int64, value interface{}) *Validation { + msg := fmt.Sprintf(maxItemsFail, name, in, max) + if in == "" { + msg = fmt.Sprintf(maxItemsFailNoIn, name, max) + } + + return &Validation{ + code: MaxItemsFailCode, + Name: name, + In: in, + Value: value, + message: msg, + } +} + +// TooFewItems error for when an array contains too few items +func TooFewItems(name, in string, min int64, value interface{}) *Validation { + msg := fmt.Sprintf(minItemsFail, name, in, min) + if in == "" { + msg = fmt.Sprintf(minItemsFailNoIn, name, min) + } + return &Validation{ + code: MinItemsFailCode, + Name: name, + In: in, + Value: value, + message: msg, + } +} + +// ExceedsMaximumInt error for when maximum validation fails +func ExceedsMaximumInt(name, in string, max int64, exclusive bool, value interface{}) *Validation { + var message string + if in == "" { + m := maxIncFailNoIn + if exclusive { + m = maxExcFailNoIn + } + message = fmt.Sprintf(m, name, max) + } else { + m := maxIncFail + if exclusive { + m = maxExcFail + } + message = fmt.Sprintf(m, name, in, max) + } + return &Validation{ + code: MaxFailCode, + Name: name, + In: in, + Value: value, + message: message, + } +} + +// ExceedsMaximumUint error for when maximum validation fails +func ExceedsMaximumUint(name, in string, max uint64, exclusive bool, value interface{}) *Validation { + var message string + if in == "" { + m := maxIncFailNoIn + if exclusive { + m = maxExcFailNoIn + } + message = fmt.Sprintf(m, name, max) + } else { + m := maxIncFail + if exclusive { + m = maxExcFail + } + message = fmt.Sprintf(m, name, in, max) + } + return &Validation{ + code: MaxFailCode, + Name: name, + In: in, + Value: value, + message: message, + } +} + +// ExceedsMaximum error for when maximum validation fails +func ExceedsMaximum(name, in string, max float64, exclusive bool, value interface{}) *Validation { + var message string + if in == "" { + m := maxIncFailNoIn + if exclusive { + m = maxExcFailNoIn + } + message = fmt.Sprintf(m, name, max) + } else { + m := maxIncFail + if exclusive { + m = maxExcFail + } + message = fmt.Sprintf(m, name, in, max) + } + return &Validation{ + code: MaxFailCode, + Name: name, + In: in, + Value: value, + message: message, + } +} + +// ExceedsMinimumInt error for when minimum validation fails +func ExceedsMinimumInt(name, in string, min int64, exclusive bool, value interface{}) *Validation { + var message string + if in == "" { + m := minIncFailNoIn + if exclusive { + m = minExcFailNoIn + } + message = fmt.Sprintf(m, name, min) + } else { + m := minIncFail + if exclusive { + m = minExcFail + } + message = fmt.Sprintf(m, name, in, min) + } + return &Validation{ + code: MinFailCode, + Name: name, + In: in, + Value: value, + message: message, + } +} + +// ExceedsMinimumUint error for when minimum validation fails +func ExceedsMinimumUint(name, in string, min uint64, exclusive bool, value interface{}) *Validation { + var message string + if in == "" { + m := minIncFailNoIn + if exclusive { + m = minExcFailNoIn + } + message = fmt.Sprintf(m, name, min) + } else { + m := minIncFail + if exclusive { + m = minExcFail + } + message = fmt.Sprintf(m, name, in, min) + } + return &Validation{ + code: MinFailCode, + Name: name, + In: in, + Value: value, + message: message, + } +} + +// ExceedsMinimum error for when minimum validation fails +func ExceedsMinimum(name, in string, min float64, exclusive bool, value interface{}) *Validation { + var message string + if in == "" { + m := minIncFailNoIn + if exclusive { + m = minExcFailNoIn + } + message = fmt.Sprintf(m, name, min) + } else { + m := minIncFail + if exclusive { + m = minExcFail + } + message = fmt.Sprintf(m, name, in, min) + } + return &Validation{ + code: MinFailCode, + Name: name, + In: in, + Value: value, + message: message, + } +} + +// NotMultipleOf error for when multiple of validation fails +func NotMultipleOf(name, in string, multiple, value interface{}) *Validation { + var msg string + if in == "" { + msg = fmt.Sprintf(multipleOfFailNoIn, name, multiple) + } else { + msg = fmt.Sprintf(multipleOfFail, name, in, multiple) + } + return &Validation{ + code: MultipleOfFailCode, + Name: name, + In: in, + Value: value, + message: msg, + } +} + +// EnumFail error for when an enum validation fails +func EnumFail(name, in string, value interface{}, values []interface{}) *Validation { + var msg string + if in == "" { + msg = fmt.Sprintf(enumFailNoIn, name, values) + } else { + msg = fmt.Sprintf(enumFail, name, in, values) + } + + return &Validation{ + code: EnumFailCode, + Name: name, + In: in, + Value: value, + Values: values, + message: msg, + } +} + +// Required error for when a value is missing +func Required(name, in string, value interface{}) *Validation { + var msg string + if in == "" { + msg = fmt.Sprintf(requiredFailNoIn, name) + } else { + msg = fmt.Sprintf(requiredFail, name, in) + } + return &Validation{ + code: RequiredFailCode, + Name: name, + In: in, + Value: value, + message: msg, + } +} + +// ReadOnly error for when a value is present in request +func ReadOnly(name, in string, value interface{}) *Validation { + var msg string + if in == "" { + msg = fmt.Sprintf(readOnlyFailNoIn, name) + } else { + msg = fmt.Sprintf(readOnlyFail, name, in) + } + return &Validation{ + code: ReadOnlyFailCode, + Name: name, + In: in, + Value: value, + message: msg, + } +} + +// TooLong error for when a string is too long +func TooLong(name, in string, max int64, value interface{}) *Validation { + var msg string + if in == "" { + msg = fmt.Sprintf(tooLongMessageNoIn, name, max) + } else { + msg = fmt.Sprintf(tooLongMessage, name, in, max) + } + return &Validation{ + code: TooLongFailCode, + Name: name, + In: in, + Value: value, + message: msg, + } +} + +// TooShort error for when a string is too short +func TooShort(name, in string, min int64, value interface{}) *Validation { + var msg string + if in == "" { + msg = fmt.Sprintf(tooShortMessageNoIn, name, min) + } else { + msg = fmt.Sprintf(tooShortMessage, name, in, min) + } + + return &Validation{ + code: TooShortFailCode, + Name: name, + In: in, + Value: value, + message: msg, + } +} + +// FailedPattern error for when a string fails a regex pattern match +// the pattern that is returned is the ECMA syntax version of the pattern not the golang version. +func FailedPattern(name, in, pattern string, value interface{}) *Validation { + var msg string + if in == "" { + msg = fmt.Sprintf(patternFailNoIn, name, pattern) + } else { + msg = fmt.Sprintf(patternFail, name, in, pattern) + } + + return &Validation{ + code: PatternFailCode, + Name: name, + In: in, + Value: value, + message: msg, + } +} + +// MultipleOfMustBePositive error for when a +// multipleOf factor is negative +func MultipleOfMustBePositive(name, in string, factor interface{}) *Validation { + return &Validation{ + code: MultipleOfMustBePositiveCode, + Name: name, + In: in, + Value: factor, + message: fmt.Sprintf(multipleOfMustBePositive, name, factor), + } +} diff --git a/vendor/github.com/go-openapi/strfmt/.editorconfig b/vendor/github.com/go-openapi/strfmt/.editorconfig new file mode 100644 index 0000000000..3152da69a5 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/.editorconfig @@ -0,0 +1,26 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +# Set default charset +[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] +charset = utf-8 + +# Tab indentation (no size specified) +[*.go] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false + +# Matches the exact files either package.json or .travis.yml +[{package.json,.travis.yml}] +indent_style = space +indent_size = 2 diff --git a/vendor/github.com/go-openapi/strfmt/.gitattributes b/vendor/github.com/go-openapi/strfmt/.gitattributes new file mode 100644 index 0000000000..d020be8ea4 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/.gitattributes @@ -0,0 +1,2 @@ +*.go text eol=lf + diff --git a/vendor/github.com/go-openapi/strfmt/.gitignore b/vendor/github.com/go-openapi/strfmt/.gitignore new file mode 100644 index 0000000000..dd91ed6a04 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/.gitignore @@ -0,0 +1,2 @@ +secrets.yml +coverage.out diff --git a/vendor/github.com/go-openapi/strfmt/.golangci.yml b/vendor/github.com/go-openapi/strfmt/.golangci.yml new file mode 100644 index 0000000000..be4899cb12 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/.golangci.yml @@ -0,0 +1,59 @@ +linters-settings: + govet: + check-shadowing: true + golint: + min-confidence: 0 + gocyclo: + min-complexity: 31 + maligned: + suggest-new: true + dupl: + threshold: 100 + goconst: + min-len: 2 + min-occurrences: 4 + +linters: + enable: + - revive + - goimports + - gosec + - unparam + - unconvert + - predeclared + - prealloc + - misspell + + # disable: + # - maligned + # - lll + # - gochecknoinits + # - gochecknoglobals + # - godox + # - gocognit + # - whitespace + # - wsl + # - funlen + # - wrapcheck + # - testpackage + # - nlreturn + # - gofumpt + # - goerr113 + # - gci + # - gomnd + # - godot + # - exhaustivestruct + # - paralleltest + # - varnamelen + # - ireturn + # - exhaustruct + # #- thelper + +issues: + exclude-rules: + - path: bson.go + text: "should be .*ObjectID" + linters: + - golint + - stylecheck + diff --git a/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..9322b065e3 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at ivan+abuse@flanders.co.nz. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/strfmt/LICENSE b/vendor/github.com/go-openapi/strfmt/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-openapi/strfmt/README.md b/vendor/github.com/go-openapi/strfmt/README.md new file mode 100644 index 0000000000..0cf89d7766 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/README.md @@ -0,0 +1,88 @@ +# Strfmt [![Build Status](https://travis-ci.org/go-openapi/strfmt.svg?branch=master)](https://travis-ci.org/go-openapi/strfmt) [![codecov](https://codecov.io/gh/go-openapi/strfmt/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/strfmt) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) + +[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/strfmt/master/LICENSE) +[![GoDoc](https://godoc.org/github.com/go-openapi/strfmt?status.svg)](http://godoc.org/github.com/go-openapi/strfmt) +[![GolangCI](https://golangci.com/badges/github.com/go-openapi/strfmt.svg)](https://golangci.com) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/strfmt)](https://goreportcard.com/report/github.com/go-openapi/strfmt) + +This package exposes a registry of data types to support string formats in the go-openapi toolkit. + +strfmt represents a well known string format such as credit card or email. The go toolkit for OpenAPI specifications knows how to deal with those. + +## Supported data formats +go-openapi/strfmt follows the swagger 2.0 specification with the following formats +defined [here](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types). + +It also provides convenient extensions to go-openapi users. + +- [x] JSON-schema draft 4 formats + - date-time + - email + - hostname + - ipv4 + - ipv6 + - uri +- [x] swagger 2.0 format extensions + - binary + - byte (e.g. base64 encoded string) + - date (e.g. "1970-01-01") + - password +- [x] go-openapi custom format extensions + - bsonobjectid (BSON objectID) + - creditcard + - duration (e.g. "3 weeks", "1ms") + - hexcolor (e.g. "#FFFFFF") + - isbn, isbn10, isbn13 + - mac (e.g "01:02:03:04:05:06") + - rgbcolor (e.g. "rgb(100,100,100)") + - ssn + - uuid, uuid3, uuid4, uuid5 + - cidr (e.g. "192.0.2.1/24", "2001:db8:a0b:12f0::1/32") + - ulid (e.g. "00000PP9HGSBSSDZ1JTEXBJ0PW", [spec](https://github.com/ulid/spec)) + +> NOTE: as the name stands for, this package is intended to support string formatting only. +> It does not provide validation for numerical values with swagger format extension for JSON types "number" or +> "integer" (e.g. float, double, int32...). + +## Type conversion + +All types defined here are stringers and may be converted to strings with `.String()`. +Note that most types defined by this package may be converted directly to string like `string(Email{})`. + +`Date` and `DateTime` may be converted directly to `time.Time` like `time.Time(Time{})`. +Similarly, you can convert `Duration` to `time.Duration` as in `time.Duration(Duration{})` + +## Using pointers + +The `conv` subpackage provides helpers to convert the types to and from pointers, just like `go-openapi/swag` does +with primitive types. + +## Format types +Types defined in strfmt expose marshaling and validation capabilities. + +List of defined types: +- Base64 +- CreditCard +- Date +- DateTime +- Duration +- Email +- HexColor +- Hostname +- IPv4 +- IPv6 +- CIDR +- ISBN +- ISBN10 +- ISBN13 +- MAC +- ObjectId +- Password +- RGBColor +- SSN +- URI +- UUID +- UUID3 +- UUID4 +- UUID5 +- [ULID](https://github.com/ulid/spec) diff --git a/vendor/github.com/go-openapi/strfmt/bson.go b/vendor/github.com/go-openapi/strfmt/bson.go new file mode 100644 index 0000000000..a8a3604a2c --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/bson.go @@ -0,0 +1,165 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package strfmt + +import ( + "database/sql/driver" + "fmt" + + "go.mongodb.org/mongo-driver/bson" + + "go.mongodb.org/mongo-driver/bson/bsontype" + bsonprim "go.mongodb.org/mongo-driver/bson/primitive" +) + +func init() { + var id ObjectId + // register this format in the default registry + Default.Add("bsonobjectid", &id, IsBSONObjectID) +} + +// IsBSONObjectID returns true when the string is a valid BSON.ObjectId +func IsBSONObjectID(str string) bool { + _, err := bsonprim.ObjectIDFromHex(str) + return err == nil +} + +// ObjectId represents a BSON object ID (alias to go.mongodb.org/mongo-driver/bson/primitive.ObjectID) +// +// swagger:strfmt bsonobjectid +type ObjectId bsonprim.ObjectID //nolint:revive + +// NewObjectId creates a ObjectId from a Hex String +func NewObjectId(hex string) ObjectId { //nolint:revive + oid, err := bsonprim.ObjectIDFromHex(hex) + if err != nil { + panic(err) + } + return ObjectId(oid) +} + +// MarshalText turns this instance into text +func (id ObjectId) MarshalText() ([]byte, error) { + oid := bsonprim.ObjectID(id) + if oid == bsonprim.NilObjectID { + return nil, nil + } + return []byte(oid.Hex()), nil +} + +// UnmarshalText hydrates this instance from text +func (id *ObjectId) UnmarshalText(data []byte) error { // validation is performed later on + if len(data) == 0 { + *id = ObjectId(bsonprim.NilObjectID) + return nil + } + oidstr := string(data) + oid, err := bsonprim.ObjectIDFromHex(oidstr) + if err != nil { + return err + } + *id = ObjectId(oid) + return nil +} + +// Scan read a value from a database driver +func (id *ObjectId) Scan(raw interface{}) error { + var data []byte + switch v := raw.(type) { + case []byte: + data = v + case string: + data = []byte(v) + default: + return fmt.Errorf("cannot sql.Scan() strfmt.URI from: %#v", v) + } + + return id.UnmarshalText(data) +} + +// Value converts a value to a database driver value +func (id ObjectId) Value() (driver.Value, error) { + return driver.Value(bsonprim.ObjectID(id).Hex()), nil +} + +func (id ObjectId) String() string { + return bsonprim.ObjectID(id).Hex() +} + +// MarshalJSON returns the ObjectId as JSON +func (id ObjectId) MarshalJSON() ([]byte, error) { + return bsonprim.ObjectID(id).MarshalJSON() +} + +// UnmarshalJSON sets the ObjectId from JSON +func (id *ObjectId) UnmarshalJSON(data []byte) error { + var obj bsonprim.ObjectID + if err := obj.UnmarshalJSON(data); err != nil { + return err + } + *id = ObjectId(obj) + return nil +} + +// MarshalBSON renders the object id as a BSON document +func (id ObjectId) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": bsonprim.ObjectID(id)}) +} + +// UnmarshalBSON reads the objectId from a BSON document +func (id *ObjectId) UnmarshalBSON(data []byte) error { + var obj struct { + Data bsonprim.ObjectID + } + if err := bson.Unmarshal(data, &obj); err != nil { + return err + } + *id = ObjectId(obj.Data) + return nil +} + +// MarshalBSONValue is an interface implemented by types that can marshal themselves +// into a BSON document represented as bytes. The bytes returned must be a valid +// BSON document if the error is nil. +func (id ObjectId) MarshalBSONValue() (bsontype.Type, []byte, error) { + oid := bsonprim.ObjectID(id) + return bsontype.ObjectID, oid[:], nil +} + +// UnmarshalBSONValue is an interface implemented by types that can unmarshal a +// BSON value representation of themselves. The BSON bytes and type can be +// assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it +// wishes to retain the data after returning. +func (id *ObjectId) UnmarshalBSONValue(_ bsontype.Type, data []byte) error { + var oid bsonprim.ObjectID + copy(oid[:], data) + *id = ObjectId(oid) + return nil +} + +// DeepCopyInto copies the receiver and writes its value into out. +func (id *ObjectId) DeepCopyInto(out *ObjectId) { + *out = *id +} + +// DeepCopy copies the receiver into a new ObjectId. +func (id *ObjectId) DeepCopy() *ObjectId { + if id == nil { + return nil + } + out := new(ObjectId) + id.DeepCopyInto(out) + return out +} diff --git a/vendor/github.com/go-openapi/strfmt/date.go b/vendor/github.com/go-openapi/strfmt/date.go new file mode 100644 index 0000000000..3c93381c7c --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/date.go @@ -0,0 +1,187 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package strfmt + +import ( + "database/sql/driver" + "encoding/json" + "errors" + "fmt" + "time" + + "go.mongodb.org/mongo-driver/bson" +) + +func init() { + d := Date{} + // register this format in the default registry + Default.Add("date", &d, IsDate) +} + +// IsDate returns true when the string is a valid date +func IsDate(str string) bool { + _, err := time.Parse(RFC3339FullDate, str) + return err == nil +} + +const ( + // RFC3339FullDate represents a full-date as specified by RFC3339 + // See: http://goo.gl/xXOvVd + RFC3339FullDate = "2006-01-02" +) + +// Date represents a date from the API +// +// swagger:strfmt date +type Date time.Time + +// String converts this date into a string +func (d Date) String() string { + return time.Time(d).Format(RFC3339FullDate) +} + +// UnmarshalText parses a text representation into a date type +func (d *Date) UnmarshalText(text []byte) error { + if len(text) == 0 { + return nil + } + dd, err := time.ParseInLocation(RFC3339FullDate, string(text), DefaultTimeLocation) + if err != nil { + return err + } + *d = Date(dd) + return nil +} + +// MarshalText serializes this date type to string +func (d Date) MarshalText() ([]byte, error) { + return []byte(d.String()), nil +} + +// Scan scans a Date value from database driver type. +func (d *Date) Scan(raw interface{}) error { + switch v := raw.(type) { + case []byte: + return d.UnmarshalText(v) + case string: + return d.UnmarshalText([]byte(v)) + case time.Time: + *d = Date(v) + return nil + case nil: + *d = Date{} + return nil + default: + return fmt.Errorf("cannot sql.Scan() strfmt.Date from: %#v", v) + } +} + +// Value converts Date to a primitive value ready to written to a database. +func (d Date) Value() (driver.Value, error) { + return driver.Value(d.String()), nil +} + +// MarshalJSON returns the Date as JSON +func (d Date) MarshalJSON() ([]byte, error) { + return json.Marshal(time.Time(d).Format(RFC3339FullDate)) +} + +// UnmarshalJSON sets the Date from JSON +func (d *Date) UnmarshalJSON(data []byte) error { + if string(data) == jsonNull { + return nil + } + var strdate string + if err := json.Unmarshal(data, &strdate); err != nil { + return err + } + tt, err := time.ParseInLocation(RFC3339FullDate, strdate, DefaultTimeLocation) + if err != nil { + return err + } + *d = Date(tt) + return nil +} + +func (d Date) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": d.String()}) +} + +func (d *Date) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if data, ok := m["data"].(string); ok { + rd, err := time.ParseInLocation(RFC3339FullDate, data, DefaultTimeLocation) + if err != nil { + return err + } + *d = Date(rd) + return nil + } + + return errors.New("couldn't unmarshal bson bytes value as Date") +} + +// DeepCopyInto copies the receiver and writes its value into out. +func (d *Date) DeepCopyInto(out *Date) { + *out = *d +} + +// DeepCopy copies the receiver into a new Date. +func (d *Date) DeepCopy() *Date { + if d == nil { + return nil + } + out := new(Date) + d.DeepCopyInto(out) + return out +} + +// GobEncode implements the gob.GobEncoder interface. +func (d Date) GobEncode() ([]byte, error) { + return d.MarshalBinary() +} + +// GobDecode implements the gob.GobDecoder interface. +func (d *Date) GobDecode(data []byte) error { + return d.UnmarshalBinary(data) +} + +// MarshalBinary implements the encoding.BinaryMarshaler interface. +func (d Date) MarshalBinary() ([]byte, error) { + return time.Time(d).MarshalBinary() +} + +// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +func (d *Date) UnmarshalBinary(data []byte) error { + var original time.Time + + err := original.UnmarshalBinary(data) + if err != nil { + return err + } + + *d = Date(original) + + return nil +} + +// Equal checks if two Date instances are equal +func (d Date) Equal(d2 Date) bool { + return time.Time(d).Equal(time.Time(d2)) +} diff --git a/vendor/github.com/go-openapi/strfmt/default.go b/vendor/github.com/go-openapi/strfmt/default.go new file mode 100644 index 0000000000..a89a4de3f3 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/default.go @@ -0,0 +1,2035 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package strfmt + +import ( + "database/sql/driver" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/mail" + "regexp" + "strings" + + "github.com/asaskevich/govalidator" + "go.mongodb.org/mongo-driver/bson" +) + +const ( + // HostnamePattern http://json-schema.org/latest/json-schema-validation.html#anchor114 + // A string instance is valid against this attribute if it is a valid + // representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034]. + // http://tools.ietf.org/html/rfc1034#section-3.5 + // ::= any one of the ten digits 0 through 9 + // var digit = /[0-9]/; + // ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case + // var letter = /[a-zA-Z]/; + // ::= | + // var letDig = /[0-9a-zA-Z]/; + // ::= | "-" + // var letDigHyp = /[-0-9a-zA-Z]/; + // ::= | + // var ldhStr = /[-0-9a-zA-Z]+/; + //