Skip to content

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

refactor: move some code to helper functions to reduce the function size; this is to prepare tenant schema updates in webhook (#316)

spinningbotb7b69708144d
diff --git a/server/project.go b/server/project.go
index 16abf15c2a..b1d5a60d5c 100644
--- a/server/project.go
+++ b/server/project.go
@@ -196,7 +196,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
}
}
- webhookId, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).CreateWebhook(
+ webhookID, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).CreateWebhook(
ctx,
common.OauthContext{
AccessToken: repositoryCreate.AccessToken,
@@ -211,7 +211,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create webhook for project ID: %v", repositoryCreate.ProjectID)).SetInternal(err)
}
- repositoryCreate.ExternalWebhookID = webhookId
+ repositoryCreate.ExternalWebhookID = webhookID
repositoryCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)
// Remove enclosing /
diff --git a/server/webhook.go b/server/webhook.go
index 4062d07ca8..fa0b643710 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -86,25 +86,8 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
// Ignored the schema file we auto generated to the repository.
- if repository.SchemaPathTemplate != "" {
- placeholderList := []string{
- "ENV_NAME",
- "DB_NAME",
- }
- schemafilePathRegex := repository.SchemaPathTemplate
- for _, placeholder := range placeholderList {
- schemafilePathRegex = strings.ReplaceAll(schemafilePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))
- }
- myRegex, err := regexp.Compile(schemafilePathRegex)
- if err != nil {
- s.l.Warn("Invalid schema path template.", zap.String("schema_path_template",
- repository.SchemaPathTemplate),
- zap.Error(err),
- )
- }
- if myRegex.MatchString(added) {
- continue
- }
+ if isSkipGeneratedSchemaFile(repository, added, s.l) {
+ continue
}
vcsPushEvent := vcs.VCSPushEvent{
@@ -183,151 +166,177 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
continue
}
- // Find matching database list
- databaseFind := &api.DatabaseFind{
- ProjectID: &repository.ProjectID,
- Name: &mi.Database,
- }
- databaseList, err := s.composeDatabaseListByFind(ctx, databaseFind)
+ // Create schema update issue.
+ issue, err := s.createSchemaUpdateIssue(ctx, repository, mi, vcsPushEvent, commit, added, string(b))
if err != nil {
- createIgnoredFileActivity(fmt.Errorf("failed to find database matching database %q referenced by the committed file", mi.Database))
- continue
- } else if len(databaseList) == 0 {
- createIgnoredFileActivity(fmt.Errorf("project ID %d does not own database %q referenced by the committed file", repository.ProjectID, mi.Database))
+ createIgnoredFileActivity(err)
continue
}
+ createdMessageList = append(createdMessageList, fmt.Sprintf("Created issue %q on adding %s", issue.Name, added))
- // We support 3 patterns on how to organize the schema files.
- // Pattern 1: The database name is the same across all environments. Each environment will have its own directory, so the
- // schema file looks like "dev/v1__db1", "staging/v1__db1".
- //
- // Pattern 2: Like 1, the database name is the same across all environments. All environment shares the same schema file,
- // say v1__db1, when a new file is added like v2__db1__add_column, we will create a multi stage pipeline where
- // each stage corresponds to an environment.
- //
- // Pattern 3: The database name is different among different environments. In such case, the database name alone is enough
- // to identify ambiguity.
-
- // Further filter by environment name if applicable.
- filteredDatabaseList := []*api.Database{}
- if mi.Environment != "" {
- for _, database := range databaseList {
- // Environment name comparision is case insensitive
- if strings.EqualFold(database.Instance.Environment.Name, mi.Environment) {
- filteredDatabaseList = append(filteredDatabaseList, database)
- }
- }
- if len(filteredDatabaseList) == 0 {
- createIgnoredFileActivity(fmt.Errorf("project does not contain committed file database %q for environment %q", mi.Database, mi.Environment))
- continue
- }
- } else {
- filteredDatabaseList = databaseList
- }
-
- var pipelineApprovalByEnv = map[int]api.PipelineApprovalValue{}
- {
- // It could happen that for a particular environment a project contain 2 database with the same name.
- // We will emit warning in this case.
- var databaseListByEnv = map[int][]*api.Database{}
- for _, database := range filteredDatabaseList {
- list, ok := databaseListByEnv[database.Instance.EnvironmentID]
- if ok {
- databaseListByEnv[database.Instance.EnvironmentID] = append(list, database)
- } else {
- list := make([]*api.Database, 0)
- databaseListByEnv[database.Instance.EnvironmentID] = append(list, database)
- }
-
- // Load pipeline approval policy per environment.
- if _, ok := pipelineApprovalByEnv[database.Instance.EnvironmentID]; !ok {
- p, err := s.PolicyService.GetPipelineApprovalPolicy(ctx, database.Instance.EnvironmentID)
- if err != nil {
- createIgnoredFileActivity(fmt.Errorf("failed to find pipeline approval policy for environment %v", database.Instance.EnvironmentID))
- continue
- }
- pipelineApprovalByEnv[database.Instance.EnvironmentID] = p.Value
- }
- }
-
- var multipleDatabaseForSameEnv = false
- for environmentID, databaseList := range databaseListByEnv {
- if len(databaseList) > 1 {
- multipleDatabaseForSameEnv = true
-
- s.l.Warn(fmt.Sprintf("Ignored committed file, multiple ambiguous databases named %q for environment %d.", mi.Database, environmentID),
- zap.Int("project_id", repository.ProjectID),
- zap.String("file", added),
- )
- }
- }
-
- if multipleDatabaseForSameEnv {
- continue
- }
+ // Create a project activity after successfully creating the issue as the result of the push event
+ bytes, err := json.Marshal(api.ActivityProjectRepositoryPushPayload{
+ VCSPushEvent: vcsPushEvent,
+ IssueID: issue.ID,
+ IssueName: issue.Name,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)
}
- // Compose the new issue
- m := &api.UpdateSchemaContext{
- MigrationType: mi.Type,
- VCSPushEvent: &vcsPushEvent,
+ activityCreate := &api.ActivityCreate{
+ CreatorID: api.SystemBotID,
+ ContainerID: repository.ProjectID,
+ Type: api.ActivityProjectRepositoryPush,
+ Level: api.ActivityInfo,
+ Comment: fmt.Sprintf("Created issue %q.", issue.Name),
+ Payload: string(bytes),
}
- for _, database := range filteredDatabaseList {
- m.UpdateSchemaDetailList = append(m.UpdateSchemaDetailList,
- &api.UpdateSchemaDetail{
- DatabaseID: database.ID,
- Statement: string(b),
- })
- }
- createContext, err := json.Marshal(m)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct issue create context payload").SetInternal(err)
- }
- issueCreate := &api.IssueCreate{
- ProjectID: repository.ProjectID,
- Name: commit.Title,
- Type: api.IssueDatabaseSchemaUpdate,
- Description: commit.Message,
- AssigneeID: api.SystemBotID,
- CreateContext: string(createContext),
+ if _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issue.ID)).SetInternal(err)
}
+ }
+ }
+
+ return c.String(http.StatusOK, strings.Join(createdMessageList, "\n"))
+ })
+}
- issue, err := s.createIssue(ctx, issueCreate, api.SystemBotID)
+func (s *Server) createSchemaUpdateIssue(ctx context.Context, repository *api.Repository, mi *db.MigrationInfo, vcsPushEvent vcs.VCSPushEvent, commit gitlab.WebhookCommit, added string, statement string) (*api.Issue, error) {
+ // Find matching database list
+ databaseFind := &api.DatabaseFind{
+ ProjectID: &repository.ProjectID,
+ Name: &mi.Database,
+ }
+ databaseList, err := s.composeDatabaseListByFind(ctx, databaseFind)
+ if err != nil {
+ return nil, fmt.Errorf("failed to find database matching database %q referenced by the committed file", mi.Database)
+ } else if len(databaseList) == 0 {
+ return nil, fmt.Errorf("project ID %d does not own database %q referenced by the committed file", repository.ProjectID, mi.Database)
+ }
+
+ // We support 3 patterns on how to organize the schema files.
+ // Pattern 1: The database name is the same across all environments. Each environment will have its own directory, so the
+ // schema file looks like "dev/v1__db1", "staging/v1__db1".
+ //
+ // Pattern 2: Like 1, the database name is the same across all environments. All environment shares the same schema file,
+ // say v1__db1, when a new file is added like v2__db1__add_column, we will create a multi stage pipeline where
+ // each stage corresponds to an environment.
+ //
+ // Pattern 3: The database name is different among different environments. In such case, the database name alone is enough
+ // to identify ambiguity.
+
+ // Further filter by environment name if applicable.
+ filteredDatabaseList := []*api.Database{}
+ if mi.Environment != "" {
+ for _, database := range databaseList {
+ // Environment name comparision is case insensitive
+ if strings.EqualFold(database.Instance.Environment.Name, mi.Environment) {
+ filteredDatabaseList = append(filteredDatabaseList, database)
+ }
+ }
+ if len(filteredDatabaseList) == 0 {
+ return nil, fmt.Errorf("project does not contain committed file database %q for environment %q", mi.Database, mi.Environment)
+ }
+ } else {
+ filteredDatabaseList = databaseList
+ }
+
+ var pipelineApprovalByEnv = map[int]api.PipelineApprovalValue{}
+ {
+ // It could happen that for a particular environment a project contain 2 database with the same name.
+ // We will emit warning in this case.
+ var databaseListByEnv = map[int][]*api.Database{}
+ for _, database := range filteredDatabaseList {
+ list, ok := databaseListByEnv[database.Instance.EnvironmentID]
+ if ok {
+ databaseListByEnv[database.Instance.EnvironmentID] = append(list, database)
+ } else {
+ list := make([]*api.Database, 0)
+ databaseListByEnv[database.Instance.EnvironmentID] = append(list, database)
+ }
+
+ // Load pipeline approval policy per environment.
+ if _, ok := pipelineApprovalByEnv[database.Instance.EnvironmentID]; !ok {
+ p, err := s.PolicyService.GetPipelineApprovalPolicy(ctx, database.Instance.EnvironmentID)
if err != nil {
- s.l.Warn("Failed to create update schema task for added repository file", zap.Error(err),
- zap.String("file", added))
- continue
+ return nil, fmt.Errorf("failed to find pipeline approval policy for environment %v", database.Instance.EnvironmentID)
}
+ pipelineApprovalByEnv[database.Instance.EnvironmentID] = p.Value
+ }
+ }
- createdMessageList = append(createdMessageList, fmt.Sprintf("Created issue %q on adding %s", issue.Name, added))
+ var multipleDatabaseForSameEnv = false
+ for environmentID, databaseList := range databaseListByEnv {
+ if len(databaseList) > 1 {
+ multipleDatabaseForSameEnv = true
- // Create a project activity after successfully creating the issue as the result of the push event
- {
- bytes, err := json.Marshal(api.ActivityProjectRepositoryPushPayload{
- VCSPushEvent: vcsPushEvent,
- IssueID: issue.ID,
- IssueName: issue.Name,
- })
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)
- }
-
- activityCreate := &api.ActivityCreate{
- CreatorID: api.SystemBotID,
- ContainerID: repository.ProjectID,
- Type: api.ActivityProjectRepositoryPush,
- Level: api.ActivityInfo,
- Comment: fmt.Sprintf("Created issue %q.", issue.Name),
- Payload: string(bytes),
- }
- _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issue.ID)).SetInternal(err)
- }
- }
+ s.l.Warn(fmt.Sprintf("Ignored committed file, multiple ambiguous databases named %q for environment %d.", mi.Database, environmentID),
+ zap.Int("project_id", repository.ProjectID),
+ zap.String("file", added),
+ )
}
}
- return c.String(http.StatusOK, strings.Join(createdMessageList, "\n"))
- })
+ if multipleDatabaseForSameEnv {
+ return nil, nil
+ }
+ }
+
+ // Compose the new issue
+ m := &api.UpdateSchemaContext{
+ MigrationType: mi.Type,
+ VCSPushEvent: &vcsPushEvent,
+ }
+ for _, database := range filteredDatabaseList {
+ m.UpdateSchemaDetailList = append(m.UpdateSchemaDetailList,
+ &api.UpdateSchemaDetail{
+ DatabaseID: database.ID,
+ Statement: statement,
+ })
+ }
+ createContext, err := json.Marshal(m)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to construct issue create context payload, error %v", err)
+ }
+ issueCreate := &api.IssueCreate{
+ ProjectID: repository.ProjectID,
+ Name: commit.Title,
+ Type: api.IssueDatabaseSchemaUpdate,
+ Description: commit.Message,
+ AssigneeID: api.SystemBotID,
+ CreateContext: string(createContext),
+ }
+
+ issue, err := s.createIssue(ctx, issueCreate, api.SystemBotID)
+ if err != nil {
+ s.l.Warn("Failed to create update schema task for added repository file", zap.Error(err),
+ zap.String("file", added))
+ return nil, nil
+ }
+ return issue, nil
+}
+
+func isSkipGeneratedSchemaFile(repository *api.Repository, added string, logger *zap.Logger) bool {
+ if repository.SchemaPathTemplate != "" {
+ placeholderList := []string{
+ "ENV_NAME",
+ "DB_NAME",
+ }
+ schemafilePathRegex := repository.SchemaPathTemplate
+ for _, placeholder := range placeholderList {
+ schemafilePathRegex = strings.ReplaceAll(schemafilePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))
+ }
+ myRegex, err := regexp.Compile(schemafilePathRegex)
+ if err != nil {
+ logger.Warn("Invalid schema path template.", zap.String("schema_path_template",
+ repository.SchemaPathTemplate),
+ zap.Error(err),
+ )
+ }
+ if myRegex.MatchString(added) {
+ return true
+ }
+ }
+ return false
}