Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Implement sql/ping and use it in TestConnection button in the Instance detail panel
天舟b01d9ac0fc3f
diff --git a/backend/api/sql.go b/backend/api/sql.gonew file mode 100644index 0000000000..0bebf213c7--- /dev/null+++ b/backend/api/sql.go@@ -0,0 +1,23 @@+package api++import (+ "context"++ "github.com/bytebase/bytebase/db"+)++type SqlConfig struct {+ DBType db.Type `jsonapi:"attr,dbType"`+ Host string `jsonapi:"attr,host"`+ Port string `jsonapi:"attr,port"`+ Username string `jsonapi:"attr,username"`+ Password string `jsonapi:"attr,password"`+}++type SqlResultSet struct {+ Error string `jsonapi:"attr,error"`+}++type SqlService interface {+ Ping(ctx context.Context, config *SqlConfig) (*SqlResultSet, error)+}diff --git a/backend/db/driver.go b/backend/db/driver.gonew file mode 100644index 0000000000..daeec1a4cf--- /dev/null+++ b/backend/db/driver.go@@ -0,0 +1,72 @@+package db++import (+ "database/sql"+ "fmt"+ "sync"++ "github.com/bytebase/bytebase"+)++type Type string++const (+ Mysql Type = "MYSQL"+)++func (e Type) String() string {+ switch e {+ case Mysql:+ return "MYSQL"+ }+ return ""+}++var (+ driversMu sync.RWMutex+ drivers = make(map[Type]DriverFunc)+)++type DriverConfig struct {+ Logger *bytebase.Logger+}++type DriverFunc func(DriverConfig) Driver++type Driver interface {+ Open(config ConnectionConfig) (*sql.DB, error)+}++type ConnectionConfig struct {+ Host string+ Port string+ Username string+ Password string+}++// Register makes a database driver available by the provided type.+// If Register is called twice with the same name or if driver is nil,+// it panics.+func register(dbType Type, f DriverFunc) {+ driversMu.Lock()+ defer driversMu.Unlock()+ if f == nil {+ panic("db: Register driver is nil")+ }+ if _, dup := drivers[dbType]; dup {+ panic("db: Register called twice for driver " + dbType)+ }+ drivers[dbType] = f+}++// Open opens a database specified by its database driver type and connection config+func Open(dbType Type, driverConfig DriverConfig, connectionConfig ConnectionConfig) (*sql.DB, error) {+ driversMu.RLock()+ f, ok := drivers[dbType]+ driversMu.RUnlock()+ if !ok {+ return nil, fmt.Errorf("db: unknown driver %v", dbType)+ }++ return f(driverConfig).Open(connectionConfig)+}diff --git a/backend/db/mysql.go b/backend/db/mysql.gonew file mode 100644index 0000000000..d5cf0b28b7--- /dev/null+++ b/backend/db/mysql.go@@ -0,0 +1,41 @@+package db++import (+ "database/sql"+ "fmt"+ "strings"++ "github.com/bytebase/bytebase"++ _ "github.com/go-sql-driver/mysql"+)++func init() {+ register(Mysql, newDriver)+}++type MySQLDriver struct {+ l *bytebase.Logger+}++func newDriver(config DriverConfig) Driver {+ return &MySQLDriver{+ l: config.Logger,+ }+}++func (driver *MySQLDriver) Open(config ConnectionConfig) (*sql.DB, error) {+ protocol := "tcp"+ if strings.HasPrefix(config.Host, "/") {+ protocol = "unix"+ }++ dsn := fmt.Sprintf("%s:%s@%s(%s:%s)/", config.Username, config.Password, protocol, config.Host, config.Port)+ driver.l.Debugf("DSN: %s", dsn)+ db, err := sql.Open("mysql", dsn)+ if err != nil {+ panic(err)+ }++ return db, nil+}diff --git a/backend/go.mod b/backend/go.modindex a479c57096..4f893ada6f 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -5,6 +5,7 @@ go 1.16require (github.com/casbin/casbin/v2 v2.29.2github.com/dgrijalva/jwt-go v3.2.0+incompatible+ github.com/go-sql-driver/mysql v1.6.0 // indirectgithub.com/golang-migrate/migrate/v4 v4.14.1github.com/google/jsonapi v1.0.0github.com/labstack/echo/v4 v4.2.2diff --git a/backend/go.sum b/backend/go.sumindex 2f18848d7a..d26642f923 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -87,6 +87,8 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=github.com/go-sql-driver/mysql v1.4.0/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-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=github.com/gobuffalo/here v0.6.0/go.mod h1:wAG085dHOYqUpf+Ap+WOdrPTp5IYcDAs/x7PLa8Y5fM=github.com/gocql/gocql v0.0.0-20190301043612-f6df8288f9b4/go.mod h1:4Fw1eo5iaEhDUs8XyuhSVCVy52Jq3L+/3GJgYkwc+/0=diff --git a/backend/server/acl_casbin_policy_dba.csv b/backend/server/acl_casbin_policy_dba.csvindex bd3060e245..68437cdd95 100644--- a/backend/server/acl_casbin_policy_dba.csv+++ b/backend/server/acl_casbin_policy_dba.csv@@ -32,4 +32,5 @@ p, DBA, /activity/{id}, DELETE_SELFp, DBA, /bookmark, POSTp, DBA, /bookmark, GETp, DBA, /bookmark/{id}, DELETE_SELF-p, DBA, /pipeline/{pipelineId}/task/{taskId}/status, PATCH\ No newline at end of file+p, DBA, /pipeline/{pipelineId}/task/{taskId}/status, PATCH+p, DBA, /sql/ping, POST\ No newline at end of filediff --git a/backend/server/acl_casbin_policy_developer.csv b/backend/server/acl_casbin_policy_developer.csvindex b09ecbe0e6..0f9a7f4e6b 100644--- a/backend/server/acl_casbin_policy_developer.csv+++ b/backend/server/acl_casbin_policy_developer.csv@@ -29,3 +29,4 @@ p, DEVELOPER, /bookmark, POSTp, DEVELOPER, /bookmark, GETp, DEVELOPER, /bookmark/{id}, DELETE_SELFp, DEVELOPER, /pipeline/{pipelineId}/task/{taskId}/status, PATCH+p, DEVELOPER, /sql/ping, POSTdiff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csvindex adb2d5bf4a..37c4fab648 100644--- a/backend/server/acl_casbin_policy_owner.csv+++ b/backend/server/acl_casbin_policy_owner.csv@@ -38,3 +38,4 @@ p, OWNER, /bookmark, POSTp, OWNER, /bookmark, GETp, OWNER, /bookmark/{id}, DELETE_SELFp, OWNER, /pipeline/{pipelineId}/task/{taskId}/status, PATCH+p, OWNER, /sql/ping, POSTdiff --git a/backend/server/server.go b/backend/server/server.goindex 92e429c065..4092164225 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -132,6 +132,7 @@ func NewServer(logger *bytebase.Logger) *Server {s.registerTaskRoutes(g)s.registerActivityRoutes(g)s.registerBookmarkRoutes(g)+ s.registerSqlRoutes(g)return s}diff --git a/backend/server/sql.go b/backend/server/sql.gonew file mode 100644index 0000000000..eea792f8ec--- /dev/null+++ b/backend/server/sql.go@@ -0,0 +1,41 @@+package server++import (+ "context"+ "net/http"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/db"+ "github.com/google/jsonapi"+ "github.com/labstack/echo/v4"+)++func (s *Server) registerSqlRoutes(g *echo.Group) {+ g.POST("/sql/ping", func(c echo.Context) error {+ config := &api.SqlConfig{}+ if err := jsonapi.UnmarshalPayload(c.Request().Body, config); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql ping request").SetInternal(err)+ }++ db, err := db.Open(config.DBType, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{+ Username: config.Username,+ Password: config.Password,+ Host: config.Host,+ Port: config.Port,+ })+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to open database").SetInternal(err)+ }++ resultSet := &api.SqlResultSet{}+ if err = db.PingContext(context.Background()); err != nil {+ resultSet.Error = err.Error()+ }++ 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+ })+}diff --git a/backend/store/seed/0060_instance.sql b/backend/store/seed/0060_instance.sqlindex 9011118d3f..bdf9ca0bb2 100644--- a/backend/store/seed/0060_instance.sql+++ b/backend/store/seed/0060_instance.sql@@ -17,10 +17,10 @@ VALUES1001,1,5001,- 'ON - premise MySQL instance',- 'google.com',+ 'On-premise MySQL instance','localhost',- '3306'+ '127.0.0.1',+ '33060');INSERT INTOdiff --git a/backend/store/seed/0080_data_source.sql b/backend/store/seed/0080_data_source.sqlindex 1b3ee7e253..26b3bf3270 100644--- a/backend/store/seed/0080_data_source.sql+++ b/backend/store/seed/0080_data_source.sql@@ -21,8 +21,8 @@ VALUES7001,'Admin data source','ADMIN',- 'admin1',- 'adminpwd1'+ 'root',+ 'root');INSERT INTOdiff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vueindex f7e41b3279..3bdd823aab 100644--- a/frontend/src/components/InstanceForm.vue+++ b/frontend/src/components/InstanceForm.vue@@ -146,12 +146,7 @@ input[type="number"] {</p></div></div>- <div class="pt-4">- <button :disabled="!allowEdit" type="button" class="btn-normal">- Test Connection- </button>- </div>- <div class="pt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-3">+ <div class="pt-4 grid grid-cols-1 gap-y-4 gap-x-4 sm:grid-cols-3"><div class="sm:col-span-1 sm:col-start-1"><label for="username" class="textlabel block"> Username </label><!-- For mysql, username can be empty indicating anonymous user.@@ -227,6 +222,30 @@ input[type="number"] {/></div></div>+ <div class="pt-8 space-y-2">+ <div class="flex flex-row space-x-2">+ <button+ :disabled="!allowEdit"+ @click.prevent="testConnection"+ type="button"+ class="btn-normal whitespace-nowrap items-center"+ >+ Test Connection+ </button>+ <div+ v-if="state.connectionResult == 'OK'"+ class="flex items-center text-success"+ >+ {{ state.connectionResult }}+ </div>+ </div>+ <div+ v-if="state.connectionResult && state.connectionResult != 'OK'"+ class="flex items-center text-error"+ >+ {{ state.connectionResult }}+ </div>+ </div></div></div><!-- Action Button Group -->@@ -279,12 +298,16 @@ import {UNKNOWN_ID,Principal,InstancePatch,+ SqlConfig,+ SqlResultSet,} from "../types";+import { isEmpty } from "lodash";interface LocalState {originalInstance?: Instance;instance: Instance | InstanceCreate;showPassword: Boolean;+ connectionResult: string;}export default {@@ -323,6 +346,7 @@ export default {username: "root",},showPassword: false,+ connectionResult: "",});const allowCreate = computed(() => {@@ -426,6 +450,23 @@ export default {});};+ const testConnection = () => {+ const sqlConfig: SqlConfig = {+ dbType: "MYSQL",+ username: state.instance.username,+ password: state.instance.password,+ host: state.instance.host,+ port: state.instance.port,+ };+ store.dispatch("sql/ping", sqlConfig).then((resultSet: SqlResultSet) => {+ if (isEmpty(resultSet.error)) {+ state.connectionResult = "OK";+ } else {+ state.connectionResult = resultSet.error;+ }+ });+ };+return {state,allowCreate,@@ -435,6 +476,7 @@ export default {cancel,doCreate,doUpdate,+ testConnection,};},};diff --git a/frontend/src/main.ts b/frontend/src/main.tsindex be89ecd970..770bed3547 100644--- a/frontend/src/main.ts+++ b/frontend/src/main.ts@@ -107,7 +107,8 @@ axios.interceptors.request.use((request) => {!request.url!.startsWith("/api/issue") &&!request.url!.startsWith("/api/pipeline") &&!request.url!.startsWith("/api/activity") &&- !request.url!.startsWith("/api/bookmar"))+ !request.url!.startsWith("/api/bookmar") &&+ !request.url!.startsWith("/api/sql"))) {request.url = request.url!.replace("/api", "/mock");}diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.tsindex 581b2c7266..f407b381ee 100644--- a/frontend/src/store/index.ts+++ b/frontend/src/store/index.ts@@ -10,6 +10,7 @@ import project from "./modules/project";import instance from "./modules/instance";import dataSource from "./modules/dataSource";import database from "./modules/database";+import sql from "./modules/sql";import principal from "./modules/principal";import plan from "./modules/plan";import auth from "./modules/auth";@@ -42,6 +43,7 @@ export const store: Store<any> = createStore({instance,dataSource,database,+ sql,principal,plan,auth,diff --git a/frontend/src/store/modules/sql.ts b/frontend/src/store/modules/sql.tsnew file mode 100644index 0000000000..d1d4b3822a--- /dev/null+++ b/frontend/src/store/modules/sql.ts@@ -0,0 +1,34 @@+import axios from "axios";+import { ResourceObject, SqlResultSet, SqlConfig } from "../../types";++function convert(resultSet: ResourceObject): SqlResultSet {+ return {+ error: resultSet.attributes.error as string,+ };+}++const getters = {};++const actions = {+ async ping({ commit }: any, sqlConfig: SqlConfig) {+ const resultSet = (+ await axios.post(`/api/sql/ping`, {+ data: {+ type: "sqlConfig",+ attributes: sqlConfig,+ },+ })+ ).data.data;++ return convert(resultSet);+ },+};++const mutations = {};++export default {+ namespaced: true,+ getters,+ actions,+ mutations,+};diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 38042b5c60..59ade5a837 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -9,6 +9,7 @@ export * from "./pipeline";export * from "./instance";export * from "./database";export * from "./dataSource";+export * from "./sql";export * from "./bookmark";export * from "./activity";export * from "./message";diff --git a/frontend/src/types/sql.ts b/frontend/src/types/sql.tsnew file mode 100644index 0000000000..71dcd7019e--- /dev/null+++ b/frontend/src/types/sql.ts@@ -0,0 +1,14 @@+export type DBType = "MYSQL";++export type SqlConfig = {+ dbType: DBType;+ host: string;+ port?: string;+ // In mysql, username can be empty which means anonymous user+ username?: string;+ password?: string;+};++export type SqlResultSet = {+ error: string;+};