Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement schema check API with OpenAPI specification (#1693)
ecmadao732b48a6624f
diff --git a/.gitignore b/.gitignoreindex 9acfcbeb00..09d4448678 100644--- a/.gitignore+++ b/.gitignore@@ -35,3 +35,4 @@ bytebase-build.DS_Storedist/+docs/openapi/swagger.jsondiff --git a/api/environment.go b/api/environment.goindex d96703036d..62d7020aa4 100644--- a/api/environment.go+++ b/api/environment.go@@ -38,6 +38,9 @@ type EnvironmentFind struct {// Standard fieldsRowStatus *RowStatus++ // Domain specific fields+ Name *string}func (find *EnvironmentFind) String() string {diff --git a/docs/openapi.md b/docs/openapi.mdnew file mode 100644index 0000000000..6320d484d3--- /dev/null+++ b/docs/openapi.md@@ -0,0 +1,58 @@+# Bytebase OpenAPI++Bytebase OpenAPI implements the OpenAPI specification with Swagger.++## Dev++### Required tools++* [`swag`](https://github.com/swaggo/swag) for the Swagger command line.+* [`echo-swagger`](https://github.com/swaggo/echo-swagger) Swagger middleware for echo.++### Comment for OpenAPIs++1. Add general API annotations in `./server/server.go`.+2. Add API operation annotations in your controller code.++> Note: you need to comment for a specific controller function, otherwise the swagger cannot extract the comment as docs. For example:++* ❌ Incorrect++```go+// Swagger doc (cannot work)+// @Summary Health check for service+// @Accept */*+// @Produce plain+// @Router /healthz [get]+e.GET("/healthz", func(c echo.Context) error {+ return c.String(http.StatusOK, "OK!\n")+})+```++* ✅ Correct++```go+// Swagger doc (this can work)+// @Summary Health check for service+// @Accept */*+// @Produce plain+// @Router /healthz [get]+func healthCheckController(c echo.Context) error {+ return c.String(http.StatusOK, "OK!\n")+}++e.GET("/healthz", healthCheckController)+```++### Generate Swagger docs++Every time you changed the comments, you need to re-run the following command to re-generate the Swagger docs:++```bash+cd bytebase+# generate swagger doc+swag init -g ./server.go -d ./server --output docs/openapi --parseDependency+```++This should generate new docs under `./docs/openapi` folder based on your comments.+Then start the service, you can visit the Swagger dashboard on `/swagger/index.html`diff --git a/docs/openapi/docs.go b/docs/openapi/docs.gonew file mode 100644index 0000000000..a568ed5e66--- /dev/null+++ b/docs/openapi/docs.go@@ -0,0 +1,138 @@+// Package openapi GENERATED BY SWAG; DO NOT EDIT+// This file was generated by swaggo/swag+package openapi++import "github.com/swaggo/swag"++const docTemplate = `{+ "schemes": {{ marshal .Schemes }},+ "swagger": "2.0",+ "info": {+ "description": "{{escape .Description}}",+ "title": "{{.Title}}",+ "termsOfService": "https://www.bytebase.com/terms",+ "contact": {+ "name": "API Support",+ "url": "https://github.com/bytebase/bytebase/",+ "email": "[email protected]"+ },+ "license": {+ "name": "MIT",+ "url": "https://github.com/bytebase/bytebase/blob/main/LICENSE"+ },+ "version": "{{.Version}}"+ },+ "host": "{{.Host}}",+ "basePath": "{{.BasePath}}",+ "paths": {+ "/sql/advise": {+ "get": {+ "description": "Parse and check the SQL statement according to the schema review policy.",+ "consumes": [+ "*/*"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Schema Review"+ ],+ "summary": "Check the SQL statement.",+ "parameters": [+ {+ "type": "string",+ "description": "The environment name. Case sensitive",+ "name": "environment",+ "in": "query",+ "required": true+ },+ {+ "type": "string",+ "description": "The SQL statement",+ "name": "statement",+ "in": "query",+ "required": true+ },+ {+ "enum": [+ "MySQL",+ "PostgreSQL",+ "TiDB"+ ],+ "type": "string",+ "description": "The database type",+ "name": "databaseType",+ "in": "query",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/advisor.Advice"+ }+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/echo.HTTPError"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/echo.HTTPError"+ }+ }+ }+ }+ }+ },+ "definitions": {+ "advisor.Advice": {+ "type": "object",+ "properties": {+ "code": {+ "description": "Code is the SQL check error code.",+ "type": "integer"+ },+ "content": {+ "type": "string"+ },+ "status": {+ "description": "Status is the SQL check result. Could be \"SUCCESS\", \"WARN\", \"ERROR\"",+ "type": "string"+ },+ "title": {+ "type": "string"+ }+ }+ },+ "echo.HTTPError": {+ "type": "object",+ "properties": {+ "message": {}+ }+ }+ }+}`++// SwaggerInfo holds exported Swagger Info so clients can modify it+var SwaggerInfo = &swag.Spec{+ Version: "1.0",+ Host: "localhost:8080",+ BasePath: "/v1/",+ Schemes: []string{"http"},+ Title: "Bytebase OpenAPI",+ Description: "The OpenAPI for bytebase.",+ InfoInstanceName: "swagger",+ SwaggerTemplate: docTemplate,+}++func init() {+ swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)+}diff --git a/docs/openapi/swagger.yaml b/docs/openapi/swagger.yamlnew file mode 100644index 0000000000..c0ce196375--- /dev/null+++ b/docs/openapi/swagger.yaml@@ -0,0 +1,82 @@+basePath: /v1/+definitions:+ advisor.Advice:+ properties:+ code:+ description: Code is the SQL check error code.+ type: integer+ content:+ type: string+ status:+ description: Status is the SQL check result. Could be "SUCCESS", "WARN", "ERROR"+ type: string+ title:+ type: string+ type: object+ echo.HTTPError:+ properties:+ message: {}+ type: object+host: localhost:8080+info:+ contact:+ email: [email protected]+ name: API Support+ url: https://github.com/bytebase/bytebase/+ description: The OpenAPI for bytebase.+ license:+ name: MIT+ url: https://github.com/bytebase/bytebase/blob/main/LICENSE+ termsOfService: https://www.bytebase.com/terms+ title: Bytebase OpenAPI+ version: "1.0"+paths:+ /sql/advise:+ get:+ consumes:+ - '*/*'+ description: Parse and check the SQL statement according to the schema review+ policy.+ parameters:+ - description: The environment name. Case sensitive+ in: query+ name: environment+ required: true+ type: string+ - description: The SQL statement+ in: query+ name: statement+ required: true+ type: string+ - description: The database type+ enum:+ - MySQL+ - PostgreSQL+ - TiDB+ in: query+ name: databaseType+ required: true+ type: string+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ items:+ $ref: '#/definitions/advisor.Advice'+ type: array+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/echo.HTTPError'+ "500":+ description: Internal Server Error+ schema:+ $ref: '#/definitions/echo.HTTPError'+ summary: Check the SQL statement.+ tags:+ - Schema Review+schemes:+- http+swagger: "2.0"diff --git a/go.mod b/go.modindex 08d66238a1..20993c2c8d 100644--- a/go.mod+++ b/go.mod@@ -18,7 +18,7 @@ require (github.com/jackc/pgtype v1.10.0github.com/jackc/pgx/v4 v4.15.0github.com/labstack/echo-contrib v0.12.0- github.com/labstack/echo/v4 v4.6.1+ github.com/labstack/echo/v4 v4.7.2github.com/mattn/go-sqlite3 v1.14.7github.com/pganalyze/pg_query_go/v2 v2.1.2github.com/pingcap/tidb v1.1.0-beta.0.20211209055157-9f744cdf8266@@ -30,13 +30,13 @@ require (github.com/snowflakedb/gosnowflake v1.6.3github.com/spf13/cobra v1.2.0github.com/stretchr/testify v1.7.0+ github.com/swaggo/echo-swagger v1.3.3+ github.com/swaggo/swag v1.8.1github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8github.com/xo/dburl v0.9.1github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c // indirectgo.uber.org/zap v1.19.1- golang.org/x/crypto v0.0.0-20210920023735-84f357641f63- golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect- golang.org/x/sys v0.0.0-20220224003255-dbe011f71a99 // indirect+ golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4)// copied from pingcap/tidbdiff --git a/go.sum b/go.sumindex 2c26a7c83b..1543987d1a 100644--- a/go.sum+++ b/go.sum@@ -80,12 +80,15 @@ github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzgithub.com/Joker/jade v1.0.1-0.20190614124447-d475f43051e7/go.mod h1:6E6s8o2AE4KhCrqr6GRJjdC/gNfTdxkIXvuGZZda2VM=github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible h1:1G1pk05UrOh0NlF1oeaaix1x8XzrfjIDK47TY0Zehcw=github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=+github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc=github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs=github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=+github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=+github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=github.com/ReneKroon/ttlcache/v2 v2.3.0/go.mod h1:zbo6Pv/28e21Z8CzzqgYRArQYGYtjONRxaAKGxzQvG4=github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0=@@ -99,6 +102,8 @@ github.com/VividCortex/ewma v1.1.1 h1:MnEK4VOv6n0RSY4vtRe3h11qjxL3+t0B8yOL8iMXdcgithub.com/VividCortex/ewma v1.1.1/go.mod h1:2Tkkvm3sRDVXaiyucHiACn4cqf7DpdyLvmxzcbUokwA=github.com/VividCortex/mysqlerr v0.0.0-20200629151747-c28746d985dd/go.mod h1:f3HiCrHjHBdcm6E83vGaXh1KomZMA2P6aeo3hKx/wg0=github.com/Xeoncross/go-aesctr-with-hmac v0.0.0-20200623134604-12b17a7ff502/go.mod h1:pmnBM9bxWSiHvC/gSWunUIyDvGn33EkP2CUjxFKtTTM=+github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs=+github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY=github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw=github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=@@ -333,15 +338,23 @@ github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIgithub.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/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=+github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=+github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=github.com/go-openapi/jsonreference v0.17.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I=github.com/go-openapi/jsonreference v0.19.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I=github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc=github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8=+github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=+github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=github.com/go-openapi/spec v0.19.0/go.mod h1:XkF/MOi14NmjsfZ8VtAKf8pIlbZzyoTvZsdfssdxcBI=github.com/go-openapi/spec v0.19.4/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8Lj9mJglo=+github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=+github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=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.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=+github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM=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=@@ -614,6 +627,8 @@ github.com/joho/sqltocsv v0.0.0-20210428211105-a6d6801d59df/go.mod h1:mAVCUAYtW9github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo=github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=github.com/joomcode/errorx v1.0.1/go.mod h1:kgco15ekB6cs+4Xjzo7SPeXzx38PbJzBwbnu9qfVNHQ=+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=@@ -672,8 +687,9 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/labstack/echo-contrib v0.12.0 h1:NPr1ez+XUa5s/4LujEon+32Bxg5DO6EKSW/va06pmLc=github.com/labstack/echo-contrib v0.12.0/go.mod h1:kR62TbwsBgmpV2HVab5iQRsQtLuhPyGqCBee88XRc4M=github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g=-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/echo/v4 v4.7.2 h1:Kv2/p8OaQ+M6Ex4eGimg9b9e6icoxA42JSlOR3msKtI=+github.com/labstack/echo/v4 v4.7.2/go.mod h1:xkCDAdFCIf8jsFQ5NnbK7oqaF/yU1A1X20Ltm0OvSks=github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=github.com/labstack/gommon v0.3.1 h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o=github.com/labstack/gommon v0.3.1/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=@@ -688,6 +704,9 @@ github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKgithub.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=+github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=+github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=+github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=@@ -786,6 +805,12 @@ github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStgithub.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=github.com/openzipkin/zipkin-go v0.3.0/go.mod h1:4c3sLeE8xjNqehmF5RpAFLPLJxXscc0R4l6Zg0P1tTQ=+github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE=+github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U=+github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=+github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs=+github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo=+github.com/otiai10/mint v1.3.3/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc=github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=github.com/pascaldekloe/name v0.0.0-20180628100202-0fd16699aae1/go.mod h1:eD5JxqMiuNYyFNmyY9rkJ/slN8y59oEu4Ei7F8OoKWQ=github.com/paulmach/orb v0.4.0 h1:ilp1MQjRapLJ1+qcays1nZpe0mvkCY+b8JU/qBKRZ1A=@@ -999,12 +1024,18 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=+github.com/swaggo/echo-swagger v1.3.3 h1:Fx8kQ8IcIIEL3ZE20wzvcT8gFnPo/4U+fsnS3I1wvCw=+github.com/swaggo/echo-swagger v1.3.3/go.mod h1:vbKcEBeJgOexLuPcsdZhrRAV508fsE79xaKIqmvse98=github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14/go.mod h1:gxQT6pBGRuIGunNf/+tSOB5OHvguWi8Tbt82WOkf35E=+github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe h1:K8pHPVoTgxFJt1lXuIzzOX7zZhZFldJQK/CgKx9BFIc=+github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w=github.com/swaggo/gin-swagger v1.2.0/go.mod h1:qlH2+W7zXGZkczuL+r2nEBR2JTT+/lX05Nn6vPhc7OI=github.com/swaggo/http-swagger v0.0.0-20200308142732-58ac5e232fba/go.mod h1:O1lAbCgAAX/KZ80LM/OXwtWFI/5TvZlwxSg8Cq08PV0=github.com/swaggo/swag v1.5.1/go.mod h1:1Bl9F/ZBpVWh22nY0zmYyASPO1lI/zIwRDrpZU+tv8Y=github.com/swaggo/swag v1.6.3/go.mod h1:wcc83tB4Mb2aNiL/HP4MFeQdpHUrca+Rp/DRNgWAUio=github.com/swaggo/swag v1.6.6-0.20200529100950-7c765ddd0476/go.mod h1:xDhTyuFIujYiN3DKWC/H/83xcfHp+UE/IzWWampG7Zc=+github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI=+github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ=github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965 h1:1oFLiOyVl+W7bnBzGhf7BbIv9loSFQcieWWYIjLqcAw=github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA=github.com/thoas/go-funk v0.8.0/go.mod h1:+IWnUfUmFO1+WVYQWQtIJHeRRdaIyyYglZN7xzUPe4Q=@@ -1088,6 +1119,8 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9degithub.com/yuin/goldmark v1.1.32/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.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=+github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=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=go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=@@ -1171,8 +1204,10 @@ golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPgolang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=-golang.org/x/crypto v0.0.0-20210920023735-84f357641f63 h1:kETrAMYZq6WVGPa8IIixL0CaEcIUNi+1WX7grUoi3y8=golang.org/x/crypto v0.0.0-20210920023735-84f357641f63/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=+golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA=+golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=golang.org/x/exp v0.0.0-20181106170214-d68db9428509/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=@@ -1215,6 +1250,8 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.4.1/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 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o=+golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=@@ -1265,16 +1302,20 @@ golang.org/x/net v0.0.0-20210224082022-3d97a244fca7/go.mod h1:m0MpNAwzfU5UDzcl9vgolang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=+golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=+golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210913180222-943fd674d43e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=-golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk=-golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=+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-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA=+golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=@@ -1374,6 +1415,7 @@ golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wgolang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=@@ -1384,15 +1426,17 @@ golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBcgolang.org/x/sys v0.0.0-20210616094352-59db8d763f22/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-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20210818153620-00dd8d7831e7/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e/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-20210927094055-39ccf1dd6fa6/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-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20220224003255-dbe011f71a99 h1:Us899Z5PCfOrSgeCYWobI1/bSigAz9Rhf8+fz5Grkzc=-golang.org/x/sys v0.0.0-20220224003255-dbe011f71a99/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 h1:xHms4gcpe1YE7A3yIllJXP16CMAGuqwO2lX1mTyyRRc=+golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=@@ -1489,8 +1533,10 @@ golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=-golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA=golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=+golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=+golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20=+golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 726f4c8395..1ab3a48cf3 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -113,7 +113,9 @@ const (// Advice is the result of an advisor.type Advice struct {- Status Status `json:"status"`+ // Status is the SQL check result. Could be "SUCCESS", "WARN", "ERROR"+ Status Status `json:"status"`+ // Code is the SQL check error code.Code Code `json:"code"`Title string `json:"title"`Content string `json:"content"`diff --git a/plugin/advisor/mysql/advisor_naming_index_convention.go b/plugin/advisor/mysql/advisor_naming_index_convention.goindex 978076c205..f5da2ae1fb 100644--- a/plugin/advisor/mysql/advisor_naming_index_convention.go+++ b/plugin/advisor/mysql/advisor_naming_index_convention.go@@ -153,6 +153,9 @@ func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*ind)continue}+ if index == nil {+ continue+ }if index.Unique {// Unique index naming convention should in advisor_naming_unique_key_convention.gocontinuediff --git a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go b/plugin/advisor/mysql/advisor_naming_unique_key_convention.goindex 9120e16219..524921bf94 100644--- a/plugin/advisor/mysql/advisor_naming_unique_key_convention.go+++ b/plugin/advisor/mysql/advisor_naming_unique_key_convention.go@@ -146,6 +146,9 @@ func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexM)continue}+ if index == nil {+ continue+ }if !index.Unique {// Index naming convention should in advisor_naming_index_convention.gocontinuediff --git a/server/acl.go b/server/acl.goindex e9391f3a2a..db49569250 100644--- a/server/acl.go+++ b/server/acl.go@@ -35,6 +35,10 @@ func aclMiddleware(s *Server, ce *casbin.Enforcer, next echo.HandlerFunc, readonif common.HasPrefixes(c.Path(), "/api/subscription") && method == "GET" {return next(c)}+ // Skip OpenAPI request+ if common.HasPrefixes(c.Path(), openAPIPrefix) {+ return next(c)+ }if readonly && method != "GET" {return echo.NewHTTPError(http.StatusMethodNotAllowed, "Server is in readonly mode")diff --git a/server/jwt.go b/server/jwt.goindex 579683e472..f396f1fb5f 100644--- a/server/jwt.go+++ b/server/jwt.go@@ -176,6 +176,10 @@ func JWTMiddleware(principalStore *store.Store, next echo.HandlerFunc, mode commif common.HasPrefixes(c.Path(), "/api/subscription") && method == "GET" {return next(c)}+ // Skip OpenAPI request+ if common.HasPrefixes(c.Path(), openAPIPrefix) {+ return next(c)+ }cookie, err := c.Cookie(accessTokenCookieName)if err != nil {diff --git a/server/openapi.go b/server/openapi.gonew file mode 100644index 0000000000..1b132b5cb5--- /dev/null+++ b/server/openapi.go@@ -0,0 +1,86 @@+package server++import (+ "context"+ "fmt"+ "net/http"+ "strings"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/advisor/catalog"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/labstack/echo/v4"+)++// catalogService is the catalog service for sql check api.+type catalogService struct{}++// FindIndex is the API message for find index in catalog.+// We will not connect to the user's database in the early version of sql check api+func (c *catalogService) FindIndex(ctx context.Context, find *catalog.IndexFind) (*catalog.Index, error) {+ return nil, nil+}++func (s *Server) registerOpenAPIRoutes(g *echo.Group) {+ g.GET("/sql/advise", s.sqlCheckController)+}++// sqlCheckController godoc+// @Summary Check the SQL statement.+// @Description Parse and check the SQL statement according to the schema review policy.+// @Accept */*+// @Tags Schema Review+// @Produce json+// @Param environment query string true "The environment name. Case sensitive"+// @Param statement query string true "The SQL statement"+// @Param databaseType query string true "The database type" Enums(MySQL, PostgreSQL, TiDB)+// @Success 200 {array} advisor.Advice+// @Failure 400 {object} echo.HTTPError+// @Failure 500 {object} echo.HTTPError+// @Router /sql/advise [get]+func (s *Server) sqlCheckController(c echo.Context) error {+ envName := c.QueryParams().Get("environment")+ if envName == "" {+ return echo.NewHTTPError(http.StatusBadRequest, "Missing required environment name")+ }++ statement := c.QueryParams().Get("statement")+ if statement == "" {+ return echo.NewHTTPError(http.StatusBadRequest, "Missing required SQL statement")+ }++ dbType := c.QueryParams().Get("databaseType")+ if dbType == "" {+ return echo.NewHTTPError(http.StatusBadRequest, "Missing required database type")+ }+ advisorDBType, err := api.ConvertToAdvisorDBType(db.Type(strings.ToUpper(dbType)))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Database %s is not support", dbType))+ }++ ctx := c.Request().Context()+ envList, err := s.store.FindEnvironment(ctx, &api.EnvironmentFind{+ Name: &envName,+ })+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to find environment %s", envName)).SetInternal(err)+ }+ if len(envList) != 1 {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Invalid environment %s", envName))+ }++ _, adviceList, err := s.sqlCheck(+ ctx,+ advisorDBType,+ "utf8mb4",+ "utf8mb4_general_ci",+ envList[0].ID,+ statement,+ &catalogService{},+ )+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to run sql check").SetInternal(err)+ }++ return c.JSON(http.StatusOK, adviceList)+}diff --git a/server/server.go b/server/server.goindex 0d8ddfd960..7b6732d451 100644--- a/server/server.go+++ b/server/server.go@@ -21,10 +21,12 @@ import ("github.com/labstack/echo/v4""github.com/labstack/echo/v4/middleware"scas "github.com/qiangmzsx/string-adapter/v2"+ echoSwagger "github.com/swaggo/echo-swagger""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log"+ _ "github.com/bytebase/bytebase/docs/openapi" // initial the swagger docenterpriseAPI "github.com/bytebase/bytebase/enterprise/api"enterpriseService "github.com/bytebase/bytebase/enterprise/service""github.com/bytebase/bytebase/metric"@@ -34,6 +36,9 @@ import ("github.com/bytebase/bytebase/store")+// openAPIPrefix is the API prefix for Bytebase OpenAPI+const openAPIPrefix = "/v1"+// Server is the Bytebase server.type Server struct {// Asynchronous runners.@@ -75,6 +80,25 @@ var casbinDBAPolicy string//go:embed acl_casbin_policy_developer.csvvar casbinDeveloperPolicy string+// Use following cmd to generate swagger doc+// swag init -g ./server.go -d ./server --output docs/openapi --parseDependency++// @title Bytebase OpenAPI+// @version 1.0+// @description The OpenAPI for bytebase.+// @termsOfService https://www.bytebase.com/terms++// @contact.name API Support+// @contact.url https://github.com/bytebase/bytebase/+// @contact.email [email protected]++// @license.name MIT+// @license.url https://github.com/bytebase/bytebase/blob/main/LICENSE++// @host localhost:8080+// @BasePath /v1/+// @schemes http+// NewServer creates a server.func NewServer(ctx context.Context, prof Profile) (*Server, error) {s := &Server{@@ -261,11 +285,13 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {}))}e.Use(recoverMiddleware)+ e.GET("/swagger/*", echoSwagger.WrapHandler)webhookGroup := e.Group("/hook")s.registerWebhookRoutes(webhookGroup)apiGroup := e.Group("/api")+ openAPIGroup := e.Group(openAPIPrefix)apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {return JWTMiddleware(s.store, next, prof.Mode, config.secret)@@ -310,6 +336,8 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {s.registerSubscriptionRoutes(apiGroup)s.registerSheetRoutes(apiGroup)s.registerSheetOrganizerRoutes(apiGroup)+ s.registerOpenAPIRoutes(openAPIGroup)+// Register healthz endpoint.e.GET("/healthz", func(c echo.Context) error {return c.String(http.StatusOK, "OK!\n")diff --git a/server/sql.go b/server/sql.goindex 27b45d12c7..d4a2a6b8e9 100644--- a/server/sql.go+++ b/server/sql.go@@ -18,6 +18,7 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/catalog""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util""github.com/bytebase/bytebase/store"@@ -159,9 +160,38 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {adviceList := []advisor.Advice{}if s.feature(api.FeatureSchemaReviewPolicy) && api.IsSchemaReviewSupported(instance.Engine) {- adviceLevel, adviceList, err = s.sqlCheck(ctx, instance, exec)+ dbType, err := api.ConvertToAdvisorDBType(instance.Engine)if err != nil {- return err+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to convert db type %v into advisor db type", instance.Engine))+ }++ databaseFind := &api.DatabaseFind{+ InstanceID: &instance.ID,+ Name: &exec.DatabaseName,+ }+ dbList, err := s.store.FindDatabase(ctx, databaseFind)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch database `%s` for instance ID: %d", exec.DatabaseName, instance.ID)).SetInternal(err)+ }+ if len(dbList) == 0 {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database `%s` for instance ID: %d not found", exec.DatabaseName, instance.ID))+ }+ if len(dbList) > 1 {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("There are multiple database `%s` for instance ID: %d", exec.DatabaseName, instance.ID))+ }+ db := dbList[0]++ adviceLevel, adviceList, err = s.sqlCheck(+ ctx,+ dbType,+ db.CharacterSet,+ db.Collation,+ instance.EnvironmentID,+ exec.Statement,+ store.NewCatalog(&db.ID, s.store),+ )+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to check schema review policy").SetInternal(err)}if adviceLevel == advisor.Error {@@ -761,77 +791,65 @@ func (s *Server) createSQLEditorQueryActivity(ctx context.Context, c echo.Contexreturn nil}-func (s *Server) sqlCheck(ctx context.Context, instance *api.Instance, exec *api.SQLExecute) (advisor.Status, []advisor.Advice, error) {- adviceLevel := advisor.Success+func (s *Server) sqlCheck(+ ctx context.Context,+ dbType advisor.DBType,+ dbCharacterSet string,+ dbCollation string,+ environmentID int,+ statement string,+ catalog catalog.Catalog,+) (advisor.Status, []advisor.Advice, error) {var adviceList []advisor.Advice- policy, err := s.store.GetNormalSchemaReviewPolicy(ctx, &api.PolicyFind{EnvironmentID: &instance.EnvironmentID})+ policy, err := s.store.GetNormalSchemaReviewPolicy(ctx, &api.PolicyFind{EnvironmentID: &environmentID})if err != nil {if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {- adviceLevel = advisor.Warn- adviceList = append(adviceList, advisor.Advice{- Status: advisor.Warn,- Code: advisor.NotFound,- Title: "Empty schema review policy or disabled",- Content: "",- })- } else {- return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch schema review policy by environment ID: %d", instance.EnvironmentID)).SetInternal(err)+ adviceList = []advisor.Advice{+ {+ Status: advisor.Warn,+ Code: advisor.NotFound,+ Title: "Schema review policy is not configured or disabled",+ Content: "",+ },+ }+ return advisor.Warn, adviceList, nil}+ return advisor.Error, nil, err}- if adviceLevel == advisor.Success {- databaseFind := &api.DatabaseFind{- InstanceID: &instance.ID,- Name: &exec.DatabaseName,- }- db, err := s.store.FindDatabase(ctx, databaseFind)- if err != nil {- return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch database `%s` for instance ID: %d", exec.DatabaseName, instance.ID)).SetInternal(err)- }- if len(db) == 0 {- return advisor.Error, nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database `%s` for instance ID: %d not found", exec.DatabaseName, instance.ID))- }- if len(db) > 1 {- return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("There are multiple database `%s` for instance ID: %d", exec.DatabaseName, instance.ID))- }-- dbType, err := api.ConvertToAdvisorDBType(instance.Engine)- if err != nil {- return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to convert db type %v into advisor db type", instance.Engine))- }- res, err := advisor.SchemaReviewCheck(ctx, exec.Statement, policy, advisor.SchemaReviewCheckContext{- Charset: db[0].CharacterSet,- Collation: db[0].Collation,- DbType: dbType,- Catalog: store.NewCatalog(&db[0].ID, s.store),- })- if err != nil {- return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to run schema review check").SetInternal(err)- }+ res, err := advisor.SchemaReviewCheck(ctx, statement, policy, advisor.SchemaReviewCheckContext{+ Charset: dbCharacterSet,+ Collation: dbCollation,+ DbType: dbType,+ Catalog: catalog,+ })+ if err != nil {+ return advisor.Error, nil, err+ }- for _, advice := range res {- switch advice.Status {- case advisor.Warn:- if adviceLevel != advisor.Error {- adviceLevel = advisor.Warn- }- case advisor.Error:- adviceLevel = advisor.Error- case advisor.Success:- continue+ adviceLevel := advisor.Success+ for _, advice := range res {+ switch advice.Status {+ case advisor.Warn:+ if adviceLevel != advisor.Error {+ adviceLevel = advisor.Warn}-- adviceList = append(adviceList, advice)+ case advisor.Error:+ adviceLevel = advisor.Error+ case advisor.Success:+ continue}- if len(adviceList) == 0 {- adviceList = append(adviceList, advisor.Advice{- Status: advisor.Success,- Code: advisor.Ok,- Title: "OK",- Content: "",- })- }+ adviceList = append(adviceList, advice)+ }++ if len(adviceList) == 0 {+ adviceList = append(adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })}return adviceLevel, adviceList, nil}diff --git a/store/environment.go b/store/environment.goindex 737730b601..45fa9e2e17 100644--- a/store/environment.go+++ b/store/environment.go@@ -305,6 +305,9 @@ func (s *Store) findEnvironmentImpl(ctx context.Context, tx *sql.Tx, find *api.Eif v := find.ID; v != nil {where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)}+ if v := find.Name; v != nil {+ where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)+ }if v := find.RowStatus; v != nil {where, args = append(where, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, *v)}