Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: deprecate legacy migration history (#6424)
Danny Xu5ebcf1ce00d7
diff --git a/backend/legacyapi/data_source.go b/backend/legacyapi/data_source.goindex 41960d590f..fbf6517067 100644--- a/backend/legacyapi/data_source.go+++ b/backend/legacyapi/data_source.go@@ -87,32 +87,3 @@ type DataSource struct {Options DataSourceOptions `jsonapi:"attr,options"`Database string `jsonapi:"attr,database"`}--// DataSourceCreate is the API message for creating a data source.-type DataSourceCreate struct {- Name string `jsonapi:"attr,name"`- Type DataSourceType `jsonapi:"attr,type"`- Username string `jsonapi:"attr,username"`- Password string `jsonapi:"attr,password"`- SslCa string `jsonapi:"attr,sslCa"`- SslCert string `jsonapi:"attr,sslCert"`- SslKey string `jsonapi:"attr,sslKey"`- Host string `jsonapi:"attr,host"`- Port string `jsonapi:"attr,port"`- Options DataSourceOptions `jsonapi:"attr,options"`- Database string `jsonapi:"attr,database"`-}--// DataSourcePatch is the API message for data source.-type DataSourcePatch struct {- Username *string `jsonapi:"attr,username"`- Password *string `jsonapi:"attr,password"`- UseEmptyPassword *bool `jsonapi:"attr,useEmptyPassword"`- SslCa *string `jsonapi:"attr,sslCa"`- SslCert *string `jsonapi:"attr,sslCert"`- SslKey *string `jsonapi:"attr,sslKey"`- Host *string `jsonapi:"attr,host"`- Port *string `jsonapi:"attr,port"`- Options *DataSourceOptions `jsonapi:"attr,options"`- Database *string `jsonapi:"attr,database"`-}diff --git a/backend/legacyapi/database.go b/backend/legacyapi/database.goindex af3fa66e77..c0e4850c7a 100644--- a/backend/legacyapi/database.go+++ b/backend/legacyapi/database.go@@ -62,16 +62,6 @@ func (find *DatabaseFind) String() string {return string(str)}-// DatabasePatch is the API message for patching a database.-type DatabasePatch struct {- // Related fields- ProjectID *int `jsonapi:"attr,projectId"`-- // Labels is a json-encoded string from a list of DatabaseLabel,- // e.g. "[{"key":"bb.location","value":"earth"},{"key":"bb.tenant","value":"bytebase"}]".- Labels *string `jsonapi:"attr,labels"`-}-// DatabaseEdit is the API message for updating a database in UI editor.type DatabaseEdit struct {DatabaseID int `json:"databaseId"`diff --git a/backend/legacyapi/instance.go b/backend/legacyapi/instance.goindex 22e0d6468d..b113ed08bd 100644--- a/backend/legacyapi/instance.go+++ b/backend/legacyapi/instance.go@@ -31,40 +31,6 @@ type Instance struct {Password string}-// InstanceCreate is the API message for creating an instance.-type InstanceCreate struct {- ResourceID string `jsonapi:"attr,resourceId"`-- // Related fields- EnvironmentID int `jsonapi:"attr,environmentId"`-- // Domain specific fields- Name string `jsonapi:"attr,name"`- Engine db.Type `jsonapi:"attr,engine"`- ExternalLink string `jsonapi:"attr,externalLink"`- Host string `jsonapi:"attr,host"`- Port string `jsonapi:"attr,port"`- Database string `jsonapi:"attr,database"`- Username string `jsonapi:"attr,username"`- Password string `jsonapi:"attr,password"`- SslCa string `jsonapi:"attr,sslCa"`- SslCert string `jsonapi:"attr,sslCert"`- SslKey string `jsonapi:"attr,sslKey"`-- // SRV record is used for MongoDB only.- SRV bool `jsonapi:"attr,srv"`- // AuthenticationDatabase is used for MongoDB only.- AuthenticationDatabase string `jsonapi:"attr,authenticationDatabase"`- // SID and ServiceName are used for Oracle.- SID string `jsonapi:"attr,sid"`- ServiceName string `jsonapi:"attr,serviceName"`- SSHHost string `json:"sshHost" jsonapi:"attr,sshHost"`- SSHPort string `json:"sshPort" jsonapi:"attr,sshPort"`- SSHUser string `json:"sshUser" jsonapi:"attr,sshUser"`- SSHPassword string `json:"sshPassword" jsonapi:"attr,sshPassword"`- SSHPrivateKey string `json:"sshPrivateKey" jsonapi:"attr,sshPrivateKey"`-}-// InstanceFind is the API message for finding instances.type InstanceFind struct {ID *int@@ -80,72 +46,3 @@ func (find *InstanceFind) String() string {}return string(str)}--// InstancePatch is the API message for patching an instance.-type InstancePatch struct {- ID int `jsonapi:"primary,instancePatch"`-- // Standard fields- RowStatus *string `jsonapi:"attr,rowStatus"`- // Value is assigned from the jwt subject field passed by the client.- UpdaterID int-- // Domain specific fields- Name *string `jsonapi:"attr,name"`- EngineVersion *string- ExternalLink *string `jsonapi:"attr,externalLink"`- // TODO(zp): deprecate SRV and AuthenticationDatabase in InstancePatch.- // SRV record is used for MongoDB only.- SRV bool `jsonapi:"attr,srv"`- // AuthenticationDatabase is used for MongoDB only.- AuthenticationDatabase string `json:"authenticationDatabase" jsonapi:"attr,authenticationDatabase"`-}--// InstanceMigrationSchemaStatus is the schema status for instance migration.-type InstanceMigrationSchemaStatus string--const (- // InstanceMigrationSchemaUnknown is the UNKNOWN InstanceMigrationSchemaStatus.- InstanceMigrationSchemaUnknown InstanceMigrationSchemaStatus = "UNKNOWN"- // InstanceMigrationSchemaOK is the OK InstanceMigrationSchemaStatus.- InstanceMigrationSchemaOK InstanceMigrationSchemaStatus = "OK"- // InstanceMigrationSchemaNotExist is the NOT_EXIST InstanceMigrationSchemaStatus.- InstanceMigrationSchemaNotExist InstanceMigrationSchemaStatus = "NOT_EXIST"-)--// InstanceMigration is the API message for instance migration.-type InstanceMigration struct {- Status InstanceMigrationSchemaStatus `jsonapi:"attr,status"`- 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.-// TODO(p0ny): migrate to instance change history.-type MigrationHistory struct {- ID string `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- ReleaseVersion string `jsonapi:"attr,releaseVersion"`- Database string `jsonapi:"attr,database"`- Source db.MigrationSource `jsonapi:"attr,source"`- Type db.MigrationType `jsonapi:"attr,type"`- Status db.MigrationStatus `jsonapi:"attr,status"`- Version string `jsonapi:"attr,version"`- UseSemanticVersion bool `jsonapi:"attr,useSemanticVersion"`- SemanticVersionSuffix string `jsonapi:"attr,semanticVersionSuffix"`- Description string `jsonapi:"attr,description"`- Statement string `jsonapi:"attr,statement"`- Schema string `jsonapi:"attr,schema"`- SchemaPrev string `jsonapi:"attr,schemaPrev"`- ExecutionDurationNs int64 `jsonapi:"attr,executionDurationNs"`- // This is a string instead of int as the issue id may come from other issue tracking system in the future- IssueID string `jsonapi:"attr,issueId"`- Payload string `jsonapi:"attr,payload"`-}diff --git a/backend/legacyapi/label_test.go b/backend/legacyapi/label_test.godeleted file mode 100644index 094f5257f6..0000000000--- a/backend/legacyapi/label_test.go+++ /dev/null@@ -1,33 +0,0 @@-package api--import (- "bytes"- "encoding/json"- "testing"-- "github.com/google/jsonapi"- "github.com/stretchr/testify/require"-)--func TestUnmarshal(t *testing.T) {- b := []byte(`{- "data": {- "type": "databasePatch",- "attributes": {- "labels": "[{\"key\":\"bb.location\",\"value\":\"earth\"}]"- }- }- }`)- keys := []string{"bb.location", "bb.tenant"}- values := []string{"earth", "bytebase"}- databasePatch := &DatabasePatch{}- err := jsonapi.UnmarshalPayload(bytes.NewReader(b), databasePatch)- require.NoError(t, err)- var labels []*DatabaseLabel- err = json.Unmarshal([]byte(*databasePatch.Labels), &labels)- require.NoError(t, err)- for i, label := range labels {- require.Equal(t, keys[i], label.Key)- require.Equal(t, values[i], label.Value)- }-}diff --git a/backend/legacyapi/member.go b/backend/legacyapi/member.goindex b228d2e1d1..9be10dd62f 100644--- a/backend/legacyapi/member.go+++ b/backend/legacyapi/member.go@@ -29,33 +29,3 @@ const (// UnknownRole is the unknown role.UnknownRole Role = "UNKNOWN")--// Member is the API message for a member.-type Member struct {- ID int `jsonapi:"primary,member"`-- RowStatus RowStatus `jsonapi:"attr,rowStatus"`-- // Domain specific fields- Status MemberStatus `jsonapi:"attr,status"`- Role Role `jsonapi:"attr,role"`- PrincipalID int- Principal *Principal `jsonapi:"relation,principal"`-}--// MemberCreate is the API message for creating a member.-type MemberCreate struct {- // Domain specific fields- Role Role `jsonapi:"attr,role"`- PrincipalID int `jsonapi:"attr,principalId"`-}--// MemberPatch is the API message for patching a member.-type MemberPatch struct {- ID int-- // Standard fields- RowStatus *string `jsonapi:"attr,rowStatus"`- // Domain specific fields- Role *string `jsonapi:"attr,role"`-}diff --git a/backend/legacyapi/policy.go b/backend/legacyapi/policy.goindex 1fe239aedf..20091abc94 100644--- a/backend/legacyapi/policy.go+++ b/backend/legacyapi/policy.go@@ -113,26 +113,6 @@ type Policy struct {Payload string `jsonapi:"attr,payload"`}-// PolicyFind is the message to get a policy.-type PolicyFind struct {- ID *int-- // Related fields- ResourceType *PolicyResourceType- ResourceID *int-- // Domain specific fields- Type PolicyType `jsonapi:"attr,type"`-}--// PolicyUpsert is the message to upsert a policy.-// NOTE: We use PATCH for Upsert, this is inspired by https://google.aip.dev/134#patch-and-put-type PolicyUpsert struct {- RowStatus *string `jsonapi:"attr,rowStatus"`- InheritFromParent *bool `jsonapi:"attr,inheritFromParent"`- Payload *string `jsonapi:"attr,payload"`-}-// PipelineApprovalPolicy is the policy configuration for pipeline approval.type PipelineApprovalPolicy struct {Value PipelineApprovalValue `json:"value"`@@ -323,131 +303,6 @@ func UnmarshalEnvironmentTierPolicy(payload string) (*EnvironmentTierPolicy, errreturn &p, nil}-// ValidatePolicyType will validate the policy type.-func ValidatePolicyType(pType PolicyType) error {- if _, ok := AllowedResourceTypes[pType]; !ok {- return errors.Errorf("invalid policy type: %s", pType)- }- return nil-}--// ValidatePolicy will validate the policy resource type, type and payload values.-func ValidatePolicy(resourceType PolicyResourceType, pType PolicyType, payload *string) error {- hasResourceType := false- for _, rt := range AllowedResourceTypes[pType] {- if rt == resourceType {- hasResourceType = true- }- }- if !hasResourceType {- return errors.Errorf("invalid resource type %s and policy type %s pair", resourceType, pType)- }- // If payload is not changed, we will not check its content.- if payload == nil {- return nil- }-- switch pType {- case PolicyTypePipelineApproval:- pa, err := UnmarshalPipelineApprovalPolicy(*payload)- if err != nil {- return err- }- if pa.Value != PipelineApprovalValueManualNever && pa.Value != PipelineApprovalValueManualAlways {- return errors.Errorf("invalid approval policy value: %q", *payload)- }- issueTypeSeen := make(map[IssueType]bool)- for _, group := range pa.AssigneeGroupList {- if group.IssueType != IssueDatabaseSchemaUpdate &&- group.IssueType != IssueDatabaseSchemaUpdateGhost &&- group.IssueType != IssueDatabaseDataUpdate {- return errors.Errorf("invalid assignee group issue type %q", group.IssueType)- }- if issueTypeSeen[group.IssueType] {- return errors.Errorf("duplicate assignee group issue type %q", group.IssueType)- }- issueTypeSeen[group.IssueType] = true- }- return nil- case PolicyTypeBackupPlan:- bp, err := UnmarshalBackupPlanPolicy(*payload)- if err != nil {- return err- }- if bp.Schedule != BackupPlanPolicyScheduleUnset && bp.Schedule != BackupPlanPolicyScheduleDaily && bp.Schedule != BackupPlanPolicyScheduleWeekly {- return errors.Errorf("invalid backup plan policy schedule: %q", bp.Schedule)- }- return nil- case PolicyTypeSQLReview:- sr, err := UnmarshalSQLReviewPolicy(*payload)- if err != nil {- return err- }- if err := sr.Validate(); err != nil {- return errors.Wrap(err, "invalid SQL review policy")- }- return nil- case PolicyTypeEnvironmentTier:- p, err := UnmarshalEnvironmentTierPolicy(*payload)- if err != nil {- return err- }- if p.EnvironmentTier != EnvironmentTierValueProtected && p.EnvironmentTier != EnvironmentTierValueUnprotected {- return errors.Errorf("invalid environment tier value %q", p.EnvironmentTier)- }- return nil- case PolicyTypeSensitiveData:- p, err := UnmarshalSensitiveDataPolicy(*payload)- if err != nil {- return err- }- for _, v := range p.SensitiveDataList {- if v.Table == "" || v.Column == "" {- return errors.Errorf("sensitive data policy rule cannot have empty table or column name")- }- if v.Type != SensitiveDataMaskTypeDefault {- return errors.Errorf("sensitive data policy rule must have mask type %q", SensitiveDataMaskTypeDefault)- }- }- return nil- case PolicyTypeAccessControl:- if _, err := UnmarshalAccessControlPolicy(*payload); err != nil {- return err- }- return nil- }- return nil-}--// GetDefaultPolicy will return the default value for the given policy type.-// The default policy can be empty when we don't have anything to enforce at runtime.-func GetDefaultPolicy(pType PolicyType) (string, error) {- switch pType {- case PolicyTypePipelineApproval:- policy := PipelineApprovalPolicy{- Value: PipelineApprovalValueManualAlways,- }- return policy.String()- case PolicyTypeBackupPlan:- policy := BackupPlanPolicy{- Schedule: BackupPlanPolicyScheduleUnset,- }- return policy.String()- case PolicyTypeSQLReview:- // TODO(ed): we may need to define the default SQL review policy payload in the PR of policy data migration.- return "{}", nil- case PolicyTypeEnvironmentTier:- policy := EnvironmentTierPolicy{- EnvironmentTier: EnvironmentTierValueUnprotected,- }- return policy.String()- case PolicyTypeSensitiveData:- policy := SensitiveDataPolicy{}- return policy.String()- }- return "", nil-}-// GetPolicyResourceType gets the policy resource type.func GetPolicyResourceType(resourceType string) (PolicyResourceType, error) {var rt PolicyResourceTypediff --git a/backend/server/acl.go b/backend/server/acl.goindex f1d79ce3d4..301912dc20 100644--- a/backend/server/acl.go+++ b/backend/server/acl.go@@ -1,17 +1,14 @@package serverimport (- "bytes""context""fmt"- "io""net/http""regexp""strconv""strings""github.com/casbin/casbin/v2"- "github.com/google/jsonapi""github.com/pkg/errors""github.com/labstack/echo/v4"@@ -138,20 +135,6 @@ func aclMiddleware(s *Server, pathPrefix string, ce *casbin.Enforcer, next echo.aclErr = enforceWorkspaceDeveloperProjectRouteACL(s.licenseService.GetEffectivePlan(), path, method, principalID, projectRolesFinder)} else if strings.HasPrefix(path, "/sheet") {aclErr = enforceWorkspaceDeveloperSheetRouteACL(s.licenseService.GetEffectivePlan(), path, method, principalID, projectRolesFinder, sheetFinder)- } else if strings.HasPrefix(path, "/database") {- // We need to copy the body because it will be consumed by the next middleware.- // And TeeReader require us the write must complete before the read completes.- // The body under the /issue route is a JSON object, and always not too large, so using ioutil.ReadAll is fine here.- bodyBytes, err := io.ReadAll(c.Request().Body)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to read request body.").SetInternal(err)- }- if err := c.Request().Body.Close(); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to close request body.").SetInternal(err)- }- c.Request().Body = io.NopCloser(bytes.NewBuffer(bodyBytes))-- aclErr = enforceWorkspaceDeveloperDatabaseRouteACL(s.licenseService.GetEffectivePlan(), path, method, string(bodyBytes), principalID, getRetrieveDatabaseProjectID(ctx, s.store), projectRolesFinder)}if aclErr != nil {return aclErr@@ -207,63 +190,6 @@ func enforceWorkspaceDeveloperProjectRouteACL(plan api.PlanType, path string, mereturn nil}-var databaseGeneralRouteRegex = regexp.MustCompile(`^/database/(?P<databaseID>\d+)$`)--func enforceWorkspaceDeveloperDatabaseRouteACL(plan api.PlanType, path string, method string, body string, principalID int, projectIDOfDatabase func(databaseID int) (int, error), projectRolesFinder func(projectID int, principalID int) (map[common.ProjectRole]bool, error)) *echo.HTTPError {- switch method {- case http.MethodGet:- case http.MethodPatch:- // PATCH /database/xxx- if matches := databaseGeneralRouteRegex.FindStringSubmatch(path); len(matches) > 0 {- databaseID := matches[1]- databaseIDInt, err := strconv.Atoi(databaseID)- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Invalid database id").SetInternal(err)- }- oldProjectID, err := projectIDOfDatabase(databaseIDInt)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Cannot find project id for database %d", databaseIDInt)).SetInternal(err)- }- oldProjectRoles, err := projectRolesFinder(oldProjectID, principalID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Cannot find project member ids for project %d", oldProjectID)).SetInternal(err)- }- if plan == api.ENTERPRISE {- if _, ok := oldProjectRoles[common.ProjectOwner]; !ok {- return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("user is not project owner of project owns the database %d", databaseIDInt))- }- } else {- if len(oldProjectRoles) == 0 {- return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("user is not a project member of project owns the database %d", databaseIDInt))- }- }-- // Workspace developer can only modify the database belongs to the project which he is a member of.- var databasePatch api.DatabasePatch- if err := jsonapi.UnmarshalPayload(strings.NewReader(body), &databasePatch); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch database request").SetInternal(err)- }- // Workspace developer cannot transfer the project to the project that he is not a member of.- if databasePatch.ProjectID != nil {- newProjectRoles, err := projectRolesFinder(*databasePatch.ProjectID, principalID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Cannot find project member ids for project %d", *databasePatch.ProjectID)).SetInternal(err)- }- if plan == api.ENTERPRISE {- if _, ok := newProjectRoles[common.ProjectOwner]; !ok {- return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("user is not project owner of project want owns the database %d", databaseIDInt))- }- } else {- if len(newProjectRoles) == 0 {- return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("user is not a project member of project want to owns the database %d", databaseIDInt))- }- }- }- }- }- return nil-}-var sheetRouteRegex = regexp.MustCompile(`^/sheet/(?P<sheetID>\d+)`)var sheetOrganizeRouteRegex = regexp.MustCompile(`^/sheet/(?P<projectID>\d+)/organize`)@@ -344,30 +270,6 @@ func enforceWorkspaceDeveloperSheetRouteACL(plan api.PlanType, path string, methreturn nil}-func getRetrieveDatabaseProjectID(ctx context.Context, s *store.Store) func(databaseID int) (int, error) {- return func(databaseID int) (int, error) {- db, err := s.GetDatabaseV2(ctx, &store.FindDatabaseMessage{- UID: &databaseID,- })- if err != nil {- return 0, err- }- if db == nil {- return 0, errors.Errorf("cannot find database %d", databaseID)- }- project, err := s.GetProjectV2(ctx, &store.FindProjectMessage{- ResourceID: &db.ProjectID,- })- if err != nil {- return 0, err- }- if project == nil {- return 0, errors.Errorf("cannot find project %s", db.ProjectID)- }- return project.UID, nil- }-}-func isOperatingSelf(ctx context.Context, c echo.Context, s *Server, curPrincipalID int, method string, path string) (bool, error) {switch method {case http.MethodGet:diff --git a/backend/server/acl_database_test.go b/backend/server/acl_database_test.godeleted file mode 100644index c7a12e6fd0..0000000000--- a/backend/server/acl_database_test.go+++ /dev/null@@ -1,156 +0,0 @@-package server--import (- "testing"-- api "github.com/bytebase/bytebase/backend/legacyapi"-- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/common"-)--func TestEnforceWorkspaceDeveloperDatabaseRouteACL(t *testing.T) {- type test struct {- desc string- path string- body string- method string- principalID int- errMsg string- plan api.PlanType- }-- tests := []test{- // Retrieve the database which is unassigned to any project.- {- desc: "Retrieve the database which is assigned to a project, and the user is a member of the project",- path: "/database/303",- method: "GET",- body: "",- principalID: 201,- errMsg: "",- plan: api.ENTERPRISE,- },-- // Transfer the database.- {- desc: "Enterprise Plan, workspace developer of project developer cannot transfer the database out",- path: "/database/304",- body: `{"data":{"type":"databasePatch","attributes":{"projectId":104}}}`,- method: "PATCH",- principalID: 201,- errMsg: "user is not project owner of project owns the database 304",- plan: api.ENTERPRISE,- },- {- desc: "Free & Pro Plan, workspace developer of project developer can transfer the database out",- path: "/database/304",- body: `{"data":{"type":"databasePatch","attributes":{"projectId":104}}}`,- method: "PATCH",- principalID: 201,- errMsg: "",- plan: api.FREE,- },- {- desc: "Enterprise Plan, workspace developer of project owner cannot transfer the database out to the project if he is not the owner",- path: "/database/303",- body: `{"data":{"type":"databasePatch","attributes":{"projectId":103}}}`,- method: "PATCH",- principalID: 201,- errMsg: "user is not project owner of project want owns the database 303",- plan: api.ENTERPRISE,- },- {- desc: "Free & Pro Plan, workspace developer of project owner can transfer the database out to the project if he is not the owner",- path: "/database/303",- body: `{"data":{"type":"databasePatch","attributes":{"projectId":103}}}`,- method: "PATCH",- principalID: 201,- errMsg: "",- plan: api.TEAM,- },- {- desc: "Transfer the database to the project which the user is not a member of",- path: "/database/303",- body: `{"data":{"type":"databasePatch","attributes":{"projectId":101}}}`,- method: "PATCH",- principalID: 201,- errMsg: "user is not a project member of project want to owns the database 303",- plan: api.FREE,- },- {- desc: "Transfer out the database under the project which the user is not a member of",- path: "/database/302",- body: `{"data":{"type":"databasePatch","attributes":{"projectId":102}}}`,- method: "PATCH",- principalID: 201,- errMsg: "user is not a project member of project owns the database 302",- plan: api.FREE,- },- }-- for _, tc := range tests {- t.Run(tc.desc, func(t *testing.T) {- err := enforceWorkspaceDeveloperDatabaseRouteACL(tc.plan, tc.path, tc.method, tc.body, tc.principalID, testWorkspaceDeveloperDatabaseRouteMockGetDatabaseProjectID, getProjectRolesFinderForTest(testWorkspaceDeveloperDatabaseRouteHelper.projectMembers))- if err != nil {- if tc.errMsg == "" {- t.Errorf("expect no error, got %s", err.Message)- } else if tc.errMsg != err.Message {- t.Errorf("expect error %s, got %s", tc.errMsg, err.Message)- }- } else if tc.errMsg != "" {- t.Errorf("expect error %s, got no error", tc.errMsg)- }- })- }-}--var testWorkspaceDeveloperDatabaseRouteHelper = struct {- projectMembers map[int]map[common.ProjectRole][]int- // projectOwnsDatabase is a map from project ID to the map of <database ID, true>.- projectOwnsDatabase map[int]map[int]bool-}{- projectMembers: map[int]map[common.ProjectRole][]int{- 1: {},- 101: {},- 102: {- common.ProjectOwner: {201},- },- 103: {- common.ProjectDeveloper: {201},- },- 104: {- common.ProjectOwner: {201},- },- },- projectOwnsDatabase: map[int]map[int]bool{- // Default Project owns database 301.- 1: {- 301: true,- },- // Project 101 owns database 302.- 101: {- 302: true,- },- // Project 102 owns database 303.- 102: {- 303: true,- },- // Project 103 owns database 304.- 103: {- 304: true,- },- 104: {},- },-}--func testWorkspaceDeveloperDatabaseRouteMockGetDatabaseProjectID(databaseID int) (int, error) {- for projectID, databaseMap := range testWorkspaceDeveloperDatabaseRouteHelper.projectOwnsDatabase {- _, ok := databaseMap[databaseID]- if ok {- return projectID, nil- }- }- return 0, errors.Errorf("database %d not found", databaseID)-}diff --git a/backend/server/acl_test_helper.go b/backend/server/acl_test_helper.goindex 97128a1013..d0bdb0406e 100644--- a/backend/server/acl_test_helper.go+++ b/backend/server/acl_test_helper.go@@ -75,25 +75,6 @@ func testFindPrincipalIDFromSheet(sheetID int, v string) int {return id}-func getProjectRolesFinderForTest(projectMemberMap map[int]map[common.ProjectRole][]int) func(projectID int, principalID int) (map[common.ProjectRole]bool, error) {- return func(projectID int, principalID int) (map[common.ProjectRole]bool, error) {- m, ok := projectMemberMap[projectID]- if !ok {- return nil, errors.Errorf("failed to get project iam policy for project %d", projectID)- }-- projectRoles := make(map[common.ProjectRole]bool)- for role, ids := range m {- for _, id := range ids {- if id == principalID {- projectRoles[role] = true- }- }- }- return projectRoles, nil- }-}-var projectRolesFinderForTest = func(projectID int, principalID int) (map[common.ProjectRole]bool, error) {m, ok := testProjectMemberMap[projectID]if !ok {diff --git a/backend/server/instance.go b/backend/server/instance.godeleted file mode 100644index a0f751e731..0000000000--- a/backend/server/instance.go+++ /dev/null@@ -1,175 +0,0 @@-package server--import (- "fmt"- "net/http"- "strconv"-- "github.com/google/jsonapi"- "github.com/labstack/echo/v4"-- api "github.com/bytebase/bytebase/backend/legacyapi"- "github.com/bytebase/bytebase/backend/plugin/db"- parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"-- "github.com/bytebase/bytebase/backend/plugin/parser/sql/transform"- "github.com/bytebase/bytebase/backend/store"-)--func (s *Server) registerInstanceRoutes(g *echo.Group) {- g.GET("/instance/:instanceID/migration/history/:historyID", func(c echo.Context) error {- ctx := c.Request().Context()- instanceID, err := strconv.Atoi(c.Param("instanceID"))- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Instance ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)- }-- historyID := c.Param("historyID")- isSDL := c.QueryParam("sdl") == "true"-- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &instanceID})- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", instanceID)).SetInternal(err)- }- if instance == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", instanceID))- }-- var entry *db.MigrationHistory- find := &db.MigrationHistoryFind{ID: &historyID, InstanceID: &instanceID}- list, err := s.store.FindInstanceChangeHistoryList(ctx, find)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)- }- if len(list) == 0 {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %q not found for instance %q", historyID, instance.Title))- }- entry = list[0]-- if isSDL {- var engineType parser.EngineType- switch instance.Engine {- case db.MySQL, db.TiDB, db.MariaDB, db.OceanBase:- engineType = parser.MySQL- default:- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Not support SDL format for %s instance", instance.Engine))- }- entry.Schema, err = transform.SchemaTransform(engineType, entry.Schema)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to transform Schema to SDL format for instance %q", instance.Title)).SetInternal(err)- }- entry.SchemaPrev, err = transform.SchemaTransform(engineType, entry.SchemaPrev)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to transform SchemaPrev to SDL format for instance %q", instance.Title)).SetInternal(err)- }- }-- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, &api.MigrationHistory{- ID: entry.ID,- Creator: entry.Creator,- CreatedTs: entry.CreatedTs,- Updater: entry.Updater,- UpdatedTs: entry.UpdatedTs,- ReleaseVersion: entry.ReleaseVersion,- Database: entry.Namespace,- Source: entry.Source,- Type: entry.Type,- Status: entry.Status,- Version: entry.Version,- UseSemanticVersion: entry.UseSemanticVersion,- SemanticVersionSuffix: entry.SemanticVersionSuffix,- Description: entry.Description,- Statement: entry.Statement,- Schema: entry.Schema,- SchemaPrev: entry.SchemaPrev,- ExecutionDurationNs: entry.ExecutionDurationNs,- IssueID: entry.IssueID,- Payload: entry.Payload,- }); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal migration history response for instance: %v", instance.Title)).SetInternal(err)- }- return nil- })-- g.GET("/instance/:instanceID/migration/history", func(c echo.Context) error {- ctx := c.Request().Context()- 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.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &id})- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", id)).SetInternal(err)- }- if instance == nil {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))- }-- find := &db.MigrationHistoryFind{- InstanceID: &instance.UID,- }- if databaseStr := c.QueryParams().Get("database"); databaseStr != "" {- database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{- InstanceID: &instance.ResourceID,- DatabaseName: &databaseStr,- })- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get database %q from instance ID %v", databaseStr, instance.ResourceID)).SetInternal(err)- }- if database == nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot find database %q from instance ID %v", databaseStr, instance.ResourceID)).SetInternal(err)- }- find.Database = &databaseStr- find.DatabaseID = &database.UID- }- if versionStr := c.QueryParams().Get("version"); versionStr != "" {- find.Version = &versionStr- }- if limitStr := c.QueryParam("limit"); limitStr != "" {- limit, err := strconv.Atoi(limitStr)- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("limit query parameter is not a number: %s", limitStr)).SetInternal(err)- }- find.Limit = &limit- }-- migrationHistoryList, err := s.store.FindInstanceChangeHistoryList(ctx, find)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)- }-- historyList := []*api.MigrationHistory{}- for _, entry := range migrationHistoryList {- historyList = append(historyList, &api.MigrationHistory{- ID: entry.ID,- Creator: entry.Creator,- CreatedTs: entry.CreatedTs,- Updater: entry.Updater,- UpdatedTs: entry.UpdatedTs,- ReleaseVersion: entry.ReleaseVersion,- Database: entry.Namespace,- Source: entry.Source,- Type: entry.Type,- Status: entry.Status,- Version: entry.Version,- UseSemanticVersion: entry.UseSemanticVersion,- SemanticVersionSuffix: entry.SemanticVersionSuffix,- Description: entry.Description,- Statement: entry.Statement,- Schema: entry.Schema,- SchemaPrev: entry.SchemaPrev,- ExecutionDurationNs: entry.ExecutionDurationNs,- IssueID: entry.IssueID,- Payload: entry.Payload,- })- }-- 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.Title)).SetInternal(err)- }- return nil- })-}diff --git a/backend/server/server.go b/backend/server/server.goindex 87fe0e309b..d483b21c00 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -506,7 +506,6 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {s.registerOAuthRoutes(apiGroup)s.registerProjectRoutes(apiGroup)s.registerEnvironmentRoutes(apiGroup)- s.registerInstanceRoutes(apiGroup)s.registerDatabaseRoutes(apiGroup)s.registerIssueRoutes(apiGroup)s.registerIssueSubscriberRoutes(apiGroup)diff --git a/backend/store/database.go b/backend/store/database.goindex d011cd324d..f994fed893 100644--- a/backend/store/database.go+++ b/backend/store/database.go@@ -16,46 +16,6 @@ import (storepb "github.com/bytebase/bytebase/proto/generated-go/store")-// FindDatabase finds a list of Database instances.-func (s *Store) FindDatabase(ctx context.Context, find *api.DatabaseFind) ([]*api.Database, error) {- // We don't have caller for searching IncludeAllDatabase.- v2Find := &FindDatabaseMessage{}- if find.InstanceID != nil {- instance, err := s.GetInstanceV2(ctx, &FindInstanceMessage{UID: find.InstanceID})- if err != nil {- return nil, err- }- v2Find.InstanceID = &instance.ResourceID- }- if find.ProjectID != nil {- project, err := s.GetProjectV2(ctx, &FindProjectMessage{UID: find.ProjectID})- if err != nil {- return nil, err- }- v2Find.ProjectID = &project.ResourceID- }- if find.Name != nil {- v2Find.DatabaseName = find.Name- }-- databases, err := s.ListDatabases(ctx, v2Find)- if err != nil {- return nil, err- }- var databaseList []*api.Database- for _, database := range databases {- composedDatabase, err := s.composeDatabase(ctx, database)- if err != nil {- return nil, err- }- if find.SyncStatus != nil && composedDatabase.SyncStatus != *find.SyncStatus {- continue- }- databaseList = append(databaseList, composedDatabase)- }- return databaseList, nil-}-// GetDatabase gets an instance of Database.func (s *Store) GetDatabase(ctx context.Context, find *api.DatabaseFind) (*api.Database, error) {v2Find := &FindDatabaseMessage{diff --git a/backend/store/environment.go b/backend/store/environment.goindex 32d16b0ecc..1327fc8d81 100644--- a/backend/store/environment.go+++ b/backend/store/environment.go@@ -4,7 +4,6 @@ import ("context""database/sql""fmt"- "sort""strings""github.com/pkg/errors"@@ -13,98 +12,6 @@ import (api "github.com/bytebase/bytebase/backend/legacyapi")-// EnvironmentCreate is the API message for creating an environment.-// TODO(ed): This is an temporary struct to compatible with OpenAPI and JSONAPI. Find way to move it into the API package.-type EnvironmentCreate struct {- // Standard fields- CreatorID int-- // Domain specific fields- Name string- Order *int-}--// EnvironmentPatch is the API message for patching an environment.-// TODO(ed): This is an temporary struct to compatible with OpenAPI and JSONAPI. Find way to move it into the API package.-type EnvironmentPatch struct {- ID int-- // Standard fields- RowStatus *string- UpdaterID int-- // Domain specific fields- Name *string- Order *int-}--// CreateEnvironment creates an instance of Environment.-func (s *Store) CreateEnvironment(ctx context.Context, create *EnvironmentCreate) (*api.Environment, error) {- if create.Order == nil {- return nil, errors.Errorf("order must be set in legacy CreateEnvironment")- }- environment, err := s.CreateEnvironmentV2(ctx, &EnvironmentMessage{- ResourceID: strings.ToLower(create.Name),- Title: create.Name,- Order: int32(*create.Order),- Protected: false,- }, create.CreatorID)- if err != nil {- return nil, errors.Wrapf(err, "failed to create Environment with EnvironmentCreate[%+v]", create)- }-- return composeEnvironment(environment), nil-}--// FindEnvironment finds a list of Environment instances.-func (s *Store) FindEnvironment(ctx context.Context, find *api.EnvironmentFind) ([]*api.Environment, error) {- v2Find := &FindEnvironmentMessage{ShowDeleted: true}- environments, err := s.ListEnvironmentV2(ctx, v2Find)- if err != nil {- return nil, errors.Wrapf(err, "failed to find Environment list with ListEnvironmentV2[%+v]", find)- }- sort.Slice(environments, func(i, j int) bool {- return environments[i].Order < environments[j].Order- })- var composedEnvironmentList []*api.Environment- for _, environment := range environments {- composedEnvironment := composeEnvironment(environment)- if find.RowStatus != nil && composedEnvironment.RowStatus != *find.RowStatus {- continue- }- composedEnvironmentList = append(composedEnvironmentList, composedEnvironment)- }- return composedEnvironmentList, nil-}--// PatchEnvironment patches an instance of Environment.-func (s *Store) PatchEnvironment(ctx context.Context, patch *EnvironmentPatch) (*api.Environment, error) {- environment, err := s.GetEnvironmentV2(ctx, &FindEnvironmentMessage{UID: &patch.ID})- if err != nil {- return nil, err- }- v2Update := &UpdateEnvironmentMessage{- Name: patch.Name,- }- if patch.Order != nil {- order := int32(*patch.Order)- v2Update.Order = &order- }- if patch.RowStatus != nil {- deleted := false- if *patch.RowStatus == string(api.Archived) {- deleted = true- }- v2Update.Delete = &deleted- }- environment, err = s.UpdateEnvironmentV2(ctx, environment.ResourceID, v2Update, patch.UpdaterID)- if err != nil {- return nil, errors.Wrapf(err, "failed to patch Environment with EnvironmentPatch[%+v]", patch)- }- composedEnvironment := composeEnvironment(environment)- return composedEnvironment, nil-}-// GetEnvironmentByID gets an instance of Environment by ID.func (s *Store) GetEnvironmentByID(ctx context.Context, id int) (*api.Environment, error) {environment, err := s.GetEnvironmentV2(ctx, &FindEnvironmentMessage{UID: &id})diff --git a/backend/tests/instance.go b/backend/tests/instance.godeleted file mode 100644index 89fcc03bbc..0000000000--- a/backend/tests/instance.go+++ /dev/null@@ -1,57 +0,0 @@-package tests--import (- "fmt"- "reflect"-- "github.com/google/jsonapi"- "github.com/pkg/errors"-- api "github.com/bytebase/bytebase/backend/legacyapi"- "github.com/bytebase/bytebase/backend/plugin/db"-)--func (ctl *controller) getInstanceMigrationHistory(instanceID int, find db.MigrationHistoryFind) ([]*api.MigrationHistory, error) {- params := make(map[string]string)- if find.Database != nil {- params["database"] = *find.Database- }- if find.Version != nil {- params["version"] = *find.Version- }- if find.Limit != nil {- params["limit"] = fmt.Sprintf("%d", *find.Limit)- }- body, err := ctl.get(fmt.Sprintf("/instance/%d/migration/history", instanceID), params)- if err != nil {- return nil, err- }-- var histories []*api.MigrationHistory- hs, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf(new(api.MigrationHistory)))- if err != nil {- return nil, errors.Wrap(err, "fail to unmarshal get migration history response")- }- for _, h := range hs {- history, ok := h.(*api.MigrationHistory)- if !ok {- return nil, errors.Errorf("fail to convert migration history")- }- histories = append(histories, history)- }- return histories, nil-}--func (ctl *controller) getInstanceSDLMigrationHistory(instanceID int, historyID string) (*api.MigrationHistory, error) {- params := make(map[string]string)- params["sdl"] = "true"- body, err := ctl.get(fmt.Sprintf("/instance/%d/migration/history/%s", instanceID, historyID), params)- if err != nil {- return nil, err- }- result := new(api.MigrationHistory)- if err := jsonapi.UnmarshalPayload(body, result); err != nil {- return nil, errors.Wrap(err, "fail to unmarshal get migration history response")- }- return result, nil-}diff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.goindex 6ca52e8ab5..1dd279c855 100644--- a/backend/tests/schema_update_test.go+++ b/backend/tests/schema_update_test.go@@ -18,6 +18,7 @@ import ("github.com/pkg/errors""github.com/stretchr/testify/require""google.golang.org/protobuf/encoding/protojson"+ "google.golang.org/protobuf/proto""google.golang.org/protobuf/testing/protocmp"api "github.com/bytebase/bytebase/backend/legacyapi"@@ -72,8 +73,6 @@ func TestSchemaAndDataUpdate(t *testing.T) {},})a.NoError(err)- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)// Create an issue that creates a database.databaseName := "testSchemaUpdate"@@ -169,38 +168,39 @@ func TestSchemaAndDataUpdate(t *testing.T) {a.Equal(api.TaskDone, status)// Get migration history.- histories, err := ctl.getInstanceMigrationHistory(instanceUID, db.MigrationHistoryFind{})+ resp, err := ctl.databaseServiceClient.ListChangeHistories(ctx, &v1pb.ListChangeHistoriesRequest{+ Parent: database.Name,+ })a.NoError(err)- wantHistories := []api.MigrationHistory{+ histories := resp.ChangeHistories+ wantHistories := []*v1pb.ChangeHistory{{- Database: databaseName,- Source: db.UI,- Type: db.Data,- Status: db.Done,+ Source: v1pb.ChangeHistory_UI,+ Type: v1pb.ChangeHistory_DATA,+ Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema,- SchemaPrev: dumpedSchema,+ PrevSchema: dumpedSchema,},{- Database: databaseName,- Source: db.UI,- Type: db.Migrate,- Status: db.Done,+ Source: v1pb.ChangeHistory_UI,+ Type: v1pb.ChangeHistory_MIGRATE,+ Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema,- SchemaPrev: "",+ PrevSchema: "",},}a.Equal(len(wantHistories), len(histories))for i, history := range histories {- got := api.MigrationHistory{- Database: history.Database,+ got := &v1pb.ChangeHistory{Source: history.Source,Type: history.Type,Status: history.Status,Schema: history.Schema,- SchemaPrev: history.SchemaPrev,+ PrevSchema: history.PrevSchema,}want := wantHistories[i]- a.Equal(want, got)+ proto.Equal(got, want)+ a.True(proto.Equal(got, want))a.NotEqual(history.Version, "")}@@ -220,36 +220,40 @@ func TestSchemaAndDataUpdate(t *testing.T) {cloneDatabaseName := "testClone"err = ctl.cloneDatabaseFromBackup(ctx, projectUID, instance, cloneDatabaseName, backup, nil /* labelMap */)a.NoError(err)+ cloneDatabase, err := ctl.databaseServiceClient.GetDatabase(ctx, &v1pb.GetDatabaseRequest{Name: fmt.Sprintf("%s/databases/%s", instance.Name, cloneDatabaseName)})+ a.NoError(err)// Query clone database book table data.result, err = ctl.query(instance, cloneDatabaseName, bookDataQuery)a.NoError(err)a.Equal(bookDataSQLResult, result)// Query clone migration history.- histories, err = ctl.getInstanceMigrationHistory(instanceUID, db.MigrationHistoryFind{Database: &cloneDatabaseName})+ resp, err = ctl.databaseServiceClient.ListChangeHistories(ctx, &v1pb.ListChangeHistoriesRequest{+ Parent: cloneDatabase.Name,+ })a.NoError(err)- wantCloneHistories := []api.MigrationHistory{+ histories = resp.ChangeHistories+ wantCloneHistories := []*v1pb.ChangeHistory{{- Database: cloneDatabaseName,- Source: db.UI,- Type: db.Branch,- Status: db.Done,+ Source: v1pb.ChangeHistory_UI,+ Type: v1pb.ChangeHistory_BRANCH,+ Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema,- SchemaPrev: dumpedSchema,+ PrevSchema: dumpedSchema,},}a.Equal(len(wantCloneHistories), len(histories))for i, history := range histories {- got := api.MigrationHistory{- Database: history.Database,+ got := &v1pb.ChangeHistory{Source: history.Source,Type: history.Type,Status: history.Status,Schema: history.Schema,- SchemaPrev: history.SchemaPrev,+ PrevSchema: history.PrevSchema,}want := wantCloneHistories[i]- a.Equal(want, got)+ proto.Equal(got, want)+ a.True(proto.Equal(got, want))}_, err = ctl.sheetServiceClient.SearchSheets(ctx, &v1pb.SearchSheetsRequest{@@ -480,8 +484,6 @@ func TestVCS(t *testing.T) {},})a.NoError(err)- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)// Create an issue that creates a database.databaseName := "testVCSSchemaUpdate"@@ -666,70 +668,63 @@ func TestVCS(t *testing.T) {a.Equal(dumpedSchema4, files[latestFileName])// Get migration history.- histories, err := ctl.getInstanceMigrationHistory(instanceUID, db.MigrationHistoryFind{})+ resp, err := ctl.databaseServiceClient.ListChangeHistories(ctx, &v1pb.ListChangeHistoriesRequest{+ Parent: database.Name,+ })a.NoError(err)-- var historiesDeref []api.MigrationHistory- for _, history := range histories {- historiesDeref = append(historiesDeref, *history)- }-- wantHistories := []api.MigrationHistory{+ histories := resp.ChangeHistories+ wantHistories := []*v1pb.ChangeHistory{{- Database: databaseName,- Source: db.UI,- Type: db.Migrate,- Status: db.Done,+ Source: v1pb.ChangeHistory_UI,+ Type: v1pb.ChangeHistory_MIGRATE,+ Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema4,- SchemaPrev: dumpedSchema3,+ PrevSchema: dumpedSchema3,},{- Database: databaseName,- Source: db.VCS,- Type: db.Data,- Status: db.Done,+ Source: v1pb.ChangeHistory_VCS,+ Type: v1pb.ChangeHistory_DATA,+ Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema3,- SchemaPrev: dumpedSchema3,+ PrevSchema: dumpedSchema3,},{- Database: databaseName,- Source: db.VCS,- Type: db.Migrate,- Status: db.Done,+ Source: v1pb.ChangeHistory_VCS,+ Type: v1pb.ChangeHistory_MIGRATE,+ Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema3,- SchemaPrev: dumpedSchema2,+ PrevSchema: dumpedSchema2,},{- Database: databaseName,- Source: db.VCS,- Type: db.Migrate,- Status: db.Done,+ Source: v1pb.ChangeHistory_VCS,+ Type: v1pb.ChangeHistory_MIGRATE,+ Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema2,- SchemaPrev: dumpedSchema,+ PrevSchema: dumpedSchema,},{- Database: databaseName,- Source: db.VCS,- Type: db.Migrate,- Status: db.Done,+ Source: v1pb.ChangeHistory_VCS,+ Type: v1pb.ChangeHistory_MIGRATE,+ Status: v1pb.ChangeHistory_DONE,Schema: dumpedSchema,- SchemaPrev: "",+ PrevSchema: "",},}a.Equal(len(wantHistories), len(histories))-for i, history := range histories {- got := api.MigrationHistory{- Database: history.Database,+ got := &v1pb.ChangeHistory{Source: history.Source,Type: history.Type,Status: history.Status,Schema: history.Schema,- SchemaPrev: history.SchemaPrev,+ PrevSchema: history.PrevSchema,}- a.Equalf(wantHistories[i], got, "got histories %+v", historiesDeref)- a.NotEmpty(history.Version)+ want := wantHistories[i]+ proto.Equal(got, want)+ a.True(proto.Equal(got, want))+ a.NotEqual(history.Version, "")}+a.Equal("ver4-dml", histories[1].Version)a.Equal("ver3-ddl", histories[2].Version)a.Equal("ver2-ddl", histories[3].Version)@@ -914,13 +909,14 @@ func TestVCS_SDL(t *testing.T) {},})a.NoError(err)- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)// Create an issue that creates a databaseerr = ctl.createDatabase(ctx, projectUID, instance, databaseName, "bytebase", nil /* labelMap */)a.NoError(err)+ database, err := ctl.databaseServiceClient.GetDatabase(ctx, &v1pb.GetDatabaseRequest{Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName)})+ a.NoError(err)+// Simulate Git commits for schema update to create a new table "users".schemaFile := fmt.Sprintf("bbtest/prod/.%s##LATEST.sql", databaseName)schemaFileContent += "\nCREATE TABLE users (id serial PRIMARY KEY);"@@ -1073,47 +1069,47 @@ ALTER TABLE ONLY public.users`- histories, err := ctl.getInstanceMigrationHistory(instanceUID, db.MigrationHistoryFind{})+ resp, err := ctl.databaseServiceClient.ListChangeHistories(ctx, &v1pb.ListChangeHistoriesRequest{+ Parent: database.Name,+ })a.NoError(err)- wantHistories := []api.MigrationHistory{+ histories := resp.ChangeHistories+ wantHistories := []*v1pb.ChangeHistory{{- Database: databaseName,- Source: db.VCS,- Type: db.Data,- Status: db.Done,+ Source: v1pb.ChangeHistory_VCS,+ Type: v1pb.ChangeHistory_DATA,+ Status: v1pb.ChangeHistory_DONE,Schema: updatedSchema,- SchemaPrev: updatedSchema,+ PrevSchema: updatedSchema,},{- Database: databaseName,- Source: db.VCS,- Type: db.MigrateSDL,- Status: db.Done,+ Source: v1pb.ChangeHistory_VCS,+ Type: v1pb.ChangeHistory_MIGRATE_SDL,+ Status: v1pb.ChangeHistory_DONE,Schema: updatedSchema,- SchemaPrev: initialSchema,+ PrevSchema: initialSchema,},{- Database: databaseName,- Source: db.UI,- Type: db.Migrate,- Status: db.Done,+ Source: v1pb.ChangeHistory_UI,+ Type: v1pb.ChangeHistory_MIGRATE,+ Status: v1pb.ChangeHistory_DONE,Schema: initialSchema,- SchemaPrev: "",+ PrevSchema: "",},}a.Equal(len(wantHistories), len(histories))-for i, history := range histories {- got := api.MigrationHistory{- Database: history.Database,+ got := &v1pb.ChangeHistory{Source: history.Source,Type: history.Type,Status: history.Status,Schema: history.Schema,- SchemaPrev: history.SchemaPrev,+ PrevSchema: history.PrevSchema,}- a.Equal(wantHistories[i], got, i)- a.NotEmpty(history.Version)+ want := wantHistories[i]+ proto.Equal(got, want)+ a.True(proto.Equal(got, want))+ a.NotEqual(history.Version, "")}})}@@ -2502,13 +2498,14 @@ func TestVCS_SDL_MySQL(t *testing.T) {},})a.NoError(err)- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)// Create an issue that creates a databaseerr = ctl.createDatabase(ctx, projectUID, instance, databaseName, "bytebase", nil /* labelMap */)a.NoError(err)+ database, err := ctl.databaseServiceClient.GetDatabase(ctx, &v1pb.GetDatabaseRequest{Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName)})+ a.NoError(err)+// Simulate Git commits for schema update to create a new table "users".schemaFile := fmt.Sprintf("bbtest/prod/.%s##LATEST.sql", databaseName)schemaFileContent += "\nCREATE TABLE users (id int, PRIMARY KEY (id));"@@ -2624,46 +2621,50 @@ WHERE table_schema = '%s';" PRIMARY KEY (`id`)\n" +") ENGINE=InnoDB DEFAULT CHARACTER SET=UTF8MB4 DEFAULT COLLATE=UTF8MB4_GENERAL_CI;\n\n"- histories, err := ctl.getInstanceMigrationHistory(instanceUID, db.MigrationHistoryFind{})+ resp, err := ctl.databaseServiceClient.ListChangeHistories(ctx, &v1pb.ListChangeHistoriesRequest{+ Parent: database.Name,+ })a.NoError(err)- wantHistories := []api.MigrationHistory{+ histories := resp.ChangeHistories+ wantHistories := []*v1pb.ChangeHistory{{- Database: databaseName,- Source: db.VCS,- Type: db.Data,- Status: db.Done,+ Source: v1pb.ChangeHistory_VCS,+ Type: v1pb.ChangeHistory_DATA,+ Status: v1pb.ChangeHistory_DONE,Schema: updatedSchema,- SchemaPrev: updatedSchema,+ PrevSchema: updatedSchema,},{- Database: databaseName,- Source: db.VCS,- Type: db.MigrateSDL,- Status: db.Done,+ Source: v1pb.ChangeHistory_VCS,+ Type: v1pb.ChangeHistory_MIGRATE_SDL,+ Status: v1pb.ChangeHistory_DONE,Schema: updatedSchema,- SchemaPrev: initialSchema,+ PrevSchema: initialSchema,},}a.Equal(len(wantHistories), len(histories))-for i, history := range histories {- got := api.MigrationHistory{- Database: history.Database,+ got := &v1pb.ChangeHistory{Source: history.Source,Type: history.Type,Status: history.Status,Schema: history.Schema,- SchemaPrev: history.SchemaPrev,+ PrevSchema: history.PrevSchema,}- a.Equal(wantHistories[i], got, i)- a.NotEmpty(history.Version)+ want := wantHistories[i]+ proto.Equal(got, want)+ a.True(proto.Equal(got, want))+ a.NotEqual(history.Version, "")}// Test SDL format.- sdlHistory, err := ctl.getInstanceSDLMigrationHistory(instanceUID, histories[1].ID)+ sdlHistory, err := ctl.databaseServiceClient.GetChangeHistory(ctx, &v1pb.GetChangeHistoryRequest{+ Name: histories[1].Name,+ SdlFormat: true,+ })a.NoError(err)a.Equal(updatedSDL, sdlHistory.Schema)- a.Equal(initialSDL, sdlHistory.SchemaPrev)+ a.Equal(initialSDL, sdlHistory.PrevSchema)})}}diff --git a/backend/tests/sync_schema_test.go b/backend/tests/sync_schema_test.goindex c38e78000d..072fa84812 100644--- a/backend/tests/sync_schema_test.go+++ b/backend/tests/sync_schema_test.go@@ -98,8 +98,6 @@ DROP SCHEMA "schema_a";},})a.NoError(err)- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)err = ctl.createDatabase(ctx, projectUID, instance, databaseName, "bytebase", nil)a.NoError(err)@@ -149,14 +147,14 @@ DROP SCHEMA "schema_a";a.NoError(err)a.Equal(api.TaskDone, status)- history, err := ctl.getInstanceMigrationHistory(instanceUID, db.MigrationHistoryFind{- Database: &databaseName,+ resp, err := ctl.databaseServiceClient.ListChangeHistories(ctx, &v1pb.ListChangeHistoriesRequest{+ Parent: database.Name,})a.NoError(err)-+ histories := resp.ChangeHistories// history[0] is SchemaUpdate- a.Equal(1, len(history))- latest := history[0]+ a.Equal(1, len(histories))+ latest := histories[0]err = ctl.createDatabase(ctx, projectUID, instance, newDatabaseName, "bytebase", nil)a.NoError(err)diff --git a/backend/tests/tenant_test.go b/backend/tests/tenant_test.goindex 3a040bbcd0..980f8dd233 100644--- a/backend/tests/tenant_test.go+++ b/backend/tests/tenant_test.go@@ -207,22 +207,6 @@ func TestTenant(t *testing.T) {a.NoError(err)a.Equal(bookSchemaSQLResult, result)}-- // Query migration history- var instances []*v1pb.Instance- instances = append(instances, testInstances...)- instances = append(instances, prodInstances...)- hm1 := map[string]bool{}- for _, instance := range instances {- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)- histories, err := ctl.getInstanceMigrationHistory(instanceUID, db.MigrationHistoryFind{Database: &databaseName})- a.NoError(err)- a.Equal(1, len(histories))- a.NotEqual(histories[0].Version, "")- hm1[histories[0].Version] = true- }- a.Equal(1, len(hm1))}func TestTenantVCS(t *testing.T) {@@ -505,28 +489,6 @@ func TestTenantVCS(t *testing.T) {a.NoError(err)a.Equal(bookSchemaSQLResult, result)}-- // Query migration history- var instances []*v1pb.Instance- instances = append(instances, testInstances...)- instances = append(instances, prodInstances...)- hm1 := map[string]bool{}- for _, instance := range instances {- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)-- histories, err := ctl.getInstanceMigrationHistory(- instanceUID,- db.MigrationHistoryFind{- Database: &databaseName,- },- )- a.NoError(err)- a.Len(histories, 1)- a.Equal("ver1-ddl", histories[0].Version)- hm1[histories[0].Version] = true- }- a.Len(hm1, 1)})}}@@ -991,45 +953,6 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {a.Equal(bookSchemaSQLResult, result)}- // Query migration history- hm1 := map[string]bool{}- hm2 := map[string]bool{}- for i, instance := range testInstances {- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)- tenant := fmt.Sprintf("tenant%d", i)- databaseName := baseDatabaseName + "_" + tenant- histories, err := ctl.getInstanceMigrationHistory(- instanceUID,- db.MigrationHistoryFind{- Database: &databaseName,- },- )- a.NoError(err)- a.Len(histories, 1)- a.Equal("ver1-ddl", histories[0].Version)- hm1[histories[0].Version] = true- }- for i, instance := range prodInstances {- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)- tenant := fmt.Sprintf("tenant%d", i)- databaseName := baseDatabaseName + "_" + tenant- histories, err := ctl.getInstanceMigrationHistory(- instanceUID,- db.MigrationHistoryFind{- Database: &databaseName,- },- )- a.NoError(err)- a.Len(histories, 1)- a.Equal("ver1-ddl", histories[0].Version)- hm2[histories[0].Version] = true- }-- a.Len(hm1, 1)- a.Len(hm2, 1)-// Check latestSchemaFilefiles, err := ctl.vcsProvider.GetFiles(test.externalID, fmt.Sprintf("%s/.LATEST.sql", baseDirectory))a.NoError(err)@@ -1299,27 +1222,6 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {a.NoError(err)a.Equal(bookSchemaSQLResult, result)}-- // Query migration history- hm := map[string]bool{}- for i, instance := range testInstances {- instanceUID, err := strconv.Atoi(instance.Uid)- a.NoError(err)- tenant := fmt.Sprintf("tenant%d", i)- databaseName := baseDatabaseName + "_" + tenant- histories, err := ctl.getInstanceMigrationHistory(- instanceUID,- db.MigrationHistoryFind{- Database: &databaseName,- },- )- a.NoError(err)- a.Len(histories, 1)- a.Equal("ver1-ddl", histories[0].Version)- hm[histories[0].Version] = true- }-- a.Len(hm, 1)})}}@@ -1606,32 +1508,6 @@ statement: |status, err = ctl.waitIssuePipeline(ctx, issues[0].ID)require.NoError(t, err)require.Equal(t, api.TaskDone, status)-- // Query migration history, only the database of the first tenant should be touched- instanceUID0, err := strconv.Atoi(testInstances[0].Uid)- require.NoError(t, err)- histories, err := ctl.getInstanceMigrationHistory(- instanceUID0,- db.MigrationHistoryFind{- Database: &database0Name,- },- )- require.NoError(t, err)- require.Len(t, histories, 2)- require.Equal(t, "ver2-dml", histories[0].Version)-- instanceUID1, err := strconv.Atoi(testInstances[1].Uid)- require.NoError(t, err)- database1Name := "TestTenantVCS_YAML_tenant1"- histories, err = ctl.getInstanceMigrationHistory(- instanceUID1,- db.MigrationHistoryFind{- Database: &database1Name,- },- )- require.NoError(t, err)- require.Len(t, histories, 1)- require.Equal(t, "ver1-ddl", histories[0].Version)})}}