Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(vcs): support YAML file in place of SQL for DML (#3307)
Joe Chen4f7c069c8cbe
diff --git a/api/issue.go b/api/issue.goindex e07ecf6f7c..95b7675c45 100644--- a/api/issue.go+++ b/api/issue.go@@ -172,6 +172,18 @@ type MigrationContext struct {VCSPushEvent *vcs.PushEvent `json:"vcsPushEvent"`}+// MigrationFileYAMLDatabase contains the information of a database in a YAML+// format migration file.+type MigrationFileYAMLDatabase struct {+ Name string `yaml:"name"` // The name of the database+}++// MigrationFileYAML contains the information in a YAML format migration file.+type MigrationFileYAML struct {+ Databases []MigrationFileYAMLDatabase `yaml:"databases"` // The list of databases and how to identify them+ Statement string `yaml:"statement"` // The SQL statement to be executed to specified list of databases+}+// UpdateSchemaGhostDetail is the detail of updating database schema using gh-ost.type UpdateSchemaGhostDetail struct {// DatabaseID is the ID of a database.diff --git a/plugin/vcs/util.go b/plugin/vcs/util.goindex 22ef6b435b..b8cc08625e 100644--- a/plugin/vcs/util.go+++ b/plugin/vcs/util.go@@ -56,6 +56,7 @@ type DistinctFileItem struct {Commit CommitFileName stringItemType FileItemType+ IsYAML bool}// GetDistinctFileList gets the distinct files from push event commits.@@ -74,6 +75,7 @@ func (p PushEvent) GetDistinctFileList() []DistinctFileItem {Commit: commit,FileName: fileName,ItemType: itemType,+ IsYAML: strings.HasSuffix(fileName, ".yml"),}for i, file := range distinctFileList {// For the migration file with the same name, keep the one from the latest commitdiff --git a/server/webhook.go b/server/webhook.goindex f78d314991..f68c0bcbee 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -19,6 +19,7 @@ import ("github.com/labstack/echo/v4""github.com/pkg/errors""go.uber.org/zap"+ "gopkg.in/yaml.v3""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -586,6 +587,10 @@ const (schemaFileType)+// getFileInfo processes the file item against the candidate list of+// repositories and returns the parsed migration information, file change type+// and a single matched repository. It returns an error when none or multiple+// repositories are matched.func getFileInfo(fileItem vcs.DistinctFileItem, repositoryList []*api.Repository) (*db.MigrationInfo, fileType, *api.Repository, error) {var migrationInfo *db.MigrationInfovar fType fileType@@ -599,9 +604,26 @@ func getFileInfo(fileItem vcs.DistinctFileItem, repositoryList []*api.Repositorycontinue}- allowOmitDatabaseName := repository.Project.TenantMode == api.TenantModeTenant && repository.Project.DBNameTemplate == ""// NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.- mi, err := db.ParseMigrationInfo(fileItem.FileName, path.Join(repository.BaseDirectory, repository.FilePathTemplate), allowOmitDatabaseName)+ filePathTemplate := path.Join(repository.BaseDirectory, repository.FilePathTemplate)+ allowOmitDatabaseName := false+ if repository.Project.TenantMode == api.TenantModeTenant {+ // If the committed file is a YAML file, then the user may have opted-in+ // advanced mode, we need to alter the FilePathTemplate to match ".yml" instead+ // of ".sql".+ if fileItem.IsYAML {+ filePathTemplate = strings.Replace(filePathTemplate, ".sql", ".yml", 1)++ // We do not care database name in the file path with a YAML file.+ allowOmitDatabaseName = true+ } else if repository.Project.DBNameTemplate == "" {+ // Empty DBNameTemplate represents wildcard matching of all databases, thus the+ // database name can be omitted.+ allowOmitDatabaseName = true+ }+ }++ mi, err := db.ParseMigrationInfo(fileItem.FileName, filePathTemplate, allowOmitDatabaseName)if err != nil {log.Error("Failed to parse migration file info",zap.Int("project", repository.ProjectID),@@ -611,6 +633,10 @@ func getFileInfo(fileItem vcs.DistinctFileItem, repositoryList []*api.Repositorycontinue}if mi != nil {+ if fileItem.IsYAML && mi.Type != db.Data {+ return nil, unknownFileType, nil, errors.New("only DML is allowed for YAML files in a tenant project")+ }+migrationInfo = mifType = migrationFileTypefileRepositoryList = append(fileRepositoryList, repository)@@ -643,7 +669,7 @@ func getFileInfo(fileItem vcs.DistinctFileItem, repositoryList []*api.Repositoryfor _, repository := range fileRepositoryList {projectList = append(projectList, repository.Project.Name)}- return nil, unknownFileType, nil, errors.Errorf("file change should be associated with exactly one project but found %s", strings.Join(projectList, ","))+ return nil, unknownFileType, nil, errors.Errorf("file change should be associated with exactly one project but found %s", strings.Join(projectList, ", "))}}@@ -689,7 +715,7 @@ func (s *Server) processFilesInProject(ctx context.Context, pushEvent vcs.PushEv// 1) DML is always migration-based.// 2) We may have a limitation in SDL implementation.// 3) User just wants to break the glass.- migrationDetailListForFile, activityCreateListForFile := s.prepareIssueFromFile(ctx, repo, pushEvent, fileInfo.item.FileName, fileInfo.item.ItemType, fileInfo.migrationInfo)+ migrationDetailListForFile, activityCreateListForFile := s.prepareIssueFromFile(ctx, repo, pushEvent, fileInfo)activityCreateList = append(activityCreateList, activityCreateListForFile...)migrationDetailList = append(migrationDetailList, migrationDetailListForFile...)if len(migrationDetailListForFile) != 0 {@@ -972,57 +998,105 @@ func (s *Server) prepareIssueFromSDLFile(ctx context.Context, repo *api.Reposito// prepareIssueFromFile returns a list of update schema details derived// from the given push event for DDL.-func (s *Server) prepareIssueFromFile(ctx context.Context, repo *api.Repository, pushEvent vcs.PushEvent, fileName string, fileType vcs.FileItemType, migrationInfo *db.MigrationInfo) ([]*api.MigrationDetail, []*api.ActivityCreate) {- statement, err := s.readFileContent(ctx, pushEvent, repo, fileName)+func (s *Server) prepareIssueFromFile(ctx context.Context, repo *api.Repository, pushEvent vcs.PushEvent, fileInfo fileInfo) ([]*api.MigrationDetail, []*api.ActivityCreate) {+ content, err := s.readFileContent(ctx, pushEvent, repo, fileInfo.item.FileName)if err != nil {- activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, fileName, errors.Wrap(err, "Failed to read file content"))- return nil, []*api.ActivityCreate{activityCreate}+ return nil, []*api.ActivityCreate{+ getIgnoredFileActivityCreate(+ repo.ProjectID,+ pushEvent,+ fileInfo.item.FileName,+ errors.Wrap(err, "Failed to read file content"),+ ),+ }}- var migrationDetailList []*api.MigrationDetail-- // TODO(dragonly): handle modified file for tenant mode.- migrationType := db.Migrate- if migrationInfo.Type == db.Data {- migrationType = db.Data- }if repo.Project.TenantMode == api.TenantModeTenant {- migrationDetailList = append(migrationDetailList,- &api.MigrationDetail{- MigrationType: migrationType,- DatabaseName: migrationInfo.Database,- Statement: statement,- SchemaVersion: migrationInfo.Version,- },- )+ // A non-YAML file means the whole file content is the SQL statement+ if !fileInfo.item.IsYAML {+ return []*api.MigrationDetail{+ {+ MigrationType: fileInfo.migrationInfo.Type,+ DatabaseName: fileInfo.migrationInfo.Database,+ Statement: content,+ SchemaVersion: fileInfo.migrationInfo.Version,+ },+ }, nil+ }++ var migrationFile api.MigrationFileYAML+ err = yaml.Unmarshal([]byte(content), &migrationFile)+ if err != nil {+ return nil, []*api.ActivityCreate{+ getIgnoredFileActivityCreate(+ repo.ProjectID,+ pushEvent,+ fileInfo.item.FileName,+ errors.Wrap(err, "Failed to parse file content as YAML"),+ ),+ }+ }++ var migrationDetailList []*api.MigrationDetail+ for _, database := range migrationFile.Databases {+ dbList, err := s.findProjectDatabases(ctx, repo.ProjectID, database.Name, "")+ if err != nil {+ return nil, []*api.ActivityCreate{+ getIgnoredFileActivityCreate(+ repo.ProjectID,+ pushEvent,+ fileInfo.item.FileName,+ errors.Wrapf(err, "Failed to find project database %q", database.Name),+ ),+ }+ }++ for _, db := range dbList {+ migrationDetailList = append(migrationDetailList,+ &api.MigrationDetail{+ MigrationType: fileInfo.migrationInfo.Type,+ DatabaseID: db.ID,+ Statement: migrationFile.Statement,+ SchemaVersion: fileInfo.migrationInfo.Version,+ },+ )+ }+ }return migrationDetailList, nil}- databases, err := s.findProjectDatabases(ctx, repo.ProjectID, migrationInfo.Database, migrationInfo.Environment)+ // TODO(dragonly): handle modified file for tenant mode.+ databases, err := s.findProjectDatabases(ctx, repo.ProjectID, fileInfo.migrationInfo.Database, fileInfo.migrationInfo.Environment)if err != nil {- activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, fileName, errors.Wrap(err, "Failed to find project databases"))+ activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, fileInfo.item.FileName, errors.Wrap(err, "Failed to find project databases"))return nil, []*api.ActivityCreate{activityCreate}}- if fileType == vcs.FileItemTypeAdded {+ if fileInfo.item.ItemType == vcs.FileItemTypeAdded {+ var migrationDetailList []*api.MigrationDetailfor _, database := range databases {migrationDetailList = append(migrationDetailList,&api.MigrationDetail{- MigrationType: migrationType,+ MigrationType: fileInfo.migrationInfo.Type,DatabaseID: database.ID,- Statement: statement,- SchemaVersion: migrationInfo.Version,+ Statement: content,+ SchemaVersion: fileInfo.migrationInfo.Version,},)}return migrationDetailList, nil}- if err := s.tryUpdateTasksFromModifiedFile(ctx, databases, fileName, migrationInfo.Version, statement); err != nil {- activityCreate := getIgnoredFileActivityCreate(repo.ProjectID, pushEvent, fileName, errors.Wrap(err, "Failed to find project task"))- return nil, []*api.ActivityCreate{activityCreate}+ if err := s.tryUpdateTasksFromModifiedFile(ctx, databases, fileInfo.item.FileName, fileInfo.migrationInfo.Version, content); err != nil {+ return nil, []*api.ActivityCreate{+ getIgnoredFileActivityCreate(+ repo.ProjectID,+ pushEvent,+ fileInfo.item.FileName,+ errors.Wrap(err, "Failed to find project task"),+ ),+ }}-return nil, nil}diff --git a/server/webhook_test.go b/server/webhook_test.goindex 0e51d5de6a..b9f1980759 100644--- a/server/webhook_test.go+++ b/server/webhook_test.go@@ -4,8 +4,12 @@ import ("testing""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/vcs")// TODO(d): fix the double underscore "__".@@ -167,7 +171,7 @@ You can check the docs at https://www.bytebase.com/docs/reference/error-code/advassert.Equal(t, expect, res.Content[0])}-func TestVCSSQLReview_ConvertSQLAdiceToGitHubActionResult(t *testing.T) {+func TestVCSSQLReview_ConvertSQLAdviceToGitHubActionResult(t *testing.T) {expect := []string{"::warning file=file1.sql,line=1,col=1,endColumn=2,title=column.no-null (402)::Column \"id\" in \"public\".\"book\" cannot have NULL value%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#402","::error file=file1.sql,line=2,col=1,endColumn=2,title=naming.index.idx (303)::Index in table \"tech_book\" mismatches the naming convention, expect \"^$|^idx_tech_book_id_name$\" but found \"tech_book_id_name\"%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#303",@@ -179,3 +183,158 @@ func TestVCSSQLReview_ConvertSQLAdiceToGitHubActionResult(t *testing.T) {assert.Equal(t, 4, len(res.Content))assert.Equal(t, expect, res.Content)}++func TestGetFileInfo(t *testing.T) {+ t.Run("a SQL format DDL", func(t *testing.T) {+ mi, fileType, repo, err := getFileInfo(+ vcs.DistinctFileItem{+ FileName: "db##0001##migrate.sql",+ ItemType: vcs.FileItemTypeAdded,+ },+ []*api.Repository{+ {+ ID: 1,+ Project: &api.Project{},+ FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",+ },+ },+ )+ require.NoError(t, err)+ assert.Equal(t, 1, repo.ID)+ assert.Equal(t, migrationFileType, fileType)++ want := &db.MigrationInfo{+ Version: "0001",+ Namespace: "db",+ Database: "db",+ Source: db.VCS,+ Type: db.Migrate,+ Description: "Create db schema migration",+ }+ assert.Equal(t, want, mi)+ })++ t.Run("a SQL format DML", func(t *testing.T) {+ mi, fileType, repo, err := getFileInfo(+ vcs.DistinctFileItem{+ FileName: "db##0001##data.sql",+ ItemType: vcs.FileItemTypeAdded,+ },+ []*api.Repository{+ {+ ID: 1,+ Project: &api.Project{},+ FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",+ },+ },+ )+ require.NoError(t, err)+ assert.Equal(t, 1, repo.ID)+ assert.Equal(t, migrationFileType, fileType)++ want := &db.MigrationInfo{+ Version: "0001",+ Namespace: "db",+ Database: "db",+ Source: db.VCS,+ Type: db.Data,+ Description: "Create db data change",+ }+ assert.Equal(t, want, mi)+ })++ t.Run("a YAML format DML in a tenant project", func(t *testing.T) {+ mi, fileType, repo, err := getFileInfo(+ vcs.DistinctFileItem{+ FileName: "db##0001##data.yml",+ ItemType: vcs.FileItemTypeAdded,+ IsYAML: true,+ },+ []*api.Repository{+ {+ ID: 1,+ Project: &api.Project{+ TenantMode: api.TenantModeTenant,+ },+ FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",+ },+ },+ )+ require.NoError(t, err)+ assert.Equal(t, 1, repo.ID)+ assert.Equal(t, migrationFileType, fileType)++ want := &db.MigrationInfo{+ Version: "0001",+ Namespace: "db",+ Database: "db",+ Source: db.VCS,+ Type: db.Data,+ Description: "Create db data change",+ }+ assert.Equal(t, want, mi)+ })++ t.Run("a YAML format DDL is not allowed in a tenant project", func(t *testing.T) {+ _, _, _, err := getFileInfo(+ vcs.DistinctFileItem{+ FileName: "db##0001##migrate.yml",+ ItemType: vcs.FileItemTypeAdded,+ IsYAML: true,+ },+ []*api.Repository{+ {+ ID: 1,+ Project: &api.Project{+ TenantMode: api.TenantModeTenant,+ },+ FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",+ },+ },+ )+ require.EqualError(t, err, "only DML is allowed for YAML files in a tenant project")+ })++ t.Run("no matching repository", func(t *testing.T) {+ _, _, _, err := getFileInfo(+ vcs.DistinctFileItem{+ FileName: "db##0001##migrate.sql",+ ItemType: vcs.FileItemTypeAdded,+ },+ []*api.Repository{+ {+ ID: 1,+ Project: &api.Project{},+ BaseDirectory: "bytebase",+ FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",+ },+ },+ )+ require.EqualError(t, err, "file change is not associated with any project")+ })++ t.Run("matching multiple repositories", func(t *testing.T) {+ _, _, _, err := getFileInfo(+ vcs.DistinctFileItem{+ FileName: "db##0001##migrate.sql",+ ItemType: vcs.FileItemTypeAdded,+ },+ []*api.Repository{+ {+ ID: 1,+ Project: &api.Project{+ Name: "project-1",+ },+ FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",+ }, {+ ID: 2,+ Project: &api.Project{+ Name: "project-2",+ },+ FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",+ },+ },+ )+ require.EqualError(t, err, "file change should be associated with exactly one project but found project-1, project-2")+ })+}diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 597e22d495..cab6dfcbde 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -1618,7 +1618,7 @@ func TestVCS_SQL_Review(t *testing.T) {}}-// postVCSSQLReview will creates the VCS SQL review and get the response.+// postVCSSQLReview will create the VCS SQL review and get the response.func postVCSSQLReview(ctl *controller, repo *api.Repository, request *api.VCSSQLReviewRequest) (*api.VCSSQLReviewResult, error) {url := fmt.Sprintf("%s/hook/sql-review/%s", ctl.rootURL, repo.WebhookEndpointID)diff --git a/tests/tenant_test.go b/tests/tenant_test.goindex 1b0b1ecf2d..5c50f41e25 100644--- a/tests/tenant_test.go+++ b/tests/tenant_test.go@@ -1249,3 +1249,299 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {})}}++// TestTenantVCS_YAML tests the behavior when use a YAML file to do DML in a+// tenant project.+func TestTenantVCS_YAML(t *testing.T) {+ tests := []struct {+ name string+ vcsProviderCreator fake.VCSProviderCreator+ vcsType vcs.Type+ externalID string+ repositoryFullPath string+ newWebhookPushEvent func(gitFile string) interface{}+ }{+ {+ name: "GitLab",+ vcsProviderCreator: fake.NewGitLab,+ vcsType: vcs.GitLabSelfHost,+ externalID: "121",+ repositoryFullPath: "test/dataUpdate",+ newWebhookPushEvent: func(gitFile string) interface{} {+ return gitlab.WebhookPushEvent{+ ObjectKind: gitlab.WebhookPush,+ Ref: "refs/heads/feature/foo",+ Project: gitlab.WebhookProject{+ ID: 121,+ },+ CommitList: []gitlab.WebhookCommit{+ {+ Timestamp: "2021-01-13T13:14:00Z",+ AddedList: []string{gitFile},+ },+ },+ }+ },+ },+ {+ name: "GitHub",+ vcsProviderCreator: fake.NewGitHub,+ vcsType: vcs.GitHubCom,+ externalID: "octocat/Hello-World",+ repositoryFullPath: "octocat/Hello-World",+ newWebhookPushEvent: func(gitFile string) interface{} {+ return github.WebhookPushEvent{+ Ref: "refs/heads/feature/foo",+ Repository: github.WebhookRepository{+ ID: 211,+ FullName: "octocat/Hello-World",+ HTMLURL: "https://github.com/octocat/Hello-World",+ },+ Sender: github.WebhookSender{+ Login: "fake_github_author",+ },+ Commits: []github.WebhookCommit{+ {+ ID: "fake_github_commit_id",+ Distinct: true,+ Message: "Fake GitHub commit message",+ Timestamp: time.Now(),+ URL: "https://api.github.com/octocat/Hello-World/commits/fake_github_commit_id",+ Author: github.WebhookCommitAuthor{+ Name: "fake_github_author",+ Email: "fake_github_author@localhost",+ },+ Added: []string{gitFile},+ },+ },+ }+ },+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ t.Parallel()++ ctx := context.Background()+ ctl := &controller{}+ err := ctl.StartServer(ctx, t.TempDir(), fake.NewGitHub, getTestPort(t.Name()))+ require.NoError(t, err)+ defer func() {+ _ = ctl.Close(ctx)+ }()++ err = ctl.Login()+ require.NoError(t, err)+ err = ctl.setLicense()+ require.NoError(t, err)++ // Create a VCS.+ vcs, err := ctl.createVCS(+ api.VCSCreate{+ Name: t.Name(),+ Type: test.vcsType,+ InstanceURL: ctl.vcsURL,+ APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationID: "testApplicationID",+ Secret: "testApplicationSecret",+ },+ )+ require.NoError(t, err)++ // Create a tenant project with empty database name template.+ project, err := ctl.createProject(+ api.ProjectCreate{+ Name: "Test VCS Project",+ Key: "TestTenantVCS_YAML",+ TenantMode: api.TenantModeTenant,+ },+ )+ require.NoError(t, err)++ // Create a repository.+ ctl.vcsProvider.CreateRepository(test.externalID)+ _, err = ctl.createRepository(+ api.RepositoryCreate{+ VCSID: vcs.ID,+ ProjectID: project.ID,+ Name: "Test Repository",+ FullPath: test.repositoryFullPath,+ WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ BranchFilter: "feature/foo",+ BaseDirectory: baseDirectory,+ FilePathTemplate: "{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",+ SchemaPathTemplate: ".{{DB_NAME}}##LATEST.sql",+ ExternalID: test.externalID,+ AccessToken: "accessToken1",+ RefreshToken: "refreshToken1",+ },+ )+ require.NoError(t, err)++ // Provision instances.+ instanceRootDir := t.TempDir()++ const stagingTenantNumber = 2 // We need more than one tenant to test database selection+ var stagingInstanceDirs []string+ for i := 0; i < stagingTenantNumber; i++ {+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", stagingInstanceName, i))+ require.NoError(t, err)+ stagingInstanceDirs = append(stagingInstanceDirs, instanceDir)+ }+ environments, err := ctl.getEnvironments()+ require.NoError(t, err)+ stagingEnvironment, err := findEnvironment(environments, "Staging")+ require.NoError(t, err)++ // Add the provisioned instances.+ var stagingInstances []*api.Instance+ for i, stagingInstanceDir := range stagingInstanceDirs {+ instance, err := ctl.addInstance(+ api.InstanceCreate{+ EnvironmentID: stagingEnvironment.ID,+ Name: fmt.Sprintf("%s-%d", stagingInstanceName, i),+ Engine: db.SQLite,+ Host: stagingInstanceDir,+ },+ )+ require.NoError(t, err)+ stagingInstances = append(stagingInstances, instance)+ }++ // Create deployment configuration.+ _, err = ctl.upsertDeploymentConfig(+ api.DeploymentConfigUpsert{+ ProjectID: project.ID,+ },+ api.DeploymentSchedule{+ Deployments: []*api.Deployment{+ {+ Name: "Staging stage",+ Spec: &api.DeploymentSpec{+ Selector: &api.LabelSelector{+ MatchExpressions: []*api.LabelSelectorRequirement{+ {+ Key: api.EnvironmentKeyName,+ Operator: api.InOperatorType,+ Values: []string{"Staging"},+ },+ },+ },+ },+ },+ },+ },+ )+ require.NoError(t, err)++ // Create issues that create databases.+ const baseDatabaseName = "TestTenantVCS_YAML"+ for i, stagingInstance := range stagingInstances {+ tenant := fmt.Sprintf("tenant%d", i)+ databaseName := baseDatabaseName + "_" + tenant+ err := ctl.createDatabase(project, stagingInstance, databaseName, "", nil /* labelMap */)+ require.NoError(t, err)+ }++ // Getting databases for each environment.+ databases, err := ctl.getDatabases(+ api.DatabaseFind{+ ProjectID: &project.ID,+ },+ )+ require.NoError(t, err)++ var stagingDatabases []*api.Database+ for _, stagingInstance := range stagingInstances {+ for _, database := range databases {+ if database.Instance.ID == stagingInstance.ID {+ stagingDatabases = append(stagingDatabases, database)+ break+ }+ }+ }+ require.Equal(t, stagingTenantNumber, len(stagingDatabases))++ // Simulate Git commits for schema update.+ gitFile := baseDirectory + "/ver1##migrate##create_a_test_table.sql"+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: migrationStatement})+ require.NoError(t, err)++ payload, err := json.Marshal(test.newWebhookPushEvent(gitFile))+ require.NoError(t, err)+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)+ require.NoError(t, err)++ // Get schema update issues.+ openStatus := []api.IssueStatus{api.IssueOpen}+ issues, err := ctl.getIssues(+ api.IssueFind{+ ProjectID: &project.ID,+ StatusList: openStatus,+ },+ )+ require.NoError(t, err)+ require.Len(t, issues, 1)+ status, err := ctl.waitIssuePipeline(issues[0].ID)+ require.NoError(t, err)+ require.Equal(t, api.TaskDone, status)++ // Simulate Git commits for data update.+ gitFile = baseDirectory + "/ver2##data##insert_a_new_row.yml"+ err = ctl.vcsProvider.AddFiles(+ test.externalID,+ map[string]string{+ gitFile: fmt.Sprintf(`+databases:+ - name: %s+statement: |+ INSERT INTO book (name) VALUES ('Star Wars')+`,+ databases[0].Name,+ ),+ },+ )+ require.NoError(t, err)++ payload, err = json.Marshal(test.newWebhookPushEvent(gitFile))+ require.NoError(t, err)+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)+ require.NoError(t, err)++ // Get data update issues.+ openStatus = []api.IssueStatus{api.IssueOpen}+ issues, err = ctl.getIssues(+ api.IssueFind{+ ProjectID: &project.ID,+ StatusList: openStatus,+ },+ )+ require.NoError(t, err)+ require.Len(t, issues, 2)+ status, err = ctl.waitIssuePipeline(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+ histories, err := ctl.getInstanceMigrationHistory(+ db.MigrationHistoryFind{+ ID: &stagingInstances[0].ID,+ Database: &databases[0].Name,+ },+ )+ require.NoError(t, err)+ require.Len(t, histories, 3)+ require.Equal(t, histories[0].Version, "ver2")++ histories, err = ctl.getInstanceMigrationHistory(+ db.MigrationHistoryFind{+ ID: &stagingInstances[1].ID,+ Database: &databases[1].Name,+ },+ )+ require.NoError(t, err)+ require.Len(t, histories, 2)+ require.Equal(t, histories[0].Version, "ver1")+ })+ }+}diff --git a/tests/tests.go b/tests/tests.goindex b88b4079cd..0833858c53 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -165,6 +165,8 @@ func getTestPort(testName string) int {"TestTenant","TestTenantVCS/GitLab","TestTenantVCS/GitHub",+ "TestTenantVCS_YAML/GitLab",+ "TestTenantVCS_YAML/GitHub","TestTenantDatabaseNameTemplate","TestGhostSchemaUpdate","TestTenantVCSDatabaseNameTemplate/GitLab",