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 MigrationHistory
天舟e5cd36678c6a
diff --git a/api/instance.go b/api/instance.goindex 95194e5a1d..a00fbf4ac9 100644--- a/api/instance.go+++ b/api/instance.go@@ -110,6 +110,26 @@ type InstanceMigration struct {Error string `jsonapi:"attr,error"`}+// MigrationHistory is stored in the instance instead of our own data file, so the field+// format is a bit different from the standard format+type MigrationHistory struct {+ ID int `jsonapi:"primary,migrationHistory"`++ // Standard fields+ Creator string `jsonapi:"attr,creator"`+ CreatedTs int64 `jsonapi:"attr,createdTs"`+ Updater string `jsonapi:"attr,updater"`+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`++ // Domain specific fields+ Database string `jsonapi:"attr,database"`+ Type db.MigrationType `jsonapi:"attr,type"`+ Version string `jsonapi:"attr,version"`+ Description string `jsonapi:"attr,description"`+ Statement string `jsonapi:"attr,statement"`+ ExecutionDuration int `jsonapi:"attr,executionDuration"`+}+type InstanceService interface {// CreateInstance should also create the * database and the admin data source.CreateInstance(ctx context.Context, create *InstanceCreate) (*Instance, error)diff --git a/db/driver.go b/db/driver.goindex e2e1e46039..dccc044285 100644--- a/db/driver.go+++ b/db/driver.go@@ -137,6 +137,27 @@ func ParseMigrationInfo(fullPath string, baseDir string) (*MigrationInfo, error)return mi, nil}+type MigrationHistory struct {+ ID int++ Creator string+ CreatedTs int64+ Updater string+ UpdatedTs int64++ Namespace string+ Sequence int+ Type MigrationType+ Version string+ Description string+ Statement string+ ExecutionDuration int+}++type MigrationHistoryFind struct {+ Database *string+}+type Driver interface {open(config ConnectionConfig) (Driver, error)Ping(ctx context.Context) error@@ -150,6 +171,8 @@ type Driver interface {SetupMigrationIfNeeded(ctx context.Context) error// Execute migration will apply the statement and record the migration history on success.ExecuteMigration(ctx context.Context, m *MigrationInfo, statement string) error+ // Find the migration history list+ FindMigrationHistoryList(ctx context.Context, find *MigrationHistoryFind) ([]*MigrationHistory, error)}type ConnectionConfig struct {diff --git a/db/mysql.go b/db/mysql.goindex 280dc30a21..aef89389c1 100644--- a/db/mysql.go+++ b/db/mysql.go@@ -304,6 +304,71 @@ func (driver *MySQLDriver) ExecuteMigration(ctx context.Context, m *MigrationInfreturn nil}+func (driver *MySQLDriver) FindMigrationHistoryList(ctx context.Context, find *MigrationHistoryFind) ([]*MigrationHistory, error) {+ tx, err := driver.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()++ where, args := []string{"1 = 1"}, []interface{}{}+ if v := find.Database; v != nil {+ where, args = append(where, "namespace = ?"), append(args, *v)+ }++ rows, err := tx.QueryContext(ctx, `+ SELECT+ id,+ created_by,+ created_ts,+ updated_by,+ updated_ts,+ namespace,+ sequence,+ `+"`type`,"+`+ version,+ description,+ statement,+ execution_duration+ FROM bytebase.migration_history+ WHERE `+strings.Join(where, " AND "),+ args...,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ // Iterate over result set and deserialize rows into list.+ list := make([]*MigrationHistory, 0)+ for rows.Next() {+ var history MigrationHistory+ if err := rows.Scan(+ &history.ID,+ &history.Creator,+ &history.CreatedTs,+ &history.Updater,+ &history.UpdatedTs,+ &history.Namespace,+ &history.Sequence,+ &history.Type,+ &history.Version,+ &history.Description,+ &history.Statement,+ &history.ExecutionDuration,+ ); err != nil {+ return nil, err+ }++ list = append(list, &history)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }++ return list, nil+}+func findBaseline(ctx context.Context, tx *sql.Tx, namespace string) (bool, error) {args := []interface{}{namespace}row, err := tx.QueryContext(ctx, `diff --git a/frontend/src/components/MigrationHistoryTable.vue b/frontend/src/components/MigrationHistoryTable.vuenew file mode 100644index 0000000000..49259a9f32--- /dev/null+++ b/frontend/src/components/MigrationHistoryTable.vue@@ -0,0 +1,75 @@+<template>+ <BBTable+ :columnList="COLUMN_LIST"+ :dataSource="historyList"+ :showHeader="true"+ :leftBordered="true"+ :rightBordered="true"+ :rowClickable="false"+ >+ <template v-slot:body="{ rowData: history }">+ <BBTableCell :leftPadding="4" class="w-16 table-cell">+ {{ history.creator }}+ </BBTableCell>+ <BBTableCell class="w-16 table-cell">+ {{ humanizeTs(history.createdTs) }}+ </BBTableCell>+ <BBTableCell class="w-32 table-cell">+ {{ history.version }}+ </BBTableCell>+ <BBTableCell class="w-8 table-cell truncate">+ {{ history.statement }}+ </BBTableCell>+ <BBTableCell class="w-8 table-cell truncate">+ {{ history.description }}+ </BBTableCell>+ <BBTableCell class="w-16 table-cell">+ {{ secondsToString(history.executionDuration) }}+ </BBTableCell>+ </template>+ </BBTable>+</template>++<script lang="ts">+import { PropType } from "vue";+import { MigrationHistory } from "../types";+import { secondsToString } from "../utils";++const COLUMN_LIST = [+ {+ title: "Creator",+ },+ {+ title: "Created",+ },+ {+ title: "Version",+ },+ {+ title: "SQL",+ },+ {+ title: "Description",+ },+ {+ title: "Duration",+ },+];++export default {+ name: "MigrationHistoryTable",+ components: {},+ props: {+ historyList: {+ required: true,+ type: Object as PropType<MigrationHistory[]>,+ },+ },+ setup(props, ctx) {+ return {+ COLUMN_LIST,+ secondsToString,+ };+ },+};+</script>diff --git a/frontend/src/store/modules/instance.ts b/frontend/src/store/modules/instance.tsindex 422d4216f3..1c8ebc69c8 100644--- a/frontend/src/store/modules/instance.ts+++ b/frontend/src/store/modules/instance.ts@@ -1,20 +1,21 @@import axios from "axios";import {- InstanceId,+ empty,+ EMPTY_ID,+ Environment,+ EnvironmentId,Instance,InstanceCreate,+ InstanceId,+ InstanceMigration,+ InstancePatch,InstanceState,- ResourceObject,- Environment,- EnvironmentId,+ MigrationHistory,ResourceIdentifier,- unknown,- InstancePatch,+ ResourceObject,RowStatus,- empty,- EMPTY_ID,- InstanceMigration,SqlResultSet,+ unknown,} from "../../types";function convert(@@ -47,8 +48,16 @@ function convert(};}+function convertMigrationHistory(history: ResourceObject): MigrationHistory {+ return {+ ...(history.attributes as Omit<MigrationHistory, "id">),+ id: parseInt(history.id),+ };+}+const state: () => InstanceState = () => ({instanceById: new Map(),+ migrationHistoryListByIdAndDatabaseName: new Map(),});const getters = {@@ -95,6 +104,16 @@ const getters = {state.instanceById.get(instanceId) || (unknown("INSTANCE") as Instance));},++ migrationHistoryListByInstanceIdAndDatabaseName:+ (state: InstanceState) =>+ (instanceId: InstanceId, databaseName: string): MigrationHistory[] => {+ return (+ state.migrationHistoryListByIdAndDatabaseName.get(+ [instanceId, databaseName].join(".")+ ) || []+ );+ },};const actions = {@@ -211,6 +230,34 @@ const actions = {return rootGetters["sql/convert"](data);},++ async migrationHistory(+ { commit }: any,+ {+ instanceId,+ databaseName,+ }: {+ instanceId: InstanceId;+ databaseName: string;+ }+ ): Promise<MigrationHistory> {+ const data = (+ await axios.get(+ `/api/instance/${instanceId}/migration/history?database=${databaseName}`+ )+ ).data.data;+ const historyList = data.map((history: ResourceObject) => {+ return convertMigrationHistory(history);+ });++ commit("setMigrationHistoryListByInstanceIdAndDatabaseName", {+ instanceId,+ databaseName,+ historyList,+ });++ return historyList;+ },};const mutations = {@@ -236,6 +283,24 @@ const mutations = {deleteInstanceById(state: InstanceState, instanceId: InstanceId) {state.instanceById.delete(instanceId);},++ setMigrationHistoryListByInstanceIdAndDatabaseName(+ state: InstanceState,+ {+ instanceId,+ databaseName,+ historyList,+ }: {+ instanceId: InstanceId;+ databaseName: string;+ historyList: MigrationHistory[];+ }+ ) {+ state.migrationHistoryListByIdAndDatabaseName.set(+ [instanceId, databaseName].join("."),+ historyList+ );+ },};export default {diff --git a/frontend/src/types/id.ts b/frontend/src/types/id.tsindex 8d29b7d007..8091b70e15 100644--- a/frontend/src/types/id.ts+++ b/frontend/src/types/id.ts@@ -41,6 +41,8 @@ export type VCSId = IdType;export type RepositoryId = IdType;+export type MigrationHistoryId = IdType;+export type CommandId = IdType;export type CommandRegisterId = IdType;diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.tsindex 9dc58f4b56..ae44cfd8c2 100644--- a/frontend/src/types/instance.ts+++ b/frontend/src/types/instance.ts@@ -1,6 +1,6 @@import { RowStatus } from "./common";import { Environment } from "./environment";-import { EnvironmentId, InstanceId } from "./id";+import { EnvironmentId, InstanceId, MigrationHistoryId } from "./id";import { Principal } from "./principal";export type EngineType = "MYSQL";@@ -57,9 +57,25 @@ export type InstancePatch = {password?: string;};-export type InstanceMigrationStatus = "UNKNOWN" | "OK" | "NOT_EXIST";+export type MigrationStatus = "UNKNOWN" | "OK" | "NOT_EXIST";export type InstanceMigration = {- status: InstanceMigrationStatus;+ status: MigrationStatus;error: string;};++export type MigrationType = "BASELINE" | "SQL";++export type MigrationHistory = {+ id: MigrationHistoryId;+ creator: string;+ createdTs: number;+ updater: string;+ updatedTs: number;+ database: string;+ type: MigrationType;+ version: string;+ description: string;+ statement: string;+ executionDuration: number;+};diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.tsindex cc2908f607..1a30728c22 100644--- a/frontend/src/types/store.ts+++ b/frontend/src/types/store.ts@@ -1,4 +1,5 @@import { Activity } from "./activity";+import { ServerInfo } from "./actuator";import { Bookmark } from "./bookmark";import { Command } from "./common";import { Database } from "./database";@@ -6,27 +7,26 @@ import { DataSource } from "./dataSource";import { Environment } from "./environment";import {CommandId,+ DatabaseId,DataSourceId,InstanceId,IssueId,- ProjectId,PrincipalId,- DatabaseId,+ ProjectId,VCSId,} from "./id";-import { Instance } from "./instance";+import { Instance, MigrationHistory } from "./instance";import { Issue } from "./issue";+import { IssueSubscriber } from "./issueSubscriber";import { Member } from "./member";import { Message } from "./message";+import { Notification } from "./notification";import { PlanType } from "./plan";import { Principal } from "./principal";import { Project } from "./project";-import { Notification } from "./notification";+import { Repository } from "./repository";import { Table } from "./table";import { VCS } from "./vcs";-import { Repository } from "./repository";-import { ServerInfo } from "./actuator";-import { IssueSubscriber } from "./issueSubscriber";export interface ActuatorState {serverInfo?: ServerInfo;@@ -89,6 +89,8 @@ export interface EnvironmentState {export interface InstanceState {instanceById: Map<InstanceId, Instance>;+ // The key is a concatenation of instance id and database name+ migrationHistoryListByIdAndDatabaseName: Map<string, MigrationHistory[]>;}export interface DataSourceState {diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.tsindex 2b2051256e..f0e9dfebb9 100644--- a/frontend/src/utils/util.ts+++ b/frontend/src/utils/util.ts@@ -34,6 +34,10 @@ export function bytesToString(size: number): string {return size.toString() + " " + unitList[i];}+export function secondsToString(second: number): string {+ return moment.duration(second).humanize();+}+export function urlfy(str: string): string {let result = str.trim();if (result.search(/^http[s]?\:\/\//) == -1) {diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vueindex ce38bea13c..8c1b7e4d0d 100644--- a/frontend/src/views/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail.vue@@ -154,6 +154,11 @@:mode="'VIEW'":tableList="tableList.filter((item) => item.type == 'VIEW')"/>++ <div class="mt-6 text-lg leading-6 font-medium text-main mb-4">+ Migration History+ </div>+ <MigrationHistoryTable :historyList="migrationHistoryList" /></div><!-- Hide data source list for now, as we don't allow adding new data source after creating the database. -->@@ -319,6 +324,7 @@ import { useRouter } from "vue-router";import DataSourceTable from "../components/DataSourceTable.vue";import DataSourceConnectionPanel from "../components/DataSourceConnectionPanel.vue";import TableTable from "../components/TableTable.vue";+import MigrationHistoryTable from "../components/MigrationHistoryTable.vue";import MemberSelect from "../components/MemberSelect.vue";import ProjectSelect from "../components/ProjectSelect.vue";import { idFromSlug, isDBAOrOwner } from "../utils";@@ -349,6 +355,7 @@ export default {DataSourceConnectionPanel,DataSourceTable,TableTable,+ MigrationHistoryTable,MemberSelect,ProjectSelect,},@@ -363,6 +370,12 @@ export default {const currentUser = computed(() => store.getters["auth/currentUser"]());+ const database = computed(() => {+ return store.getters["database/databaseById"](+ idFromSlug(props.databaseSlug)+ );+ });+const prepareTableList = () => {store.dispatch("table/fetchTableListByDatabaseId",@@ -372,22 +385,31 @@ export default {watchEffect(prepareTableList);+ const prepareMigrationHistoryList = () => {+ store.dispatch("instance/migrationHistory", {+ instanceId: database.value.instance.id,+ databaseName: database.value.name,+ });+ };++ watchEffect(prepareMigrationHistoryList);+const hasDataSourceFeature = computed(() =>store.getters["plan/feature"]("bb.data-source"));- const database = computed(() => {- return store.getters["database/databaseById"](- idFromSlug(props.databaseSlug)- );- });-const tableList = computed(() => {return store.getters["table/tableListByDatabaseId"](idFromSlug(props.databaseSlug));});+ const migrationHistoryList = computed(() => {+ return store.getters[+ "instance/migrationHistoryListByInstanceIdAndDatabaseName"+ ](database.value.instance.id, database.value.name);+ });+const isCurrentUserDBAOrOwner = computed((): boolean => {return isDBAOrOwner(currentUser.value.role);});@@ -515,6 +537,7 @@ export default {state,database,tableList,+ migrationHistoryList,hasDataSourceFeature,isCurrentUserDBAOrOwner,allowChangeProject,diff --git a/frontend/src/views/InstanceDetail.vue b/frontend/src/views/InstanceDetail.vueindex 08dc99aef5..346c637d9a 100644--- a/frontend/src/views/InstanceDetail.vue+++ b/frontend/src/views/InstanceDetail.vue@@ -89,12 +89,12 @@ import InstanceForm from "../components/InstanceForm.vue";import {Instance,InstanceMigration,- InstanceMigrationStatus,+ MigrationStatus,SqlResultSet,} from "../types";interface LocalState {- migrationSetupStatus: InstanceMigrationStatus;+ migrationSetupStatus: MigrationStatus;showCreateMigrationSchemaModal: boolean;}diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex a7cd12d17d..bebb218189 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -22,6 +22,7 @@ p, DBA, /instance/{id}, GETp, DBA, /instance/{id}, PATCHp, DBA, /instance/{id}/migration, POSTp, DBA, /instance/{id}/migration/status, GET+p, DBA, /instance/{id}/migration/history, GETp, DBA, /database, POSTp, DBA, /database, GETp, DBA, /database/{id}, GETdiff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csvindex 3c968a273c..1479fe8d56 100644--- a/server/acl_casbin_policy_developer.csv+++ b/server/acl_casbin_policy_developer.csv@@ -17,6 +17,7 @@ p, DEVELOPER, /environment, GETp, DEVELOPER, /instance, GETp, DEVELOPER, /instance/{id}, GETp, DEVELOPER, /instance/{id}/migration/status, GET+p, DEVELOPER, /instance/{id}/migration/history, GETp, DEVELOPER, /instance/{id}, GETp, DEVELOPER, /database, POSTp, DEVELOPER, /database, GETdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex 5dced7548b..cd72ec6fec 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -26,6 +26,7 @@ p, OWNER, /instance/{id}, GETp, OWNER, /instance/{id}, PATCHp, OWNER, /instance/{id}/migration, POSTp, OWNER, /instance/{id}/migration/status, GET+p, OWNER, /instance/{id}/migration/history, GETp, OWNER, /database, POSTp, OWNER, /database, GETp, OWNER, /database/{id}, GETdiff --git a/server/instance.go b/server/instance.goindex b952e867b2..7bf6f6bdfc 100644--- a/server/instance.go+++ b/server/instance.go@@ -235,6 +235,62 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {}return nil})++ g.GET("/instance/:instanceId/migration/history", func(c echo.Context) error {+ id, err := strconv.Atoi(c.Param("instanceId"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceId"))).SetInternal(err)+ }++ instance, err := s.ComposeInstanceById(context.Background(), id)+ if err != nil {+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", id)).SetInternal(err)+ }++ historyList := []*api.MigrationHistory{}+ driver, err := db.Open(instance.Engine, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{+ Username: instance.Username,+ Password: instance.Password,+ Host: instance.Host,+ Port: instance.Port,+ })+ if err == nil {+ find := &db.MigrationHistoryFind{}+ databaseStr := c.QueryParams().Get("database")+ if databaseStr != "" {+ find.Database = &databaseStr+ }+ list, err := driver.FindMigrationHistoryList(context.Background(), find)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)+ }++ for _, entry := range list {+ historyList = append(historyList, &api.MigrationHistory{+ ID: entry.ID,+ Creator: entry.Creator,+ CreatedTs: entry.CreatedTs,+ Updater: entry.Updater,+ UpdatedTs: entry.UpdatedTs,+ Database: entry.Namespace,+ Type: entry.Type,+ Version: entry.Version,+ Description: entry.Description,+ Statement: entry.Statement,+ ExecutionDuration: entry.ExecutionDuration,+ })+ }+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, historyList); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal migration history response for instance: %v", instance.Name)).SetInternal(err)+ }+ return nil+ })}func (s *Server) ComposeInstanceById(ctx context.Context, id int) (*api.Instance, error) {