Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: sync task database_id (#528)
STEVENb0f59318bccc
diff --git a/api/task.go b/api/task.goindex 3eab0349ca..f1c26db714 100644--- a/api/task.go+++ b/api/task.go@@ -133,7 +133,7 @@ type Task struct {StageID int `jsonapi:"attr,stageId"`InstanceID intInstance *Instance `jsonapi:"relation,instance"`- // Tasks like creating database may not have database.+ // Could be empty for creating database task when the task isn't yet completed successfully.DatabaseID *intDatabase *Database `jsonapi:"relation,database"`TaskRunList []*TaskRun `jsonapi:"relation,taskRun"`@@ -207,6 +207,7 @@ type TaskPatch struct {UpdaterID int// Domain specific fields+ DatabaseID *intStatement *string `jsonapi:"attr,statement"`Payload *stringEarliestAllowedTs *int64 `jsonapi:"attr,earliestAllowedTs"`diff --git a/server/task.go b/server/task.goindex 332a7f97bd..590acc7d3a 100644--- a/server/task.go+++ b/server/task.go@@ -552,81 +552,6 @@ func (s *Server) changeTaskStatusWithPatch(ctx context.Context, task *api.Task,updatedTask = scheduledTask}- // If create database task completes, then we will create a database entry immediately- // instead of waiting for the next schema sync cycle to sync over this newly created database.- // This is for 2 reasons:- // 1. Assign the proper project to the newly created database. Otherwise, the periodic schema- // sync will place the synced db into the default project.- // 2. Allow user to see the created database right away.- if (updatedTask.Type == api.TaskDatabaseCreate) &&- updatedTask.Status == api.TaskDone {- payload := &api.TaskDatabaseCreatePayload{}- if err := json.Unmarshal([]byte(updatedTask.Payload), payload); err != nil {- return nil, fmt.Errorf("invalid create database task payload: %w", err)- }-- instance, err := s.InstanceService.FindInstance(ctx, &api.InstanceFind{- ID: &task.InstanceID,- })- if err != nil {- return nil, fmt.Errorf("failed to find instance: %v", task.InstanceID)- }- if instance == nil {- return nil, fmt.Errorf("instance ID not found %v", task.InstanceID)- }- project, err := s.composeProjectByID(ctx, payload.ProjectID)- if err != nil {- return nil, fmt.Errorf("failed to find project: %v", payload.ProjectID)- }- if project == nil {- return nil, fmt.Errorf("project ID not found %v", payload.ProjectID)- }-- databaseCreate := &api.DatabaseCreate{- CreatorID: taskStatusPatch.UpdaterID,- ProjectID: payload.ProjectID,- InstanceID: task.InstanceID,- EnvironmentID: instance.EnvironmentID,- Name: payload.DatabaseName,- CharacterSet: payload.CharacterSet,- Collation: payload.Collation,- Labels: &payload.Labels,- SchemaVersion: payload.SchemaVersion,- }- database, err := s.DatabaseService.CreateDatabase(ctx, databaseCreate)- if err != nil {- // Just emits an error instead of failing, since we have another periodic job to sync db info.- // Though the db will be assigned to the default project instead of the desired project in that case.- s.l.Error("failed to record database after creating database",- zap.String("database_name", payload.DatabaseName),- zap.Int("project_id", payload.ProjectID),- zap.Int("instance_id", task.InstanceID),- zap.Error(err),- )- }- err = s.composeDatabaseRelationship(ctx, database)- if err != nil {- s.l.Error("failed to compose database relationship after creating database",- zap.String("database_name", payload.DatabaseName),- zap.Int("project_id", payload.ProjectID),- zap.Int("instance_id", task.InstanceID),- zap.Error(err),- )- }- // Set database labels, except bb.environment is immutable and must match instance environment.- // This needs to be after we compose database relationship.- if err == nil && databaseCreate.Labels != nil && *databaseCreate.Labels != "" {- if err := s.setDatabaseLabels(ctx, *databaseCreate.Labels, database, project, databaseCreate.CreatorID, false /* validateOnly */); err != nil {- s.l.Error("failed to record database labels after creating database",- zap.String("database_name", payload.DatabaseName),- zap.Int("project_id", payload.ProjectID),- zap.Int("instance_id", task.InstanceID),- zap.Error(err),- )- }- }- }-// If create database or schema update task completes, we sync the corresponding instance schema immediately.if (updatedTask.Type == api.TaskDatabaseCreate || updatedTask.Type == api.TaskDatabaseSchemaUpdate) &&updatedTask.Status == api.TaskDone {diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.goindex 4834cf19f0..4eb059c063 100644--- a/server/task_executor_database_create.go+++ b/server/task_executor_database_create.go@@ -120,6 +120,66 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Serreturn true, nil, err}+ // If the database creation statement executed successfully,+ // then we will create a database entry immediately+ // instead of waiting for the next schema sync cycle to sync over this newly created database.+ // This is for 2 reasons:+ // 1. Assign the proper project to the newly created database. Otherwise, the periodic schema+ // sync will place the synced db into the default project.+ // 2. Allow user to see the created database right away.+ databaseCreate := &api.DatabaseCreate{+ CreatorID: api.SystemBotID,+ ProjectID: payload.ProjectID,+ InstanceID: task.InstanceID,+ EnvironmentID: instance.EnvironmentID,+ Name: payload.DatabaseName,+ CharacterSet: payload.CharacterSet,+ Collation: payload.Collation,+ Labels: &payload.Labels,+ SchemaVersion: payload.SchemaVersion,+ }+ database, err := server.DatabaseService.CreateDatabase(ctx, databaseCreate)+ if err != nil {+ return true, nil, err+ }++ // After the task related database entry created successfully,+ // we need to update task's database_id with the newly created database immediately.+ // Here is the main reason:+ // The task database_id represents its related database entry both for creating and patching,+ // so we should sync its value right here when the related database entry created.+ taskDatabaseIDPatch := &api.TaskPatch{+ ID: task.ID,+ UpdaterID: api.SystemBotID,+ DatabaseID: &database.ID,+ }+ _, err = server.TaskService.PatchTask(ctx, taskDatabaseIDPatch)+ if err != nil {+ return true, nil, err+ }++ if database.Labels != "" {+ // Compose database relationship for setting database labels.+ err = server.composeDatabaseRelationship(ctx, database)+ if err != nil {+ return true, nil, err+ }++ project, err := server.composeProjectByID(ctx, payload.ProjectID)+ if err != nil {+ return true, nil, fmt.Errorf("failed to find project: %v", payload.ProjectID)+ }+ if project == nil {+ return true, nil, fmt.Errorf("project ID not found %v", payload.ProjectID)+ }++ // Set database labels, except bb.environment is immutable and must match instance environment.+ err = server.setDatabaseLabels(ctx, database.Labels, database, project, database.CreatorID, false)+ if err != nil {+ return true, nil, fmt.Errorf("failed to record database labels after creating database %v", database.ID)+ }+ }+return true, &api.TaskRunResultPayload{Detail: fmt.Sprintf("Created database %q", payload.DatabaseName),MigrationID: migrationID,diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sqlindex 9ab4185a9b..a3fc0d37de 100644--- a/store/migration/10001__init_schema.sql+++ b/store/migration/10001__init_schema.sql@@ -829,7 +829,7 @@ CREATE TABLE task (pipeline_id INTEGER NOT NULL REFERENCES pipeline (id),stage_id INTEGER NOT NULL REFERENCES stage (id),instance_id INTEGER NOT NULL REFERENCES instance (id),- -- Could be empty for tasks like creating database+ -- Could be empty for creating database task when the task isn't yet completed successfully.database_id INTEGER REFERENCES db (id),name TEXT NOT NULL,-- allowed status are 'PENDING', 'PENDING_APPROVAL', 'RUNNING', 'DONE', 'FAILED', 'CANCELED'.diff --git a/store/task.go b/store/task.goindex b2f87a7a37..5fc215b997 100644--- a/store/task.go+++ b/store/task.go@@ -333,6 +333,9 @@ func (s *TaskService) findTaskList(ctx context.Context, tx *Tx, find *api.TaskFifunc (s *TaskService) patchTask(ctx context.Context, tx *Tx, patch *api.TaskPatch) (*api.Task, error) {// Build UPDATE clause.set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterID}+ if v := patch.DatabaseID; v != nil {+ set, args = append(set, "database_id = ?"), append(args, *v)+ }if v := patch.Payload; v != nil {set, args = append(set, "payload = ?"), append(args, *v)}