Skip to content

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

feat(test): test tenant schema update with VCS, and tenant pipeline only write back latest schema on the last task (#544)

Danny Xu03546b521ade
diff --git a/server/task_executor.go b/server/task_executor.go
index 079bbdeafe..11681d5370 100644
--- a/server/task_executor.go
+++ b/server/task_executor.go
@@ -118,6 +118,9 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.
zap.Error(err),
)
} else {
+ if err := server.composeIssueRelationship(ctx, issue); err != nil {
+ return true, nil, err
+ }
mi.IssueID = strconv.Itoa(issue.ID)
}
@@ -159,7 +162,30 @@ func runMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.
}
// If VCS based and schema path template is specified, then we will write back the latest schema file after migration.
- if vcsPushEvent != nil && repository.SchemaPathTemplate != "" {
+ writeBack := (vcsPushEvent != nil) && (repository.SchemaPathTemplate != "")
+ // For tenant mode project, we will only write back latest schema file on the last task.
+ if writeBack && issue != nil {
+ project, err := server.composeProjectByID(ctx, task.Database.ProjectID)
+ if err != nil {
+ return true, nil, err
+ }
+ if project.TenantMode == api.TenantModeTenant {
+ var lastTask *api.Task
+ for i := len(issue.Pipeline.StageList) - 1; i >= 0; i-- {
+ stage := issue.Pipeline.StageList[i]
+ if len(stage.TaskList) > 0 {
+ lastTask = stage.TaskList[len(stage.TaskList)-1]
+ break
+ }
+ }
+ // Not the last task yet.
+ if lastTask != nil && task.ID != lastTask.ID {
+ writeBack = false
+ }
+ }
+ }
+
+ if writeBack {
latestSchemaFile := filepath.Join(repository.BaseDirectory, repository.SchemaPathTemplate)
latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{ENV_NAME}}", mi.Environment)
latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{DB_NAME}}", mi.Database)
diff --git a/tests/schema_update_test.go b/tests/schema_update_test.go
index 2f75538821..46e5bb1fa4 100644
--- a/tests/schema_update_test.go
+++ b/tests/schema_update_test.go
@@ -277,10 +277,10 @@ func TestVCSSchemaUpdate(t *testing.T) {
},
}
if err := ctl.gitlab.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement}); err != nil {
- t.Fatalf("failed to add files to gitlab project %q, error %v", gitlabProjectID, err)
+ t.Fatalf("failed to add files to gitlab project %v, error %v", gitlabProjectID, err)
}
if err := ctl.gitlab.SendCommits(gitlabProjectIDStr, pushEvent); err != nil {
- t.Fatalf("failed to send commits to gitlab project %q, error %v", gitlabProjectID, err)
+ t.Fatalf("failed to send commits to gitlab project %v, error %v", gitlabProjectID, err)
}
// Get schema update issue.
diff --git a/tests/tenant_test.go b/tests/tenant_test.go
index 0c31dd6962..2882c417c0 100644
--- a/tests/tenant_test.go
+++ b/tests/tenant_test.go
@@ -8,6 +8,8 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/plugin/db"
+ "github.com/bytebase/bytebase/plugin/vcs"
+ "github.com/bytebase/bytebase/plugin/vcs/gitlab"
"github.com/kr/pretty"
)
@@ -118,46 +120,7 @@ func TestTenantSchemaUpdate(t *testing.T) {
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"},
- },
- {
- Key: api.TenantLabelKey,
- Operator: api.ExistsOperatorType,
- },
- },
- },
- },
- },
- {
- Name: "Prod stage",
- Spec: &api.DeploymentSpec{
- Selector: &api.LabelSelector{
- MatchExpressions: []*api.LabelSelectorRequirement{
- {
- Key: api.EnvironmentKeyName,
- Operator: api.InOperatorType,
- Values: []string{"Prod"},
- },
- {
- Key: api.TenantLabelKey,
- Operator: api.ExistsOperatorType,
- },
- },
- },
- },
- },
- },
- },
+ deploymentSchdule,
); err != nil {
t.Fatal(err)
}
@@ -261,3 +224,259 @@ func TestTenantSchemaUpdate(t *testing.T) {
}
}
}
+
+func TestTenantVCSSchemaUpdate(t *testing.T) {
+ ctx := context.Background()
+ ctl := &controller{}
+ dataDir := t.TempDir()
+ if err := ctl.StartMain(ctx, dataDir); err != nil {
+ t.Fatal(err)
+ }
+ defer ctl.Close()
+ if err := ctl.Login(); err != nil {
+ t.Fatal(err)
+ }
+ if err := ctl.setLicense(); err != nil {
+ t.Fatal(err)
+ }
+
+ // Create a VCS.
+ applicationID := "testApplicationID"
+ applicationSecret := "testApplicationSecret"
+ vcs, err := ctl.createVCS(api.VCSCreate{
+ Name: "TestVCS",
+ Type: vcs.GitLabSelfHost,
+ InstanceURL: gitURL,
+ APIURL: gitAPIURL,
+ ApplicationID: applicationID,
+ Secret: applicationSecret,
+ })
+ if err != nil {
+ t.Fatalf("failed to create VCS, error: %v", err)
+ }
+
+ // Create a project.
+ project, err := ctl.createProject(api.ProjectCreate{
+ Name: "Test Project",
+ Key: "TestSchemaUpdate",
+ TenantMode: api.TenantModeTenant,
+ })
+ if err != nil {
+ t.Fatalf("failed to create project, error: %v", err)
+ }
+
+ // Create a repository.
+ repositoryPath := "test/schemaUpdate"
+ accessToken := "accessToken1"
+ refreshToken := "refreshToken1"
+ gitlabProjectID := 121
+ gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)
+ // create a gitlab project.
+ ctl.gitlab.CreateProject(gitlabProjectIDStr)
+ _, err = ctl.createRepository(api.RepositoryCreate{
+ VCSID: vcs.ID,
+ ProjectID: project.ID,
+ Name: "Test Repository",
+ FullPath: repositoryPath,
+ WebURL: fmt.Sprintf("%s/%s", gitURL, repositoryPath),
+ BranchFilter: "feature/foo",
+ BaseDirectory: "bbtest",
+ FilePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
+ SchemaPathTemplate: ".{{DB_NAME}}__LATEST.sql",
+ ExternalID: gitlabProjectIDStr,
+ AccessToken: accessToken,
+ ExpiresTs: 0,
+ RefreshToken: refreshToken,
+ })
+ if err != nil {
+ t.Fatalf("failed to create repository, error: %v", err)
+ }
+
+ // Provision instances.
+ instanceRootDir := t.TempDir()
+
+ var stagingInstanceDirs []string
+ var prodInstanceDirs []string
+ for i := 0; i < stagingInstancesNumber; i++ {
+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", stagingInstanceNamePrefix, i))
+ if err != nil {
+ t.Fatal(err)
+ }
+ stagingInstanceDirs = append(stagingInstanceDirs, instanceDir)
+ }
+ for i := 0; i < prodInstancesNumber; i++ {
+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", prodInstanceNamePrefix, i))
+ if err != nil {
+ t.Fatal(err)
+ }
+ prodInstanceDirs = append(prodInstanceDirs, instanceDir)
+ }
+ environments, err := ctl.getEnvironments()
+ if err != nil {
+ t.Fatal(err)
+ }
+ stagingEnvironment, err := findEnvironment(environments, "Staging")
+ if err != nil {
+ t.Fatal(err)
+ }
+ prodEnvironment, err := findEnvironment(environments, "Prod")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Add the provisioned instances.
+ var stagingInstances []*api.Instance
+ var prodInstances []*api.Instance
+ for i, stagingInstanceDir := range stagingInstanceDirs {
+ instance, err := ctl.addInstance(api.InstanceCreate{
+ EnvironmentID: stagingEnvironment.ID,
+ Name: fmt.Sprintf("%s-%d", stagingInstanceNamePrefix, i),
+ Engine: db.SQLite,
+ Host: stagingInstanceDir,
+ })
+ if err != nil {
+ t.Fatalf("failed to add instance, error: %v", err)
+ }
+ stagingInstances = append(stagingInstances, instance)
+ }
+ for i, prodInstanceDir := range prodInstanceDirs {
+ instance, err := ctl.addInstance(api.InstanceCreate{
+ EnvironmentID: prodEnvironment.ID,
+ Name: fmt.Sprintf("%s-%d", prodInstanceNamePrefix, i),
+ Engine: db.SQLite,
+ Host: prodInstanceDir,
+ })
+ if err != nil {
+ t.Fatalf("failed to add instance, error: %v", err)
+ }
+ prodInstances = append(prodInstances, instance)
+ }
+
+ // Set up label values for tenants.
+ // Prod and staging are using the same tenant values. Use prodInstancesNumber because it's larger than stagingInstancesNumber.
+ var tenants []string
+ for i := 0; i < prodInstancesNumber; i++ {
+ tenants = append(tenants, fmt.Sprintf("tenant%d", i))
+ }
+ if err := ctl.addLabelValues(api.TenantLabelKey, tenants); err != nil {
+ t.Fatal(err)
+ }
+
+ // Create deployment configuration.
+ if _, err := ctl.upsertDeploymentConfig(
+ api.DeploymentConfigUpsert{
+ ProjectID: project.ID,
+ },
+ deploymentSchdule,
+ ); err != nil {
+ t.Fatal(err)
+ }
+
+ // Create issues that create databases.
+ databaseName := "testTenantVCSSchemaUpdate"
+ for i, stagingInstance := range stagingInstances {
+ if err := ctl.createDatabase(project, stagingInstance, databaseName, map[string]string{api.TenantLabelKey: fmt.Sprintf("tenant%d", i)}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i, prodInstance := range prodInstances {
+ if err := ctl.createDatabase(project, prodInstance, databaseName, map[string]string{api.TenantLabelKey: fmt.Sprintf("tenant%d", i)}); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ // Getting databases for each environment.
+ databases, err := ctl.getDatabases(api.DatabaseFind{
+ ProjectID: &project.ID,
+ })
+ if err != nil {
+ t.Fatalf("failed to get databases, error: %v", err)
+ }
+
+ var stagingDatabases []*api.Database
+ var prodDatabases []*api.Database
+ for _, stagingInstance := range stagingInstances {
+ for _, database := range databases {
+ if database.Instance.ID == stagingInstance.ID {
+ stagingDatabases = append(stagingDatabases, database)
+ break
+ }
+ }
+ }
+ for _, prodInstance := range prodInstances {
+ for _, database := range databases {
+ if database.Instance.ID == prodInstance.ID {
+ prodDatabases = append(prodDatabases, database)
+ break
+ }
+ }
+ }
+ if len(stagingDatabases) != stagingInstancesNumber {
+ t.Fatalf("invalid number of staging databases %v in project %v, expecting %d database", project.ID, len(databases), stagingInstancesNumber)
+ }
+ if len(prodDatabases) != prodInstancesNumber {
+ t.Fatalf("invalid number of prod databases %v in project %v, expecting %d database", project.ID, len(databases), prodInstancesNumber)
+ }
+
+ // Simulate Git commits.
+ gitFile := "bbtest/testTenantVCSSchemaUpdate__ver1__migrate__create_a_test_table.sql"
+ pushEvent := &gitlab.WebhookPushEvent{
+ ObjectKind: gitlab.WebhookPush,
+ Ref: "refs/heads/feature/foo",
+ Project: gitlab.WebhookProject{
+ ID: gitlabProjectID,
+ },
+ CommitList: []gitlab.WebhookCommit{
+ {
+ Timestamp: "2021-01-13T13:14:00Z",
+ AddedList: []string{
+ gitFile,
+ },
+ },
+ },
+ }
+ if err := ctl.gitlab.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement}); err != nil {
+ t.Fatalf("failed to add files to gitlab project %v, error %v", gitlabProjectID, err)
+ }
+ if err := ctl.gitlab.SendCommits(gitlabProjectIDStr, pushEvent); err != nil {
+ t.Fatalf("failed to send commits to gitlab project %v, error %v", gitlabProjectID, err)
+ }
+
+ // Get schema update issue.
+ openStatus := []api.IssueStatus{api.IssueOpen}
+ issues, err := ctl.getIssues(api.IssueFind{ProjectID: &project.ID, StatusList: &openStatus})
+ if err != nil {
+ t.Fatalf("failed to get open issues for project %v, error: %v", project.ID, err)
+ }
+ if len(issues) != 1 {
+ t.Fatalf("invalid number of open issues %v in project %v, expecting one issue", len(issues), project.ID)
+ }
+ issue := issues[0]
+ status, err := ctl.waitIssuePipeline(issue.ID)
+ if err != nil {
+ t.Fatalf("failed to wait for issue %v pipeline %v, error: %v", issue.ID, issue.Pipeline.ID, err)
+ }
+ if status != api.TaskDone {
+ t.Fatalf("issue %v pipeline %v is expected to finish with status done got %v", issue.ID, issue.Pipeline.ID, status)
+ }
+
+ // Query schema.
+ for _, stagingInstance := range stagingInstances {
+ result, err := ctl.query(stagingInstance, databaseName)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if schemaSQLResult != result {
+ t.Fatalf("SQL result want %q, got %q, diff %q", schemaSQLResult, result, pretty.Diff(schemaSQLResult, result))
+ }
+ }
+ for _, prodInstance := range prodInstances {
+ result, err := ctl.query(prodInstance, databaseName)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if schemaSQLResult != result {
+ t.Fatalf("SQL result want %q, got %q, diff %q", schemaSQLResult, result, pretty.Diff(schemaSQLResult, result))
+ }
+ }
+}
diff --git a/tests/tests.go b/tests/tests.go
index 75e0f28d76..ec81c49f84 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -34,6 +34,49 @@ var (
gitAPIURL = fmt.Sprintf("%s/api/v4", gitURL)
)
+var (
+ deploymentSchdule = 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"},
+ },
+ {
+ Key: api.TenantLabelKey,
+ Operator: api.ExistsOperatorType,
+ },
+ },
+ },
+ },
+ },
+ {
+ Name: "Prod stage",
+ Spec: &api.DeploymentSpec{
+ Selector: &api.LabelSelector{
+ MatchExpressions: []*api.LabelSelectorRequirement{
+ {
+ Key: api.EnvironmentKeyName,
+ Operator: api.InOperatorType,
+ Values: []string{"Prod"},
+ },
+ {
+ Key: api.TenantLabelKey,
+ Operator: api.ExistsOperatorType,
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+)
+
type controller struct {
main *cmd.Main
client *http.Client