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: backend stub implementation for sql/execute (#244)
tianzhou3a3d9dfe5f44
diff --git a/api/sql.go b/api/sql.goindex 3391703179..b3f903727b 100644--- a/api/sql.go+++ b/api/sql.go@@ -22,6 +22,20 @@ type SQLSyncSchema struct {InstanceID int `jsonapi:"attr,instanceId"`}+// SQLExecute is the API message for execute SQL.+// For now, we only support readonly / SELECT.+type SQLExecute struct {+ InstanceID int `jsonapi:"attr,instanceId"`+ // For engines like MySQL, databaseName can be empty.+ DatabaseName string `jsonapi:"attr,databaseName"`+ Statement string `jsonapi:"attr,statement"`+ // For now, Readonly must be true+ Readonly bool `jsonapi:"attr,readonly"`+ // The maximum row count returned, only applicable to SELECT query.+ // Not enforced if limit <= 0.+ Limit int `jsonapi:"attr,limit"`+}+// SQLResultSet is the API message for SQL results.type SQLResultSet struct {// SQL operation may fail for connection issue and there is no proper http status code for it, so we return error in the response body.diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex 01c0309c21..5c28ca168a 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -384,6 +384,11 @@ func (driver *Driver) Execute(ctx context.Context, statement string, useTransactreturn err}+// Query queries a SQL statement.+func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([]interface{}, error) {+ return util.Query(ctx, driver.l, driver.db, statement, limit)+}+// NeedsSetupMigration returns whether it needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {const query = `diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex f33731cf4f..9b896b8152 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -352,6 +352,9 @@ type Driver interface {GetVersion(ctx context.Context) (string, error)SyncSchema(ctx context.Context) ([]*User, []*Schema, error)Execute(ctx context.Context, statement string, useTransaction bool) error+ // Used for execute readonly SELECT statement+ // limit is the maximum row count returned. No limit enforced if limit <= 0+ Query(ctx context.Context, statement string, limit int) ([]interface{}, error)// Migration related// Check whether we need to setup migration (e.g. creating/upgrading the migration related tables)diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 20230a7f69..c31a035474 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -541,6 +541,11 @@ func (driver *Driver) Execute(ctx context.Context, statement string, useTransactreturn err}+// Query queries a SQL statement.+func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([]interface{}, error) {+ return util.Query(ctx, driver.l, driver.db, statement, limit)+}+// NeedsSetupMigration returns whether it needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {const query = `diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex 1884c7be74..fc522168cb 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -530,6 +530,11 @@ func (driver *Driver) Execute(ctx context.Context, statement string, useTransactreturn err}+// Query queries a SQL statement.+func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([]interface{}, error) {+ return util.Query(ctx, driver.l, driver.db, statement, limit)+}+// NeedsSetupMigration returns whether it needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {exist, err := driver.hasBytebaseDatabase(ctx)diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex ed5e5d3137..7db551f70c 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -512,6 +512,11 @@ func (driver *Driver) Execute(ctx context.Context, statement string, useTransactreturn err}+// Query queries a SQL statement.+func (driver *Driver) Query(ctx context.Context, statement string, limit int) ([]interface{}, error) {+ return util.Query(ctx, driver.l, driver.db, statement, limit)+}+// NeedsSetupMigration returns whether it needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {exist, err := driver.hasBytebaseDatabase(ctx)diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex 3b407d04da..ed90eb6c1d 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -393,6 +393,83 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driverreturn insertedID, afterSchemaBuf.String(), nil}+// Query will execute a readonly / SELECT query.+func Query(ctx context.Context, l *zap.Logger, db *sql.DB, statement string, limit int) ([]interface{}, error) {+ // Not all sql engines support ReadOnly flag, so we will use tx rollback semantics to enforce readonly.+ tx, err := db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()++ rows, err := tx.QueryContext(ctx, statement)+ if err != nil {+ return nil, FormatErrorWithQuery(err, statement)+ }+ defer rows.Close()++ columnTypes, err := rows.ColumnTypes()+ if err != nil {+ return nil, formatError(err)+ }++ colCount := len(columnTypes)+ rowCount := 0+ resultSet := []interface{}{}+ for rows.Next() {+ scanArgs := make([]interface{}, colCount)+ for i, v := range columnTypes {+ switch v.DatabaseTypeName() {+ case "VARCHAR", "TEXT", "UUID", "TIMESTAMP":+ scanArgs[i] = new(sql.NullString)+ case "BOOL":+ scanArgs[i] = new(sql.NullBool)+ case "INT4":+ scanArgs[i] = new(sql.NullInt64)+ default:+ scanArgs[i] = new(sql.NullString)+ }+ }++ if err := rows.Scan(scanArgs...); err != nil {+ return nil, formatError(err)+ }++ rowData := map[string]interface{}{}+ for i, v := range columnTypes {+ if z, ok := (scanArgs[i]).(*sql.NullBool); ok {+ rowData[v.Name()] = z.Bool+ continue+ }+ if z, ok := (scanArgs[i]).(*sql.NullString); ok {+ rowData[v.Name()] = z.String+ continue+ }+ if z, ok := (scanArgs[i]).(*sql.NullInt64); ok {+ rowData[v.Name()] = z.Int64+ continue+ }+ if z, ok := (scanArgs[i]).(*sql.NullFloat64); ok {+ rowData[v.Name()] = z.Float64+ continue+ }+ if z, ok := (scanArgs[i]).(*sql.NullInt32); ok {+ rowData[v.Name()] = z.Int32+ continue+ }+ rowData[v.Name()] = scanArgs[i]+ }++ resultSet = append(resultSet, rowData)+ rowCount+++ if rowCount == limit {+ break+ }+ }++ return resultSet, nil+}+func findBaseline(ctx context.Context, dbType db.Type, tx *sql.Tx, namespace, tablePrefix string) (bool, error) {queryParams := &db.QueryParams{DatabaseType: dbType}queryParams.AddParam("namespace", namespace)diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex 831440a714..a911e84817 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -68,6 +68,7 @@ p, DBA, /pipeline/{pipelineID}/task/{taskID}/status, PATCHp, DBA, /pipeline/{pipelineID}/task/{taskID}/check, POSTp, DBA, /sql/ping, POSTp, DBA, /sql/syncschema, POST+p, DBA, /sql/execute, POSTp, DBA, /vcs, POSTp, DBA, /vcs, GETp, DBA, /vcs/{id}, GETdiff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csvindex e61c540dfb..a5f0e55bf3 100644--- a/server/acl_casbin_policy_developer.csv+++ b/server/acl_casbin_policy_developer.csv@@ -63,6 +63,7 @@ p, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}, PATCHp, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}/status, PATCHp, DEVELOPER, /pipeline/{pipelineID}/task/{taskID}/check, POSTp, DEVELOPER, /sql/ping, POST+p, DEVELOPER, /sql/execute, POSTp, DEVELOPER, /vcs, GETp, DEVELOPER, /vcs/{id}, GETp, DEVELOPER, /plan, GETdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex d72c2f4442..3a328bde70 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -73,6 +73,7 @@ p, OWNER, /pipeline/{pipelineID}/task/{taskID}/status, PATCHp, OWNER, /pipeline/{pipelineID}/task/{taskID}/check, POSTp, OWNER, /sql/ping, POSTp, OWNER, /sql/syncschema, POST+p, OWNER, /sql/execute, POSTp, OWNER, /vcs, POSTp, OWNER, /vcs, GETp, OWNER, /vcs/{id}, GETdiff --git a/server/sql.go b/server/sql.goindex 9c0124de9b..06c564b4dc 100644--- a/server/sql.go+++ b/server/sql.go@@ -2,6 +2,7 @@ package serverimport ("context"+ "encoding/json""fmt""net/http""time"@@ -91,6 +92,60 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {}return nil})++ g.POST("/sql/execute", func(c echo.Context) error {+ ctx := context.Background()+ exec := &api.SQLExecute{}+ if err := jsonapi.UnmarshalPayload(c.Request().Body, exec); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql execute request").SetInternal(err)+ }++ if exec.InstanceID == 0 {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql execute request, missing instanceId")+ }+ if len(exec.Statement) == 0 {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql execute request, missing sql statement")+ }+ if !exec.Readonly {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql execute request, only support readonly sql statement")+ }++ instance, err := s.composeInstanceByID(ctx, exec.InstanceID)+ if err != nil {+ if common.ErrorCode(err) == common.NotFound {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", exec.InstanceID))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", exec.InstanceID)).SetInternal(err)+ }++ resultSet := func() (resultSet *api.SQLResultSet) {+ resultSet = &api.SQLResultSet{}+ driver, err := getDatabaseDriver(ctx, instance, exec.DatabaseName, s.l)+ if err != nil {+ resultSet.Error = err.Error()+ return+ }++ rowSet, err := driver.Query(ctx, exec.Statement, exec.Limit)+ if err != nil {+ resultSet.Error = err.Error()+ return+ }++ if _, err = json.Marshal(rowSet); err != nil {+ resultSet.Error = err.Error()+ return+ }++ return+ }()++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, resultSet); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal sql result set response").SetInternal(err)+ }+ return nil+ })}func (s *Server) syncEngineVersionAndSchema(ctx context.Context, instance *api.Instance) (rs *api.SQLResultSet) {