Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: allow the SQL check API connect to an existed database (#1824)

ecmadao95e877166856
diff --git a/api/instance.go b/api/instance.go
index 755cd94b79..1930a7733f 100644
--- a/api/instance.go
+++ b/api/instance.go
@@ -73,6 +73,10 @@ type InstanceFind struct {
// Related fields
EnvironmentID *int
+
+ // Domain specific fields
+ Host *string
+ Port *string
}
func (find *InstanceFind) String() string {
diff --git a/docs/openapi/docs.go b/docs/openapi/docs.go
index a568ed5e66..2655df81ce 100644
--- a/docs/openapi/docs.go
+++ b/docs/openapi/docs.go
@@ -41,14 +41,14 @@ const docTemplate = `{
"parameters": [
{
"type": "string",
- "description": "The environment name. Case sensitive",
+ "description": "The environment name. Case sensitive.",
"name": "environment",
"in": "query",
"required": true
},
{
"type": "string",
- "description": "The SQL statement",
+ "description": "The SQL statement.",
"name": "statement",
"in": "query",
"required": true
@@ -60,10 +60,27 @@ const docTemplate = `{
"TiDB"
],
"type": "string",
- "description": "The database type",
+ "description": "The database type. Required if the port, host and database name is not specified.",
"name": "databaseType",
- "in": "query",
- "required": true
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "description": "The instance host.",
+ "name": "host",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "description": "The instance port.",
+ "name": "port",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "description": "The database name in the instance.",
+ "name": "databaseName",
+ "in": "query"
}
],
"responses": {
diff --git a/docs/openapi/swagger.yaml b/docs/openapi/swagger.yaml
index c0ce196375..4d07df4b3b 100644
--- a/docs/openapi/swagger.yaml
+++ b/docs/openapi/swagger.yaml
@@ -38,24 +38,36 @@ paths:
description: Parse and check the SQL statement according to the schema review
policy.
parameters:
- - description: The environment name. Case sensitive
+ - description: The environment name. Case sensitive.
in: query
name: environment
required: true
type: string
- - description: The SQL statement
+ - description: The SQL statement.
in: query
name: statement
required: true
type: string
- - description: The database type
+ - description: The database type. Required if the port, host and database name
+ is not specified.
enum:
- MySQL
- PostgreSQL
- TiDB
in: query
name: databaseType
- required: true
+ type: string
+ - description: The instance host.
+ in: query
+ name: host
+ type: string
+ - description: The instance port.
+ in: query
+ name: port
+ type: string
+ - description: The database name in the instance.
+ in: query
+ name: databaseName
type: string
produces:
- application/json
diff --git a/server/openapi.go b/server/openapi.go
index afb7e6be1c..996a692e9e 100644
--- a/server/openapi.go
+++ b/server/openapi.go
@@ -11,9 +11,14 @@ import (
"github.com/bytebase/bytebase/plugin/advisor/catalog"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/metric"
+ "github.com/bytebase/bytebase/store"
"github.com/labstack/echo/v4"
)
+var (
+ _ catalog.Catalog = (*catalogService)(nil)
+)
+
// catalogService is the catalog service for sql check api.
type catalogService struct{}
@@ -33,9 +38,12 @@ func (s *Server) registerOpenAPIRoutes(g *echo.Group) {
// @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)
+// @Param environment query string true "The environment name. Case sensitive."
+// @Param statement query string true "The SQL statement."
+// @Param databaseType query string false "The database type. Required if the port, host and database name is not specified." Enums(MySQL, PostgreSQL, TiDB)
+// @Param host query string false "The instance host."
+// @Param port query string false "The instance port."
+// @Param databaseName query string false "The database name in the instance."
// @Success 200 {array} advisor.Advice
// @Failure 400 {object} echo.HTTPError
// @Failure 500 {object} echo.HTTPError
@@ -51,16 +59,34 @@ func (s *Server) sqlCheckController(c echo.Context) error {
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")
+ ctx := c.Request().Context()
+ var dbType db.Type
+ var catalog catalog.Catalog = &catalogService{}
+
+ databaseName := c.QueryParams().Get("databaseName")
+ host := c.QueryParams().Get("host")
+ port := c.QueryParams().Get("port")
+
+ if databaseName != "" && host != "" && port != "" {
+ database, err := s.findDatabase(ctx, host, port, databaseName)
+ if err != nil {
+ return err
+ }
+ dbType = database.Instance.Engine
+ catalog = store.NewCatalog(&database.ID, s.store)
+ } else {
+ databaseType := c.QueryParams().Get("databaseType")
+ if databaseType == "" {
+ return echo.NewHTTPError(http.StatusBadRequest, "Missing required database type")
+ }
+ dbType = db.Type(strings.ToUpper(databaseType))
}
- advisorDBType, err := api.ConvertToAdvisorDBType(db.Type(strings.ToUpper(dbType)))
+
+ advisorDBType, err := api.ConvertToAdvisorDBType(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,
})
@@ -78,7 +104,7 @@ func (s *Server) sqlCheckController(c echo.Context) error {
"utf8mb4_general_ci",
envList[0].ID,
statement,
- &catalogService{},
+ catalog,
)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to run sql check").SetInternal(err)
@@ -89,7 +115,7 @@ func (s *Server) sqlCheckController(c echo.Context) error {
Name: metricAPI.SQLAdviseAPIMetricName,
Value: 1,
Labels: map[string]string{
- "database_type": dbType,
+ "database_type": string(dbType),
"environment": envName,
},
})
@@ -97,3 +123,31 @@ func (s *Server) sqlCheckController(c echo.Context) error {
return c.JSON(http.StatusOK, adviceList)
}
+
+func (s *Server) findDatabase(ctx context.Context, host string, port string, databaseName string) (*api.Database, error) {
+ instanceList, err := s.store.FindInstance(ctx, &api.InstanceFind{
+ Host: &host,
+ Port: &port,
+ })
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find instance by host: %s, port: %s", host, port)).SetInternal(err)
+ }
+ if len(instanceList) == 0 {
+ return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Cannot find instance with host: %s, port: %s", host, port))
+ }
+
+ for _, instance := range instanceList {
+ databaseList, err := s.store.FindDatabase(ctx, &api.DatabaseFind{
+ InstanceID: &instance.ID,
+ Name: &databaseName,
+ })
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find database by name %s in instance %d", databaseName, instance.ID)).SetInternal(err)
+ }
+ if len(databaseList) != 0 {
+ return databaseList[0], nil
+ }
+ }
+
+ return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Cannot find database %s in instance %s:%s", databaseName, host, port))
+}
diff --git a/store/instance.go b/store/instance.go
index 25621d8869..51cd0f047a 100644
--- a/store/instance.go
+++ b/store/instance.go
@@ -581,6 +581,12 @@ func findInstanceQuery(find *api.InstanceFind) (string, []interface{}) {
if v := find.EnvironmentID; v != nil {
where, args = append(where, fmt.Sprintf("environment_id = $%d", len(args)+1)), append(args, *v)
}
+ if v := find.Host; v != nil {
+ where, args = append(where, fmt.Sprintf("host = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := find.Port; v != nil {
+ where, args = append(where, fmt.Sprintf("port = $%d", len(args)+1)), append(args, *v)
+ }
return strings.Join(where, " AND "), args
}