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: initial the sql review service (#2057)
ecmadao02a4fc22444b
diff --git a/.gitignore b/.gitignoreindex 4708a181f2..e99537ba34 100644--- a/.gitignore+++ b/.gitignore@@ -36,5 +36,5 @@ bytebase-builddist/docs/openapi/swagger.json-frontend/src/types/sql-review.mysql.dev.yaml-frontend/src/types/sql-review.mysql.prod.yaml+docs/sqlservice/swagger.json+frontend/src/types/sql-review.*.yamldiff --git a/bin/sql-service/README.md b/bin/sql-service/README.mdnew file mode 100644index 0000000000..32a3d5428f--- /dev/null+++ b/bin/sql-service/README.md@@ -0,0 +1,3 @@+# Bytebase SQL Service++The API service for Bytebase SQL Reviewdiff --git a/bin/sql-service/cmd/profile_dev.go b/bin/sql-service/cmd/profile_dev.gonew file mode 100644index 0000000000..ce1d94c123--- /dev/null+++ b/bin/sql-service/cmd/profile_dev.go@@ -0,0 +1,21 @@+//go:build !release+// +build !release++package cmd++import (+ "github.com/bytebase/bytebase/common"+ server "github.com/bytebase/bytebase/sql-server"+)++func activeProfile() server.Profile {+ return server.Profile{+ Mode: common.ReleaseModeDev,+ BackendHost: flags.host,+ BackendPort: flags.port,+ Debug: flags.debug,+ Version: version,+ GitCommit: gitcommit,+ MetricConnectionKey: "",+ }+}diff --git a/bin/sql-service/cmd/profile_release.go b/bin/sql-service/cmd/profile_release.gonew file mode 100644index 0000000000..183c6d3dae--- /dev/null+++ b/bin/sql-service/cmd/profile_release.go@@ -0,0 +1,21 @@+//go:build release+// +build release++package cmd++import (+ "github.com/bytebase/bytebase/common"+ server "github.com/bytebase/bytebase/sql-server"+)++func activeProfile() server.Profile {+ return server.Profile{+ Mode: common.ReleaseModeProd,+ BackendHost: flags.host,+ BackendPort: flags.port,+ Debug: flags.debug,+ Version: version,+ GitCommit: gitcommit,+ MetricConnectionKey: "",+ }+}diff --git a/bin/sql-service/cmd/root.go b/bin/sql-service/cmd/root.gonew file mode 100644index 0000000000..e4ee070ac1--- /dev/null+++ b/bin/sql-service/cmd/root.go@@ -0,0 +1,142 @@+package cmd++import (+ "context"+ "fmt"+ "net/http"+ "os"+ "os/signal"+ "syscall"++ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/common/log"+ server "github.com/bytebase/bytebase/sql-server"+ "github.com/spf13/cobra"+ "go.uber.org/zap"++ // Register pingcap parser driver.+ _ "github.com/pingcap/tidb/types/parser_driver"+ // Register fake advisor.+ _ "github.com/bytebase/bytebase/plugin/advisor/fake"+ // Register mysql advisor.+ _ "github.com/bytebase/bytebase/plugin/advisor/mysql"+ // Register postgresql advisor.+ _ "github.com/bytebase/bytebase/plugin/advisor/pg"++ // Register postgres parser driver.+ _ "github.com/bytebase/bytebase/plugin/parser/engine/pg"+)++// -----------------------------------Global constant BEGIN----------------------------------------.+const (++ // greetingBanner is the greeting banner.+ // http://patorjk.com/software/taag/#p=display&f=ANSI%20Shadow&t=BB%20SQL%20Service+ greetingBanner = `+██████╗ ██████╗ ███████╗ ██████╗ ██╗ ███████╗███████╗██████╗ ██╗ ██╗██╗ ██████╗███████╗+██╔══██╗██╔══██╗ ██╔════╝██╔═══██╗██║ ██╔════╝██╔════╝██╔══██╗██║ ██║██║██╔════╝██╔════╝+██████╔╝██████╔╝ ███████╗██║ ██║██║ ███████╗█████╗ ██████╔╝██║ ██║██║██║ █████╗+██╔══██╗██╔══██╗ ╚════██║██║▄▄ ██║██║ ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║██║ ██╔══╝+██████╔╝██████╔╝ ███████║╚██████╔╝███████╗ ███████║███████╗██║ ██║ ╚████╔╝ ██║╚██████╗███████╗+╚═════╝ ╚═════╝ ╚══════╝ ╚══▀▀═╝ ╚══════╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═════╝╚══════╝++%s+___________________________________________________________________________________________++`+ // byeBanner is the bye banner.+ // http://patorjk.com/software/taag/#p=display&f=ANSI%20Shadow&t=BYE+ byeBanner = `+██████╗ ██╗ ██╗███████╗+██╔══██╗╚██╗ ██╔╝██╔════╝+██████╔╝ ╚████╔╝ █████╗+██╔══██╗ ╚██╔╝ ██╔══╝+██████╔╝ ██║ ███████╗+╚═════╝ ╚═╝ ╚══════╝++`+)++// -----------------------------------Command Line Config BEGIN------------------------------------.+var (+ flags struct {+ // Used for Bytebase command line config+ host string+ port int+ debug bool+ }+ rootCmd = &cobra.Command{+ Use: "sql",+ Short: "Bytebase SQL Service is the API service for Bytebase SQL Review",+ Run: func(_ *cobra.Command, _ []string) {+ start()++ fmt.Print(byeBanner)+ },+ }+)++// Execute executes the root command.+func Execute() error {+ return rootCmd.Execute()+}++func init() {+ rootCmd.PersistentFlags().StringVar(&flags.host, "host", "http://localhost", "host where Bytebase SQL service backend is accessed from, must start with http:// or https://.")+ rootCmd.PersistentFlags().IntVar(&flags.port, "port", 80, "port where Bytebase SQL service backend is accessed from.")+ rootCmd.PersistentFlags().BoolVar(&flags.debug, "debug", false, "whether to enable debug level logging")+}++// -----------------------------------Command Line Config END--------------------------------------++// -----------------------------------Main Entry Point---------------------------------------------++func start() {+ if flags.debug {+ log.SetLevel(zap.DebugLevel)+ }+ defer log.Sync()++ // check flags+ if !common.HasPrefixes(flags.host, "http://", "https://") {+ log.Error(fmt.Sprintf("--host %s must start with http:// or https://", flags.host))+ return+ }++ activeProfile := activeProfile()++ var s *server.Server+ // Setup signal handlers.+ ctx, cancel := context.WithCancel(context.Background())+ c := make(chan os.Signal, 1)+ // Trigger graceful shutdown on SIGINT or SIGTERM.+ // The default signal sent by the `kill` command is SIGTERM,+ // which is taken as the graceful shutdown signal for many systems, eg., Kubernetes, Gunicorn.+ signal.Notify(c, os.Interrupt, syscall.SIGTERM)+ go func() {+ sig := <-c+ log.Info(fmt.Sprintf("%s received.", sig.String()))+ if s != nil {+ _ = s.Shutdown(ctx)+ }+ cancel()+ }()++ s, err := server.NewServer(ctx, activeProfile)+ if err != nil {+ fmt.Printf("Cannot new server, error: %v\n", err)+ return+ }+ fmt.Printf(greetingBanner, fmt.Sprintf("Version %s has started at %s:%d", activeProfile.Version, activeProfile.BackendHost, activeProfile.BackendPort))+ // Execute program.+ if err := s.Run(); err != nil {+ if err != http.ErrServerClosed {+ log.Error(err.Error())+ _ = s.Shutdown(ctx)+ cancel()+ }+ }++ // Wait for CTRL-C.+ <-ctx.Done()+}diff --git a/bin/sql-service/cmd/version.go b/bin/sql-service/cmd/version.gonew file mode 100644index 0000000000..21cdbe765b--- /dev/null+++ b/bin/sql-service/cmd/version.go@@ -0,0 +1,30 @@+package cmd++import (+ "fmt"++ "github.com/spf13/cobra"+)++// These should be set via go build -ldflags -X 'xxxx'.+var version = "development"+var goversion = "unknown"+var gitcommit = "unknown"+var buildtime = "unknown"+var builduser = "unknown"++func init() {+ rootCmd.AddCommand(versionCmd)+}++var versionCmd = &cobra.Command{+ Use: "version",+ Short: "Print the version of Bytebase SQL service",+ Run: func(_ *cobra.Command, _ []string) {+ fmt.Printf("Bytebase SQL service version: %s\n", version)+ fmt.Printf("Golang version: %s\n", goversion)+ fmt.Printf("Git commit hash: %s\n", gitcommit)+ fmt.Printf("Built on: %s\n", buildtime)+ fmt.Printf("Built by: %s\n", builduser)+ },+}diff --git a/bin/sql-service/main.go b/bin/sql-service/main.gonew file mode 100644index 0000000000..e3fa786d62--- /dev/null+++ b/bin/sql-service/main.go@@ -0,0 +1,13 @@+package main++import (+ "os"++ "github.com/bytebase/bytebase/bin/sql-service/cmd"+)++func main() {+ if err := cmd.Execute(); err != nil {+ os.Exit(1)+ }+}diff --git a/docs/sqlservice/docs.go b/docs/sqlservice/docs.gonew file mode 100644index 0000000000..66e1b2ac49--- /dev/null+++ b/docs/sqlservice/docs.go@@ -0,0 +1,147 @@+// Package sqlservice GENERATED BY SWAG; DO NOT EDIT+// This file was generated by swaggo/swag+package sqlservice++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 rules.",+ "consumes": [+ "*/*"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Schema Review"+ ],+ "summary": "Check the SQL statement.",+ "parameters": [+ {+ "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+ },+ {+ "enum": [+ "bb.sql-review.mysql.prod",+ "bb.sql-review.mysql.dev"+ ],+ "type": "string",+ "description": "The SQL check template id. Required if the config is not specified.",+ "name": "template",+ "in": "query"+ },+ {+ "type": "string",+ "description": "The SQL check config override string in YAML format. Check https://github.com/bytebase/bytebase/tree/main/plugin/advisor/config/sql-review.override.yaml for example. Required if the template is not specified.",+ "name": "override",+ "in": "query"+ }+ ],+ "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:8081",+ BasePath: "/v1/",+ Schemes: []string{"http"},+ Title: "Bytebase SQL Service",+ Description: "The OpenAPI for Bytebase SQL Service.",+ InfoInstanceName: "swagger",+ SwaggerTemplate: docTemplate,+}++func init() {+ swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)+}diff --git a/docs/sqlservice/swagger.yaml b/docs/sqlservice/swagger.yamlnew file mode 100644index 0000000000..a33f2fb69d--- /dev/null+++ b/docs/sqlservice/swagger.yaml@@ -0,0 +1,89 @@+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:8081+info:+ contact:+ email: [email protected]+ name: API Support+ url: https://github.com/bytebase/bytebase/+ description: The OpenAPI for Bytebase SQL Service.+ license:+ name: MIT+ url: https://github.com/bytebase/bytebase/blob/main/LICENSE+ termsOfService: https://www.bytebase.com/terms+ title: Bytebase SQL Service+ version: "1.0"+paths:+ /sql/advise:+ get:+ consumes:+ - '*/*'+ description: Parse and check the SQL statement according to the schema review+ rules.+ parameters:+ - 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+ - description: The SQL check template id. Required if the config is not specified.+ enum:+ - bb.sql-review.mysql.prod+ - bb.sql-review.mysql.dev+ in: query+ name: template+ type: string+ - description: The SQL check config override string in YAML format. Check https://github.com/bytebase/bytebase/tree/main/plugin/advisor/config/sql-review.override.yaml+ for example. Required if the template is not specified.+ in: query+ name: override+ 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/plugin/advisor/config/sql-review.override.yaml b/plugin/advisor/config/sql-review.override.yamlnew file mode 100644index 0000000000..9922b6b0e7--- /dev/null+++ b/plugin/advisor/config/sql-review.override.yaml@@ -0,0 +1,14 @@+template: bb.sql-review.mysql.prod # Provide the template id, then we can extend rules from the specific template.+ruleList:+ - type: statement.select.no-select-all+ level: DISABLED+ - type: table.drop-naming-convention+ level: WARNING+ - type: table.require-pk+ level: WARNING+ - type: naming.table+ payload:+ format: "^table_[a-z]+(_[a-z]+)*$"+ - type: naming.column+ payload:+ maxLength: 24diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 44e0e6a56b..8e775cdeb2 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -254,14 +254,14 @@ type SQLReviewCheckContext struct {Catalog catalog.Catalog}-// SchemaReviewCheck checks the statements with schema review policy.-func SchemaReviewCheck(statements string, policy *SQLReviewPolicy, checkContext SQLReviewCheckContext) ([]Advice, error) {+// SchemaReviewCheck checks the statements with schema review rules.+func SchemaReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext SQLReviewCheckContext) ([]Advice, error) {var result []Advicedatabase, err := checkContext.Catalog.GetDatabase(context.Background())if err != nil {return nil, fmt.Errorf("failed to get database information from catalog: %w", err)}- for _, rule := range policy.RuleList {+ for _, rule := range ruleList {if rule.Level == SchemaRuleLevelDisabled {continue}diff --git a/scripts/.air_sql_service.toml b/scripts/.air_sql_service.tomlnew file mode 100644index 0000000000..4fec81936a--- /dev/null+++ b/scripts/.air_sql_service.toml@@ -0,0 +1,24 @@+root = "."+tmp_dir = ".air"++[build]+ bin = "./.air/sql-service --port 8081"+ cmd = """+ go build -gcflags=all=\"-N -l\" \+ -ldflags " \+ -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.version=development' \+ -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.goversion=$(go version)' \+ -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.gitcommit=$(git rev-parse HEAD)' \+ -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.buildtime=$(date -u +"%Y-%m-%dT%H:%M:%SZ")' \+ -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.builduser=$(id -u -n)' \+ " \+ -o ./.air/sql-service ./bin/sql-service/main.go"""+ delay = 1000+ exclude_dir = [".air", "vendor", "frontend", "docs"]+ exclude_file = []+ exclude_regex = []+ exclude_unchanged = false+ follow_symlink = false+ send_interrupt = true+ kill_delay = 1000+ full_bin = ""diff --git a/server/sql.go b/server/sql.goindex 16a177962d..bd210a2866 100644--- a/server/sql.go+++ b/server/sql.go@@ -672,7 +672,7 @@ func (s *Server) sqlCheck(return advisor.Error, nil, err}- res, err := advisor.SchemaReviewCheck(statement, policy, advisor.SQLReviewCheckContext{+ res, err := advisor.SchemaReviewCheck(statement, policy.RuleList, advisor.SQLReviewCheckContext{Charset: dbCharacterSet,Collation: dbCollation,DbType: dbType,diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.goindex dd251e5e1a..536ecee960 100644--- a/server/task_check_executor_statement_advisor_composite.go+++ b/server/task_check_executor_statement_advisor_composite.go@@ -67,7 +67,7 @@ func (*TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context, servreturn nil, err}- adviceList, err := advisor.SchemaReviewCheck(payload.Statement, policy, advisor.SQLReviewCheckContext{+ adviceList, err := advisor.SchemaReviewCheck(payload.Statement, policy.RuleList, advisor.SQLReviewCheckContext{Charset: payload.Charset,Collation: payload.Collation,DbType: dbType,diff --git a/sql-server/advise.go b/sql-server/advise.gonew file mode 100644index 0000000000..eb0bbc8b6b--- /dev/null+++ b/sql-server/advise.go@@ -0,0 +1,157 @@+package sqlserver++import (+ "context"+ "fmt"+ "net/http"+ "strings"++ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/catalog"+ "github.com/labstack/echo/v4"+ "gopkg.in/yaml.v3"+)++var (+ _ catalog.Catalog = (*catalogService)(nil)+)++// catalogService is the catalog service for sql check api.+type catalogService struct{}++// GetDatabase is the API message in catalog.+// We will not connect to the user's database in the early version of sql check api.+func (*catalogService) GetDatabase(_ context.Context) (*catalog.Database, error) {+ return nil, nil+}++func (s *Server) registerAdvisorRoutes(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 rules.+// @Accept */*+// @Tags Schema Review+// @Produce json+// @Param statement query string true "The SQL statement."+// @Param databaseType query string true "The database type." Enums(MySQL, PostgreSQL, TiDB)+// @Param template query string false "The SQL check template id. Required if the config is not specified." Enums(bb.sql-review.mysql.prod, bb.sql-review.mysql.dev)+// @Param override query string false "The SQL check config override string in YAML format. Check https://github.com/bytebase/bytebase/tree/main/plugin/advisor/config/sql-review.override.yaml for example. Required if the template is not specified."+// @Success 200 {array} advisor.Advice+// @Failure 400 {object} echo.HTTPError+// @Failure 500 {object} echo.HTTPError+// @Router /sql/advise [get].+func (*Server) sqlCheckController(c echo.Context) error {+ statement := c.QueryParams().Get("statement")+ if statement == "" {+ return echo.NewHTTPError(http.StatusBadRequest, "Missing required SQL statement")+ }++ databaseType := c.QueryParams().Get("databaseType")+ if databaseType == "" {+ return echo.NewHTTPError(http.StatusBadRequest, "Missing required database type")+ }+ advisorDBType, err := convertToAdvisorDBType(strings.ToUpper(databaseType))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Database %s is not support", databaseType))+ }++ template := c.QueryParams().Get("template")+ configOverrideYAMLStr := c.QueryParams().Get("override")+ if template == "" && configOverrideYAMLStr == "" {+ return echo.NewHTTPError(http.StatusBadRequest, "Missing required template or override")+ }++ ruleOverride := &advisor.SQLReviewConfigOverride{}+ if configOverrideYAMLStr != "" {+ if err := yaml.Unmarshal([]byte(configOverrideYAMLStr), ruleOverride); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid config: %v", configOverrideYAMLStr)).SetInternal(err)+ }+ if template != "" && string(ruleOverride.Template) != template {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("The config override should extend from the same template. Found %s in override but also get %s template in request.", ruleOverride.Template, template))+ }+ } else {+ ruleOverride.Template = advisor.SQLReviewTemplateID(template)+ }++ ruleList, err := advisor.MergeSQLReviewRules(ruleOverride)+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot merge the config for template: %s", ruleOverride.Template)).SetInternal(err)+ }++ adviceList, err := sqlCheck(+ advisorDBType,+ "utf8mb4",+ "utf8mb4_general_ci",+ statement,+ ruleList,+ &catalogService{},+ )+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to run sql check").SetInternal(err)+ }++ return c.JSON(http.StatusOK, adviceList)+}++func convertToAdvisorDBType(dbType string) (advisor.DBType, error) {+ switch dbType {+ case string(advisor.MySQL):+ return advisor.MySQL, nil+ case string(advisor.Postgres):+ return advisor.Postgres, nil+ case string(advisor.TiDB):+ return advisor.TiDB, nil+ }++ return "", fmt.Errorf("unsupported db type %s for advisor", dbType)+}++func sqlCheck(+ dbType advisor.DBType,+ dbCharacterSet string,+ dbCollation string,+ statement string,+ ruleList []*advisor.SQLReviewRule,+ catalog catalog.Catalog,+) ([]advisor.Advice, error) {+ var adviceList []advisor.Advice++ res, err := advisor.SchemaReviewCheck(statement, ruleList, advisor.SQLReviewCheckContext{+ Charset: dbCharacterSet,+ Collation: dbCollation,+ DbType: dbType,+ Catalog: catalog,+ })+ if err != nil {+ return nil, err+ }++ adviceLevel := advisor.Success+ 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+ }++ adviceList = append(adviceList, advice)+ }++ if len(adviceList) == 0 {+ adviceList = append(adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return adviceList, nil+}diff --git a/sql-server/profile.go b/sql-server/profile.gonew file mode 100644index 0000000000..bc072ca346--- /dev/null+++ b/sql-server/profile.go@@ -0,0 +1,21 @@+package sqlserver++import "github.com/bytebase/bytebase/common"++// Profile is the configuration to start main server.+type Profile struct {+ // Mode can be "prod" or "dev"+ Mode common.ReleaseMode+ // BackendHost is the listening backend host for server+ BackendHost string+ // BackendPort is the binding backend port for server.+ BackendPort int+ // Debug decides the log level+ Debug bool+ // Version is the bytebase's version+ Version string+ // Git commit hash of the build+ GitCommit string+ // MetricConnectionKey is the connection key for metric.+ MetricConnectionKey string+}diff --git a/sql-server/server.go b/sql-server/server.gonew file mode 100644index 0000000000..e81258461e--- /dev/null+++ b/sql-server/server.go@@ -0,0 +1,132 @@+package sqlserver++import (+ "context"+ "fmt"+ "net/http"+ "time"++ _ "github.com/bytebase/bytebase/docs/sqlservice" // initial the swagger doc+ echoSwagger "github.com/swaggo/echo-swagger"++ "github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/common/log"+ "github.com/labstack/echo-contrib/pprof"+ "github.com/labstack/echo-contrib/prometheus"+ "github.com/labstack/echo/v4"+ "github.com/labstack/echo/v4/middleware"+)++// Server is the Bytebase server.+type Server struct {+ profile Profile+ e *echo.Echo+ startedTs int64+}++// Use following cmd to generate swagger doc+// swag init -g ./server.go -d ./sql-server --output docs/sqlservice --parseDependency++// @title Bytebase SQL Service+// @version 1.0+// @description The OpenAPI for Bytebase SQL Service.+// @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:8081+// @BasePath /v1/+// @schemes http++// NewServer creates a server.+func NewServer(ctx context.Context, prof Profile) (*Server, error) {+ s := &Server{+ profile: prof,+ startedTs: time.Now().Unix(),+ }++ // Display config+ fmt.Println("-----Config BEGIN-----")+ fmt.Printf("mode=%s\n", prof.Mode)+ fmt.Printf("server=%s:%d\n", prof.BackendHost, prof.BackendPort)+ fmt.Printf("debug=%t\n", prof.Debug)+ fmt.Println("-----Config END-------")++ serverStarted := false+ defer func() {+ if !serverStarted {+ _ = s.Shutdown(ctx)+ }+ }()++ e := echo.New()+ e.Debug = prof.Debug+ // Disallow to be embedded in an iFrame.+ e.Use(middleware.SecureWithConfig(middleware.SecureConfig{+ XFrameOptions: "DENY",+ }))+ s.e = e++ // Middleware+ if prof.Mode == common.ReleaseModeDev || prof.Debug {+ e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{+ Skipper: func(c echo.Context) bool {+ return !common.HasPrefixes(c.Path(), "/v1")+ },+ Format: `{"time":"${time_rfc3339}",` ++ `"method":"${method}","uri":"${uri}",` ++ `"status":${status},"error":"${error}"}` + "\n",+ }))+ }+ e.Use(middleware.RecoverWithConfig(middleware.RecoverConfig{}))+ e.GET("/swagger/*", echoSwagger.WrapHandler)++ apiGroup := e.Group("/v1")+ s.registerAdvisorRoutes(apiGroup)++ // Register healthz endpoint.+ e.GET("/healthz", func(c echo.Context) error {+ return c.String(http.StatusOK, "OK!\n")+ })+ // Register pprof endpoints.+ pprof.Register(e)+ // Register prometheus metrics endpoint.+ p := prometheus.NewPrometheus("api", nil)+ p.Use(e)++ serverStarted = true+ return s, nil+}++// Run will run the server.+func (s *Server) Run() error {+ // Sleep for 1 sec to make sure port is released between runs.+ time.Sleep(time.Duration(1) * time.Second)++ return s.e.Start(fmt.Sprintf(":%d", s.profile.BackendPort))+}++// Shutdown will shut down the server.+func (s *Server) Shutdown(ctx context.Context) error {+ log.Info("Trying to stop Bytebase SQL Service ....")+ log.Info("Trying to gracefully shutdown server")++ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()++ // Shutdown echo+ if s.e != nil {+ if err := s.e.Shutdown(ctx); err != nil {+ s.e.Logger.Fatal(err)+ }+ }++ log.Info("Bytebase SQL Service stopped properly")++ return nil+}