Skip to content

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

Create migration schema on the instance before adding it into Bytebase

天舟4eca583394d9
diff --git a/backend/api/migration.go b/backend/api/migration.go
new file mode 100644
index 0000000000..86c74bb6e7
--- /dev/null
+++ b/backend/api/migration.go
@@ -0,0 +1,27 @@
+package api
+
+// Instance migration status
+type InstanceMigrationStatus string
+
+const (
+ InstanceMigrationUnknown InstanceMigrationStatus = "UNKNOWN"
+ InstanceMigrationOK InstanceMigrationStatus = "OK"
+ InstanceMigrationNotExist InstanceMigrationStatus = "NOT_EXIST"
+)
+
+func (e InstanceMigrationStatus) String() string {
+ switch e {
+ case InstanceMigrationUnknown:
+ return "UNKNOWN"
+ case InstanceMigrationOK:
+ return "OK"
+ case InstanceMigrationNotExist:
+ return "NOT_EXIST"
+ }
+ return "UNKNOWN"
+}
+
+type InstanceMigration struct {
+ Status InstanceMigrationStatus `jsonapi:"attr,status"`
+ Error string `jsonapi:"attr,error"`
+}
diff --git a/backend/api/sql.go b/backend/api/sql.go
index a7705c0200..1a297ceaf8 100644
--- a/backend/api/sql.go
+++ b/backend/api/sql.go
@@ -6,7 +6,7 @@ import (
"github.com/bytebase/bytebase/db"
)
-type SqlConfig struct {
+type ConnectionInfo struct {
DBType db.Type `jsonapi:"attr,dbType"`
Host string `jsonapi:"attr,host"`
Port string `jsonapi:"attr,port"`
@@ -24,5 +24,5 @@ type SqlResultSet struct {
}
type SqlService interface {
- Ping(ctx context.Context, config *SqlConfig) (*SqlResultSet, error)
+ Ping(ctx context.Context, config *ConnectionInfo) (*SqlResultSet, error)
}
diff --git a/backend/db/driver.go b/backend/db/driver.go
index d46fd0403d..febb55730e 100644
--- a/backend/db/driver.go
+++ b/backend/db/driver.go
@@ -57,6 +57,12 @@ type Driver interface {
Ping(ctx context.Context) error
SyncSchema(ctx context.Context) ([]*DBSchema, error)
Execute(ctx context.Context, sql string) (sql.Result, error)
+
+ // Migration related
+ // Check whether we need to setup migration (e.g. creating/upgrading the migration related tables)
+ NeedsSetupMigration(ctx context.Context) (bool, error)
+ // Create or upgrade migration related tables
+ SetupMigrationIfNeeded(ctx context.Context) error
}
type ConnectionConfig struct {
@@ -91,5 +97,14 @@ func Open(dbType Type, driverConfig DriverConfig, connectionConfig ConnectionCon
return nil, fmt.Errorf("db: unknown driver %v", dbType)
}
- return f(driverConfig).open(connectionConfig)
+ driver, err := f(driverConfig).open(connectionConfig)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := driver.Ping(context.Background()); err != nil {
+ return nil, err
+ }
+
+ return driver, nil
}
diff --git a/backend/db/mysql.go b/backend/db/mysql.go
index a1cd2b489c..78d9600ea9 100644
--- a/backend/db/mysql.go
+++ b/backend/db/mysql.go
@@ -3,6 +3,7 @@ package db
import (
"context"
"database/sql"
+ _ "embed"
"fmt"
"strings"
@@ -10,6 +11,9 @@ import (
"go.uber.org/zap"
)
+//go:embed mysql_schema.sql
+var migrationSchema string
+
var (
_ Driver = (*MySQLDriver)(nil)
)
@@ -36,7 +40,9 @@ func (driver *MySQLDriver) open(config ConnectionConfig) (Driver, error) {
protocol = "unix"
}
- dsn := fmt.Sprintf("%s:%s@%s(%s:%s)/%s", config.Username, config.Password, protocol, config.Host, config.Port, config.Database)
+ params := []string{"multiStatements=true"}
+
+ dsn := fmt.Sprintf("%s:%s@%s(%s:%s)/%s?%s", config.Username, config.Password, protocol, config.Host, config.Port, config.Database, strings.Join(params, "&"))
driver.l.Debug("Opening MySQL driver", zap.String("dsn", dsn))
db, err := sql.Open("mysql", dsn)
if err != nil {
@@ -155,3 +161,40 @@ func (driver *MySQLDriver) Execute(ctx context.Context, sql string) (sql.Result,
return tx.ExecContext(ctx, sql)
}
+
+func (driver *MySQLDriver) NeedsSetupMigration(ctx context.Context) (bool, error) {
+ rows, err := driver.db.QueryContext(ctx, `
+ SELECT
+ 1
+ FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = 'bytebase' AND TABLE_NAME = 'migration_history'`,
+ )
+ if err != nil {
+ return false, err
+ }
+ defer rows.Close()
+
+ if rows.Next() {
+ return false, nil
+ }
+
+ return true, nil
+}
+
+func (driver *MySQLDriver) SetupMigrationIfNeeded(ctx context.Context) error {
+ setup, err := driver.NeedsSetupMigration(ctx)
+ if err != nil {
+ return nil
+ }
+
+ if setup {
+ driver.l.Info("Bytebase migration schema not found, creating schema...")
+ if _, err := driver.Execute(ctx, migrationSchema); err != nil {
+ driver.l.Error("Failed to initialize migration schema.", zap.Error(err))
+ return err
+ }
+ driver.l.Info("Successfully created migration schema.")
+ }
+
+ return nil
+}
diff --git a/backend/migration/mysql_schema.sql b/backend/db/mysql_schema.sql
similarity index 100%
rename from backend/migration/mysql_schema.sql
rename to backend/db/mysql_schema.sql
diff --git a/backend/server/acl_casbin_policy_dba.csv b/backend/server/acl_casbin_policy_dba.csv
index 3591906e2a..429b157273 100644
--- a/backend/server/acl_casbin_policy_dba.csv
+++ b/backend/server/acl_casbin_policy_dba.csv
@@ -45,4 +45,6 @@ p, DBA, /vcs, GET
p, DBA, /vcs/{id}, GET
p, DBA, /vcs/{id}, PATCH
p, DBA, /vcs/{id}, DELETE
-p, DBA, /vcs/{id}/repository, GET
\ No newline at end of file
+p, DBA, /vcs/{id}/repository, GET
+p, DBA, /migration/instance/status, POST
+p, DBA, /migration/instance, POST
\ No newline at end of file
diff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csv
index f8ff165d42..29a0f6f1f5 100644
--- a/backend/server/acl_casbin_policy_owner.csv
+++ b/backend/server/acl_casbin_policy_owner.csv
@@ -51,3 +51,5 @@ p, OWNER, /vcs/{id}, GET
p, OWNER, /vcs/{id}, PATCH
p, OWNER, /vcs/{id}, DELETE
p, OWNER, /vcs/{id}/repository, GET
+p, OWNER, /migration/instance/status, POST
+p, OWNER, /migration/instance, POST
diff --git a/backend/server/migration.go b/backend/server/migration.go
new file mode 100644
index 0000000000..b776d8d9b5
--- /dev/null
+++ b/backend/server/migration.go
@@ -0,0 +1,77 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/db"
+ "github.com/google/jsonapi"
+ "github.com/labstack/echo/v4"
+)
+
+func (s *Server) registerMigrationRoutes(g *echo.Group) {
+ g.POST("/migration/instance", func(c echo.Context) error {
+ connectionInfo := &api.ConnectionInfo{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, connectionInfo); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted instance migration status request").SetInternal(err)
+ }
+
+ resultSet := &api.SqlResultSet{}
+ db, err := db.Open(connectionInfo.DBType, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
+ Username: connectionInfo.Username,
+ Password: connectionInfo.Password,
+ Host: connectionInfo.Host,
+ Port: connectionInfo.Port,
+ })
+ if err != nil {
+ resultSet.Error = err.Error()
+ } else {
+ if err := db.SetupMigrationIfNeeded(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, fmt.Sprintf("Failed to marshal migration setup status response for host:port: %v:%v", connectionInfo.Host, connectionInfo.Port)).SetInternal(err)
+ }
+ return nil
+ })
+
+ g.POST("/migration/instance/status", func(c echo.Context) error {
+ connectionInfo := &api.ConnectionInfo{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, connectionInfo); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted instance migration status request").SetInternal(err)
+ }
+
+ instanceMigration := &api.InstanceMigration{}
+ db, err := db.Open(connectionInfo.DBType, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
+ Username: connectionInfo.Username,
+ Password: connectionInfo.Password,
+ Host: connectionInfo.Host,
+ Port: connectionInfo.Port,
+ })
+ if err != nil {
+ instanceMigration.Status = api.InstanceMigrationUnknown
+ instanceMigration.Error = err.Error()
+ } else {
+ setup, err := db.NeedsSetupMigration(context.Background())
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to check migration setup status for host:port: %v:%v", connectionInfo.Host, connectionInfo.Port)).SetInternal(err)
+ }
+ if setup {
+ instanceMigration.Status = api.InstanceMigrationNotExist
+ } else {
+ instanceMigration.Status = api.InstanceMigrationOK
+ }
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, instanceMigration); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal migration setup status response for host:port: %v:%v", connectionInfo.Host, connectionInfo.Port)).SetInternal(err)
+ }
+ return nil
+ })
+}
diff --git a/backend/server/server.go b/backend/server/server.go
index 98c26415e1..187272e797 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -155,6 +155,7 @@ func NewServer(logger *zap.Logger) *Server {
s.registerBookmarkRoutes(apiGroup)
s.registerSqlRoutes(apiGroup)
s.registerVCSRoutes(apiGroup)
+ s.registerMigrationRoutes(apiGroup)
return s
}
diff --git a/backend/server/sql.go b/backend/server/sql.go
index df8788d631..080f26767d 100644
--- a/backend/server/sql.go
+++ b/backend/server/sql.go
@@ -15,16 +15,16 @@ import (
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 {
+ connectionInfo := &api.ConnectionInfo{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, connectionInfo); 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,
+ db, err := db.Open(connectionInfo.DBType, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
+ Username: connectionInfo.Username,
+ Password: connectionInfo.Password,
+ Host: connectionInfo.Host,
+ Port: connectionInfo.Port,
})
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Failed to open database").SetInternal(err)
diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vue
index aeb7102480..554d9ac6e0 100644
--- a/frontend/src/components/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm.vue
@@ -321,7 +321,7 @@ input[type="number"] {
type="button"
class="btn-primary ml-3 inline-flex justify-center py-2 px-4"
:disabled="!allowCreate"
- @click.prevent="doCreate(state.instance)"
+ @click.prevent="tryCreate"
>
Create
</button>
@@ -340,6 +340,21 @@ input[type="number"] {
</div>
</div>
</form>
+ <BBAlert
+ v-if="state.showCreateMigrationSchemaModal"
+ :style="'INFO'"
+ :okText="'Create'"
+ :title="'Create migration schema?'"
+ :description="'The migration schema does not exist on this instance and Bytebase needs to create it in order to manage schema migration.'"
+ @ok="
+ () => {
+ state.showCreateMigrationSchemaModal = false;
+ doCreateSchema();
+ }
+ "
+ @cancel="state.showCreateMigrationSchemaModal = false"
+ >
+ </BBAlert>
</template>
<script lang="ts">
@@ -357,8 +372,9 @@ import {
UNKNOWN_ID,
Principal,
InstancePatch,
- SqlConfig,
+ ConnectionInfo,
SqlResultSet,
+ InstanceMigration,
} from "../types";
import isEmpty from "lodash-es/isEmpty";
@@ -368,8 +384,9 @@ const GRANT_STATEMENT =
interface LocalState {
originalInstance?: Instance;
instance: Instance | InstanceCreate;
- showPassword: Boolean;
+ showPassword: boolean;
connectionResult: string;
+ showCreateMigrationSchemaModal: boolean;
}
export default {
@@ -410,6 +427,7 @@ export default {
},
showPassword: false,
connectionResult: "",
+ showCreateMigrationSchemaModal: false,
});
const allowCreate = computed(() => {
@@ -436,6 +454,55 @@ export default {
emit("dismiss");
};
+ const doCreateSchema = () => {
+ const connectionInfo: ConnectionInfo = {
+ dbType: "MYSQL",
+ username: state.instance.username,
+ password: state.instance.password,
+ host: state.instance.host,
+ port: state.instance.port,
+ };
+ store
+ .dispatch("migration/createkMigrationSetup", connectionInfo)
+ .then((resultSet: SqlResultSet) => {
+ if (resultSet.error) {
+ state.connectionResult = resultSet.error;
+ } else {
+ doCreate();
+ }
+ });
+ };
+
+ // We will first check if migration schema exists on the instance.
+ // If it doesn't, we will ask user to allow Bytebase to create that schema before proceeding to creating the instance.
+ const tryCreate = () => {
+ const connectionInfo: ConnectionInfo = {
+ dbType: "MYSQL",
+ username: state.instance.username,
+ password: state.instance.password,
+ host: state.instance.host,
+ port: state.instance.port,
+ };
+ store
+ .dispatch("migration/checkMigrationSetup", connectionInfo)
+ .then((migration: InstanceMigration) => {
+ switch (migration.status) {
+ case "UNKNOWN": {
+ state.connectionResult = migration.error;
+ break;
+ }
+ case "NOT_EXIST": {
+ state.showCreateMigrationSchemaModal = true;
+ break;
+ }
+ case "OK": {
+ doCreate();
+ break;
+ }
+ }
+ });
+ };
+
// We will also create the database * denoting all databases
// and its RW data source. The username, password is actually
// stored in that data source object instead of in the instance self.
@@ -444,9 +511,9 @@ export default {
// in order to display the relevant info. In those cases, we don't want to include sensitive
// info such as username/password there. It's harder to redact this on the instance. Thus the
// only option is to split those information into a separate resource which won't be pulled together.
- const doCreate = async (newInstance: InstanceCreate) => {
+ const doCreate = () => {
store
- .dispatch("instance/createInstance", newInstance)
+ .dispatch("instance/createInstance", state.instance)
.then((createdInstance) => {
emit("dismiss");
@@ -517,20 +584,22 @@ export default {
};
const testConnection = () => {
- const sqlConfig: SqlConfig = {
+ const connectionInfo: ConnectionInfo = {
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;
- }
- });
+ store
+ .dispatch("sql/ping", connectionInfo)
+ .then((resultSet: SqlResultSet) => {
+ if (isEmpty(resultSet.error)) {
+ state.connectionResult = "OK";
+ } else {
+ state.connectionResult = resultSet.error;
+ }
+ });
};
return {
@@ -541,6 +610,8 @@ export default {
valueChanged,
updateInstance,
cancel,
+ doCreateSchema,
+ tryCreate,
doCreate,
doUpdate,
copyGrantStatement,
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index 6197311590..eceb6d0040 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -31,6 +31,9 @@ import router from "./modules/router";
import command from "./modules/command";
import notification from "./modules/notification";
+// migration module
+import migration from "./modules/migration";
+
// Debug module
import debug from "./modules/debug";
@@ -63,6 +66,7 @@ export const store: Store<any> = createStore({
router,
command,
notification,
+ migration,
debug,
},
strict: !isProd,
diff --git a/frontend/src/store/modules/migration.ts b/frontend/src/store/modules/migration.ts
new file mode 100644
index 0000000000..31bfed57f8
--- /dev/null
+++ b/frontend/src/store/modules/migration.ts
@@ -0,0 +1,50 @@
+import axios from "axios";
+import { ConnectionInfo, InstanceMigration, SqlResultSet } from "../../types";
+
+const getters = {};
+
+const actions = {
+ async checkMigrationSetup(
+ {}: any,
+ connectionInfo: ConnectionInfo
+ ): Promise<InstanceMigration> {
+ const data = (
+ await axios.post(`/api/migration/instance/status`, {
+ data: {
+ type: "connectionInfo",
+ attributes: connectionInfo,
+ },
+ })
+ ).data.data;
+
+ return {
+ status: data.attributes.status,
+ error: data.attributes.error,
+ };
+ },
+
+ async createkMigrationSetup(
+ { rootGetters }: any,
+ connectionInfo: ConnectionInfo
+ ): Promise<SqlResultSet> {
+ const data = (
+ await axios.post(`/api/migration/instance`, {
+ data: {
+ type: "connectionInfo",
+ attributes: connectionInfo,
+ },
+ })
+ ).data.data;
+
+ return rootGetters["sql/convert"](data);
+ },
+};
+
+const mutations = {};
+
+export default {
+ namespaced: true,
+ getters,
+ actions,
+ mutations,
+};
diff --git a/frontend/src/store/modules/sql.ts b/frontend/src/store/modules/sql.ts
index 4e985aa7da..abef6324e6 100644
--- a/frontend/src/store/modules/sql.ts
+++ b/frontend/src/store/modules/sql.ts
@@ -2,7 +2,7 @@ import axios from "axios";
import {
ResourceObject,
SqlResultSet,
- SqlConfig,
+ ConnectionInfo,
InstanceId,
} from "../../types";
@@ -12,15 +12,21 @@ function convert(resultSet: ResourceObject): SqlResultSet {
};
}
-const getters = {};
+const getters = {
+ convert:
+ () =>
+ (resultSet: ResourceObject): SqlResultSet => {
+ return convert(resultSet);
+ },
+};
const actions = {
- async ping({ commit }: any, sqlConfig: SqlConfig) {
+ async ping({ commit }: any, connectionInfo: ConnectionInfo) {
const data = (
await axios.post(`/api/sql/ping`, {
data: {
- type: "sqlConfig",
- attributes: sqlConfig,
+ type: "connectionInfo",
+ attributes: connectionInfo,
},
})
).data.data;
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 1d6c8dac84..fc07a6ced2 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -23,3 +23,5 @@ export * from "./store";
export * from "./oauth";
export * from "./jsonapi";
+
+export * from "./migration";
diff --git a/frontend/src/types/migration.ts b/frontend/src/types/migration.ts
new file mode 100644
index 0000000000..f4072b6668
--- /dev/null
+++ b/frontend/src/types/migration.ts
@@ -0,0 +1,6 @@
+export type InstanceMigrationStatus = "UNKNOWN" | "OK" | "NOT_EXIST";
+
+export type InstanceMigration = {
+ status: InstanceMigrationStatus;
+ error: string;
+};
diff --git a/frontend/src/types/sql.ts b/frontend/src/types/sql.ts
index 71dcd7019e..481baf5c55 100644
--- a/frontend/src/types/sql.ts
+++ b/frontend/src/types/sql.ts
@@ -1,6 +1,6 @@
export type DBType = "MYSQL";
-export type SqlConfig = {
+export type ConnectionInfo = {
dbType: DBType;
host: string;
port?: string;