Skip to content

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

chore: writeback to vcs for UI issues (#4683)

Danny Xue95491800f82
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.go
index 98927af7cb..7b4bd957c8 100644
--- a/backend/plugin/vcs/github/github.go
+++ b/backend/plugin/vcs/github/github.go
@@ -1263,11 +1263,6 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthConte
return nil
}
-// GetBranchNameFromRef returns the branch name from the refs.
-func (*Provider) GetBranchNameFromRef(ref string) string {
- return strings.TrimPrefix(ref, "refs/heads/")
-}
-
// oauthContext is the request context for refreshing oauth token.
type oauthContext struct {
ClientID string `json:"client_id"`
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index 06b7f86c50..798debf9cc 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -10,7 +10,6 @@ import (
"net/http"
"net/url"
"strconv"
- "strings"
"time"
"github.com/pkg/errors"
@@ -1220,11 +1219,6 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i
}, nil
}
-// GetBranchNameFromRef returns the branch name from the refs.
-func (*Provider) GetBranchNameFromRef(ref string) string {
- return strings.TrimPrefix(ref, "refs/heads/")
-}
-
// oauthContext is the request context for refreshing oauth token.
type oauthContext struct {
ClientID string `json:"client_id"`
diff --git a/backend/plugin/vcs/vcs.go b/backend/plugin/vcs/vcs.go
index fa7ccfea27..0d80d07118 100644
--- a/backend/plugin/vcs/vcs.go
+++ b/backend/plugin/vcs/vcs.go
@@ -300,8 +300,6 @@ type Provider interface {
PatchWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string, payload []byte) error
// Deletes a webhook.
DeleteWebhook(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, webhookID string) error
- // GetBranchNameFromRef gets the branch name from the refs.
- GetBranchNameFromRef(ref string) string
}
var (
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index de4d84198a..cc61939777 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -336,13 +336,19 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac
}
}
- writeBack, err := isWriteBack(ctx, stores, license, project, repo, task, vcsPushEvent)
+ writebackBranch, err := isWriteBack(ctx, stores, license, project, repo, task, vcsPushEvent)
if err != nil {
return true, nil, err
}
- // Transform the schema to standard style for SDL mode.
- if writeBack {
+ log.Debug("Post migration...",
+ zap.String("instance", instance.ResourceID),
+ zap.String("database", database.DatabaseName),
+ zap.String("writeback_branch", writebackBranch),
+ )
+
+ if writebackBranch != "" {
+ // Transform the schema to standard style for SDL mode.
if instance.Engine == db.MySQL {
standardSchema, err := transform.SchemaTransform(parser.MySQL, schema)
if err != nil {
@@ -350,18 +356,7 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac
}
schema = standardSchema
}
- }
- log.Debug("Post migration...",
- zap.String("instance", instance.ResourceID),
- zap.String("database", database.DatabaseName),
- zap.Bool("writeBack", writeBack),
- )
-
- if writeBack {
- if err != nil {
- return true, nil, errors.Wrapf(err, "failed to get BaseDatabaseName for instance %q, database %q", instance.ResourceID, database.DatabaseName)
- }
latestSchemaFile := filepath.Join(repo.BaseDirectory, repo.SchemaPathTemplate)
latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{ENV_NAME}}", mi.Environment)
latestSchemaFile = strings.ReplaceAll(latestSchemaFile, "{{DB_NAME}}", mi.Database)
@@ -380,7 +375,7 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac
bytebaseURL = fmt.Sprintf("%s/issue/%s-%d?stage=%d", profile.ExternalURL, slug.Make(issue.Title), issue.UID, task.StageID)
}
- commitID, err := writeBackLatestSchema(ctx, stores, repo, vcsPushEvent, mi, latestSchemaFile, schema, bytebaseURL)
+ commitID, err := writeBackLatestSchema(ctx, stores, repo, vcsPushEvent, mi, writebackBranch, latestSchemaFile, schema, bytebaseURL)
if err != nil {
return true, nil, err
}
@@ -451,52 +446,58 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac
}, nil
}
-func isWriteBack(ctx context.Context, stores *store.Store, license enterpriseAPI.LicenseService, project *store.ProjectMessage, repo *api.Repository, task *store.TaskMessage, vcsPushEvent *vcsPlugin.PushEvent) (bool, error) {
+func isWriteBack(ctx context.Context, stores *store.Store, license enterpriseAPI.LicenseService, project *store.ProjectMessage, repo *api.Repository, task *store.TaskMessage, vcsPushEvent *vcsPlugin.PushEvent) (string, error) {
if !license.IsFeatureEnabled(api.FeatureVCSSchemaWriteBack) {
- return false, nil
+ return "", nil
}
- if repo == nil || repo.SchemaPathTemplate == "" {
- return false, nil
+ if task.Type != api.TaskDatabaseSchemaBaseline && task.Type != api.TaskDatabaseSchemaUpdate && task.Type != api.TaskDatabaseSchemaUpdateGhostCutover {
+ return "", nil
}
- if task.Type == api.TaskDatabaseSchemaBaseline {
- if strings.Contains(repo.BranchFilter, "*") {
- return false, nil
- }
- return true, nil
+ if repo == nil || repo.SchemaPathTemplate == "" {
+ return "", nil
}
- if vcsPushEvent == nil {
- return false, nil
+ branch := ""
+ // Prefer write back to the commit branch than the repo branch.
+ if !strings.Contains(repo.BranchFilter, "*") {
+ branch = repo.BranchFilter
+ }
+ if vcsPushEvent != nil && vcsPushEvent.Ref != "" {
+ b, err := vcsPlugin.Branch(vcsPushEvent.Ref)
+ if err != nil {
+ return "", err
+ }
+ branch = b
}
- if task.Type != api.TaskDatabaseSchemaUpdate && task.Type != api.TaskDatabaseSchemaUpdateGhostCutover {
- return false, nil
+ if branch == "" {
+ return "", nil
}
// For tenant mode project, we will only write back once and we happen to write back on lastTask done.
if project.TenantMode == api.TenantModeTenant {
stages, err := stores.ListStageV2(ctx, task.PipelineID)
if err != nil {
- return false, err
+ return "", err
}
if len(stages) == 0 {
- return false, nil
+ return "", nil
}
if stages[len(stages)-1].ID != task.StageID {
- return false, nil
+ return "", nil
}
tasks, err := stores.ListTasks(ctx, &api.TaskFind{PipelineID: &task.PipelineID, StageID: &task.StageID})
if err != nil {
- return false, err
+ return "", err
}
if len(tasks) == 0 {
- return false, nil
+ return "", nil
}
if tasks[len(tasks)-1].ID != task.ID {
- return false, nil
+ return "", nil
}
}
- return true, nil
+ return branch, nil
}
func runMigration(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, license enterpriseAPI.LicenseService, stateCfg *state.State, profile config.Profile, task *store.TaskMessage, migrationType db.MigrationType, statement, schemaVersion string, vcsPushEvent *vcsPlugin.PushEvent) (terminated bool, result *api.TaskRunResultPayload, err error) {
@@ -511,9 +512,9 @@ func runMigration(ctx context.Context, store *store.Store, dbFactory *dbfactory.
return postMigration(ctx, store, activityManager, license, profile, task, vcsPushEvent, mi, migrationID, schema)
}
-// Writes back the latest schema to the repository after migration
+// Writes back the latest schema to the repository after migration.
// Returns the commit id on success.
-func writeBackLatestSchema(ctx context.Context, store *store.Store, repository *api.Repository, pushEvent *vcsPlugin.PushEvent, mi *db.MigrationInfo, latestSchemaFile string, schema string, bytebaseURL string) (string, error) {
+func writeBackLatestSchema(ctx context.Context, store *store.Store, repository *api.Repository, pushEvent *vcsPlugin.PushEvent, mi *db.MigrationInfo, writebackBranch, latestSchemaFile string, schema string, bytebaseURL string) (string, error) {
schemaFileMeta, err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).ReadFileMeta(
ctx,
common.OauthContext{
@@ -526,7 +527,7 @@ func writeBackLatestSchema(ctx context.Context, store *store.Store, repository *
repository.VCS.InstanceURL,
repository.ExternalID,
latestSchemaFile,
- pushEvent.Ref,
+ writebackBranch,
)
createSchemaFile := false
@@ -549,19 +550,21 @@ func writeBackLatestSchema(ctx context.Context, store *store.Store, repository *
if bytebaseURL != "" {
commitBody += "\n\n" + bytebaseURL
}
- commitBody += "\n\n--------Original migration change--------\n\n"
- if len(pushEvent.CommitList) == 0 {
- // For legacy data in task payload stored in the database.
- // TODO(dragonly): Remove the field FileCommit.
- commitBody += fmt.Sprintf("%s\n\n%s",
- pushEvent.FileCommit.URL,
- pushEvent.FileCommit.Message,
- )
- } else {
- commitBody += fmt.Sprintf("%s\n\n%s",
- pushEvent.CommitList[0].URL,
- pushEvent.CommitList[0].Message,
- )
+ if pushEvent != nil {
+ commitBody += "\n\n--------Original migration change--------\n\n"
+ if len(pushEvent.CommitList) == 0 {
+ // For legacy data in task payload stored in the database.
+ // TODO(dragonly): Remove the field FileCommit.
+ commitBody += fmt.Sprintf("%s\n\n%s",
+ pushEvent.FileCommit.URL,
+ pushEvent.FileCommit.Message,
+ )
+ } else {
+ commitBody += fmt.Sprintf("%s\n\n%s",
+ pushEvent.CommitList[0].URL,
+ pushEvent.CommitList[0].Message,
+ )
+ }
}
commitMessage = fmt.Sprintf("%s\n\n%s", commitTitle, commitBody)
}
@@ -578,7 +581,7 @@ func writeBackLatestSchema(ctx context.Context, store *store.Store, repository *
}
schemaFileCommit := vcsPlugin.FileCommitCreate{
- Branch: vcsPlugin.Get(repo2.VCS.Type, vcsPlugin.ProviderConfig{}).GetBranchNameFromRef(pushEvent.Ref),
+ Branch: writebackBranch,
CommitMessage: commitMessage,
Content: schema,
}
@@ -652,7 +655,7 @@ func writeBackLatestSchema(ctx context.Context, store *store.Store, repository *
repo2.VCS.InstanceURL,
repo2.ExternalID,
latestSchemaFile,
- pushEvent.Ref,
+ writebackBranch,
)
if err != nil {
diff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.go
index 363dd50e90..a138a49653 100644
--- a/backend/tests/schema_update_test.go
+++ b/backend/tests/schema_update_test.go
@@ -270,7 +270,7 @@ func TestSchemaAndDataUpdate(t *testing.T) {
a.NoError(err)
}
-func TestVCS(t *testing.T) {
+func TestVCS1(t *testing.T) {
tests := []struct {
name string
vcsProviderCreator fake.VCSProviderCreator
@@ -363,6 +363,8 @@ func TestVCS(t *testing.T) {
defer func() {
_ = ctl.Close(ctx)
}()
+ err = ctl.setLicense()
+ a.NoError(err)
// Create a VCS.
apiVCS, err := ctl.createVCS(
@@ -434,6 +436,14 @@ func TestVCS(t *testing.T) {
databaseName := "testVCSSchemaUpdate"
err = ctl.createDatabase(project, instance, databaseName, "", nil /* labelMap */)
a.NoError(err)
+ // Expecting project to have 1 database.
+ databases, err := ctl.getDatabases(api.DatabaseFind{
+ ProjectID: &project.ID,
+ })
+ a.NoError(err)
+ a.Equal(1, len(databases))
+ database := databases[0]
+ a.Equal(instance.ID, database.Instance.ID)
// Simulate Git commits for schema update.
// We create multiple commits in one push event to test for the behavior of creating one issue per database.
@@ -560,6 +570,36 @@ func TestVCS(t *testing.T) {
)
a.NoError(err)
+ // Schema change from UI.
+ // Create an issue that updates database schema.
+ createContext, err := json.Marshal(&api.MigrationContext{
+ DetailList: []*api.MigrationDetail{
+ {
+ MigrationType: db.Migrate,
+ DatabaseID: database.ID,
+ Statement: migrationStatement4,
+ },
+ },
+ })
+ a.NoError(err)
+ issue, err = ctl.createIssue(api.IssueCreate{
+ ProjectID: project.ID,
+ Name: fmt.Sprintf("update schema for database %q", databaseName),
+ Type: api.IssueDatabaseSchemaUpdate,
+ Description: fmt.Sprintf("This updates the schema of database %q.", databaseName),
+ AssigneeID: api.SystemBotID,
+ CreateContext: string(createContext),
+ })
+ a.NoError(err)
+ status, err = ctl.waitIssuePipeline(issue.ID)
+ a.NoError(err)
+ a.Equal(api.TaskDone, status)
+ latestFileName := fmt.Sprintf("%s/%s/.%s##LATEST.sql", baseDirectory, prodEnvironment.Name, database.Name)
+ files, err := ctl.vcsProvider.GetFiles(test.externalID, latestFileName)
+ a.NoError(err)
+ a.Len(files, 1)
+ a.Equal(dumpedSchema4, files[latestFileName])
+
// Get migration history.
histories, err := ctl.getInstanceMigrationHistory(instance.ID, db.MigrationHistoryFind{})
a.NoError(err)
@@ -570,6 +610,14 @@ func TestVCS(t *testing.T) {
}
wantHistories := []api.MigrationHistory{
+ {
+ Database: databaseName,
+ Source: db.UI,
+ Type: db.Migrate,
+ Status: db.Done,
+ Schema: dumpedSchema4,
+ SchemaPrev: dumpedSchema3,
+ },
{
Database: databaseName,
Source: db.VCS,
@@ -625,10 +673,10 @@ func TestVCS(t *testing.T) {
a.Equalf(wantHistories[i], got, "got histories %+v", historiesDeref)
a.NotEmpty(history.Version)
}
- a.Equal("ver4", histories[0].Version)
- a.Equal("ver3", histories[1].Version)
- a.Equal("ver2", histories[2].Version)
- a.Equal("ver1", histories[3].Version)
+ a.Equal("ver4", histories[1].Version)
+ a.Equal("ver3", histories[2].Version)
+ a.Equal("ver2", histories[3].Version)
+ a.Equal("ver1", histories[4].Version)
})
}
}
diff --git a/backend/tests/tests.go b/backend/tests/tests.go
index 15119c14fb..d181d1cbe2 100644
--- a/backend/tests/tests.go
+++ b/backend/tests/tests.go
@@ -47,6 +47,11 @@ var (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NULL
);`
+ migrationStatement4 = `
+ CREATE TABLE book4 (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NULL
+ );`
bookTableQuery = "SELECT * FROM sqlite_schema WHERE type = 'table' AND tbl_name = 'book';"
bookSchemaSQLResult = `[["type","name","tbl_name","rootpage","sql"],["TEXT","TEXT","TEXT","INT","TEXT"],[["table","book","book",2,"CREATE TABLE book (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tname TEXT NULL\n\t)"]]]`
bookDataQuery = `SELECT * FROM book;`
@@ -84,6 +89,23 @@ CREATE TABLE book3 (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NULL
);
+`
+ dumpedSchema4 = `CREATE TABLE book (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NULL
+ );
+CREATE TABLE book2 (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NULL
+ );
+CREATE TABLE book3 (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NULL
+ );
+CREATE TABLE book4 (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NULL
+ );
`
backupDump = "CREATE TABLE book (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tname TEXT NULL\n\t);\nINSERT INTO 'book' VALUES ('1', 'byte');\nINSERT INTO 'book' VALUES ('2', NULL);\n\n"