Skip to content

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

refactor: move parseSchemaFileInfo() to db package (#2905)

Danny Xu591eb1c7b1a3
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index cfb05f6097..f0f65e734d 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -6,6 +6,7 @@ import (
"database/sql"
"fmt"
"io"
+ "path"
"regexp"
"strings"
"sync"
@@ -250,6 +251,7 @@ const placeholderRegexp = `[^\\/?%*:|"<>]+`
// ParseMigrationInfo matches filePath against filePathTemplate
// If filePath matches, then it will derive MigrationInfo from the filePath.
// Both filePath and filePathTemplate are the full file path (including the base directory) of the repository.
+// It returns (nil, nil) if it doesn't looks like a schema file path.
func ParseMigrationInfo(filePath, filePathTemplate string) (*MigrationInfo, error) {
placeholderList := []string{
"ENV_NAME",
@@ -273,7 +275,8 @@ func ParseMigrationInfo(filePath, filePathTemplate string) (*MigrationInfo, erro
return nil, errors.Errorf("invalid file path template: %q", filePathTemplate)
}
if !myRegex.MatchString(filePath) {
- return nil, errors.Errorf("file path %q does not match file path template %q", filePath, filePathTemplate)
+ // File path does not match file path template.
+ return nil, nil
}
mi := &MigrationInfo{
@@ -337,6 +340,51 @@ func ParseMigrationInfo(filePath, filePathTemplate string) (*MigrationInfo, erro
return mi, nil
}
+// ParseSchemaFileInfo attempts to parse the given schema file path to extract
+// the schema file info.
+// It returns (nil, nil) if it doesn't looks like a schema file path.
+//
+// The possible keys for the returned map are: "ENV_NAME", "DB_NAME".
+func ParseSchemaFileInfo(baseDirectory, schemaPathTemplate, file string) (*MigrationInfo, error) {
+ if schemaPathTemplate == "" {
+ return nil, nil
+ }
+
+ // Escape "." characters to match literals instead of using it as a wildcard.
+ schemaFilePathRegex := strings.ReplaceAll(schemaPathTemplate, ".", `\.`)
+
+ placeholders := []string{
+ "ENV_NAME",
+ "DB_NAME",
+ }
+ for _, placeholder := range placeholders {
+ schemaFilePathRegex = strings.ReplaceAll(schemaFilePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))
+ }
+
+ // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.
+ re, err := regexp.Compile(path.Join(baseDirectory, schemaFilePathRegex))
+ if err != nil {
+ return nil, errors.Wrap(err, "compile schema file path regex")
+ }
+ match := re.FindStringSubmatch(file)
+ if len(match) == 0 {
+ return nil, nil
+ }
+
+ info := make(map[string]string)
+ // Skip the first item because it is always the empty string, see docstring of
+ // the SubexpNames() method.
+ for i, name := range re.SubexpNames()[1:] {
+ info[name] = match[i+1]
+ }
+ return &MigrationInfo{
+ Source: VCS,
+ Type: Migrate,
+ Environment: info["ENV_NAME"],
+ Database: info["DB_NAME"],
+ }, nil
+}
+
// MigrationHistory is the API message for migration history.
type MigrationHistory struct {
ID int
diff --git a/plugin/db/driver_test.go b/plugin/db/driver_test.go
index e450045e66..3083720dab 100644
--- a/plugin/db/driver_test.go
+++ b/plugin/db/driver_test.go
@@ -4,6 +4,7 @@ import (
"fmt"
"testing"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -11,7 +12,7 @@ func TestParseMigrationInfo(t *testing.T) {
type test struct {
filePath string
filePathTemplate string
- want MigrationInfo
+ want *MigrationInfo
wantErr string
}
@@ -19,7 +20,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db1__001foo",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
@@ -34,7 +35,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db foo_+-=_#!$.__1.2.3",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "1.2.3",
Namespace: "db foo_+-=_#!$.",
Database: "db foo_+-=_#!$.",
@@ -49,7 +50,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "bytebase/db1__001foo",
filePathTemplate: "bytebase/{{DB_NAME}}__{{VERSION}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
@@ -64,7 +65,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "bytebase/dev/db1__001foo",
filePathTemplate: "bytebase/{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
@@ -79,7 +80,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db1__001foo__create_t1",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{DESCRIPTION}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
@@ -94,7 +95,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db1__001foo__migrate",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
@@ -109,7 +110,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db1__001foo__ddl",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
@@ -124,7 +125,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db1__001foo__dml",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
@@ -139,7 +140,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db_shop1__001foo__data",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db_shop1",
Database: "db_shop1",
@@ -154,7 +155,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db_shop1__001foo__data__fix_customer_info",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db_shop1",
Database: "db_shop1",
@@ -169,7 +170,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: ".db__20220811.sql",
filePathTemplate: ".{{DB_NAME}}__{{VERSION}}.sql",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "20220811",
Namespace: "db",
Database: "db",
@@ -184,7 +185,7 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db1__001foo__baseline",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}",
- want: MigrationInfo{
+ want: &MigrationInfo{
Version: "001foo",
Namespace: "db1",
Database: "db1",
@@ -199,30 +200,14 @@ func TestParseMigrationInfo(t *testing.T) {
{
filePath: "db",
filePathTemplate: "{{DB_NAME}}__{{VERSION}}",
- want: MigrationInfo{
- Version: "",
- Namespace: "",
- Database: "",
- Environment: "",
- Type: "",
- Description: "",
- Creator: "",
- },
- wantErr: "does not match file path template",
+ want: nil,
+ wantErr: "",
},
{ // Make sure the "." is escaped and should only match literals not as a wildcard
filePath: ".db__20220811.sql",
filePathTemplate: "A{{DB_NAME}}__{{VERSION}}Asql",
- want: MigrationInfo{
- Version: "",
- Namespace: "",
- Database: "",
- Environment: "",
- Type: "",
- Description: "",
- Creator: "",
- },
- wantErr: "does not match file path template",
+ want: nil,
+ wantErr: "",
},
}
for _, tc := range tests {
@@ -234,7 +219,79 @@ func TestParseMigrationInfo(t *testing.T) {
return
}
require.NoError(t, err)
- require.Equal(t, tc.want, *mi)
+ if tc.want == nil {
+ require.Nil(t, mi)
+ } else {
+ require.Equal(t, *tc.want, *mi)
+ }
+ })
+ }
+}
+
+func TestParseSchemaFileInfo(t *testing.T) {
+ tests := []struct {
+ name string
+ baseDirectory string
+ schemaPathTemplate string
+ file string
+ schemaInfo *MigrationInfo
+ }{
+ {
+ name: "no schemaPathTemplate",
+ baseDirectory: "",
+ schemaPathTemplate: "",
+ file: "Test/testdb__LATEST.sql",
+ schemaInfo: nil,
+ },
+ {
+ name: "only has DB_NAME",
+ baseDirectory: "",
+ schemaPathTemplate: "{{DB_NAME}}__LATEST.sql",
+ file: "testdb__LATEST.sql",
+ schemaInfo: &MigrationInfo{
+ Source: VCS,
+ Type: Migrate,
+ Database: "testdb",
+ },
+ },
+ {
+ name: "has both ENV_NAME and DB_NAME",
+ baseDirectory: "",
+ schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
+ file: "Test/testdb__LATEST.sql",
+ schemaInfo: &MigrationInfo{
+ Source: VCS,
+ Type: Migrate,
+ Environment: "Test",
+ Database: "testdb",
+ },
+ },
+
+ {
+ name: "baseDirectory does not match",
+ baseDirectory: "bytebase",
+ schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
+ file: "Test/testdb__LATEST.sql",
+ schemaInfo: nil,
+ },
+ {
+ name: "baseDirectory with both ENV_NAME and DB_NAME",
+ baseDirectory: "bytebase",
+ schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
+ file: "bytebase/Test/testdb__LATEST.sql",
+ schemaInfo: &MigrationInfo{
+ Source: VCS,
+ Type: Migrate,
+ Environment: "Test",
+ Database: "testdb",
+ },
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got, err := ParseSchemaFileInfo(test.baseDirectory, test.schemaPathTemplate, test.file)
+ require.NoError(t, err)
+ assert.Equal(t, test.schemaInfo, got)
})
}
}
diff --git a/server/webhook.go b/server/webhook.go
index 5590641d0b..d9996f18b8 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -12,7 +12,6 @@ import (
"io"
"net/http"
"path"
- "regexp"
"strings"
"github.com/labstack/echo/v4"
@@ -218,6 +217,11 @@ func (s *Server) processPushEvent(ctx context.Context, repositoryList []*api.Rep
var createdMessages []string
for _, item := range distinctFileList {
+ log.Debug("Processing file",
+ zap.String("file", item.FileName),
+ zap.String("commit", item.Commit.ID),
+ )
+
var createdMessageList []string
repoID2ActivityCreateList := make(map[int][]*api.ActivityCreate)
for _, repo := range repositoryList {
@@ -287,11 +291,6 @@ func (s *Server) processFile(ctx context.Context, pushEvent *vcs.PushEvent, repo
}
}
- log.Debug("Processing file",
- zap.String("file", file),
- zap.String("commit", pushEvent.FileCommit.ID),
- )
-
if !strings.HasPrefix(file, repo.BaseDirectory) {
log.Debug("Ignored file outside the base directory",
zap.String("file", file),
@@ -300,7 +299,7 @@ func (s *Server) processFile(ctx context.Context, pushEvent *vcs.PushEvent, repo
return "", false, nil, nil
}
- schemaInfo, err := parseSchemaFileInfo(repo.BaseDirectory, repo.SchemaPathTemplate, file)
+ schemaInfo, err := db.ParseSchemaFileInfo(repo.BaseDirectory, repo.SchemaPathTemplate, file)
if err != nil {
log.Debug("Failed to parse schema file info",
zap.String("file", file),
@@ -323,7 +322,7 @@ func (s *Server) processFile(ctx context.Context, pushEvent *vcs.PushEvent, repo
// Having no schema info indicates that the file is not a schema file (e.g.
// "*__LATEST.sql"), try to parse the migration info see if it is a data update.
migrationDetailList, activityCreateList = s.prepareIssueFromPushEventSDL(ctx, repo, pushEvent, schemaInfo, file)
- migrationDescription = "Apply_schema_diff"
+ migrationDescription = "Apply schema diff"
migrationType = db.Migrate
} else {
// NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.
@@ -337,6 +336,14 @@ func (s *Server) processFile(ctx context.Context, pushEvent *vcs.PushEvent, repo
)
return "", false, nil, nil
}
+ if migrationInfo == nil {
+ log.Error("File path does not match file path template",
+ zap.Int("project", repo.ProjectID),
+ zap.String("file", file),
+ zap.String("file_path_template", path.Join(repo.BaseDirectory, repo.FilePathTemplate)),
+ )
+ return "", false, nil, nil
+ }
migrationDescription = migrationInfo.Description
migrationType = migrationInfo.Type
@@ -557,8 +564,8 @@ func (s *Server) readFileContent(ctx context.Context, pushEvent *vcs.PushEvent,
// prepareIssueFromPushEventSDL returns the migration info and a list of update
// schema details derived from the given push event for SDL.
-func (s *Server) prepareIssueFromPushEventSDL(ctx context.Context, repo *api.Repository, pushEvent *vcs.PushEvent, schemaInfo map[string]string, file string) ([]*api.MigrationDetail, []*api.ActivityCreate) {
- dbName := schemaInfo["DB_NAME"]
+func (s *Server) prepareIssueFromPushEventSDL(ctx context.Context, repo *api.Repository, pushEvent *vcs.PushEvent, schemaInfo *db.MigrationInfo, file string) ([]*api.MigrationDetail, []*api.ActivityCreate) {
+ dbName := schemaInfo.Database
if dbName == "" {
log.Debug("Ignored schema file without a database name", zap.String("file", file))
return nil, nil
@@ -571,7 +578,7 @@ func (s *Server) prepareIssueFromPushEventSDL(ctx context.Context, repo *api.Rep
}
activityCreateList := []*api.ActivityCreate{}
- envName := schemaInfo["ENV_NAME"]
+ envName := schemaInfo.Environment
var migrationDetailList []*api.MigrationDetail
if repo.Project.TenantMode == api.TenantModeTenant {
migrationDetailList = append(migrationDetailList,
@@ -699,46 +706,6 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [
return nil
}
-// parseSchemaFileInfo attempts to parse the given schema file path to extract
-// the schema file info. It returns (nil, nil) if it doesn't looks like a schema
-// file path.
-//
-// The possible keys for the returned map are: "ENV_NAME", "DB_NAME".
-func parseSchemaFileInfo(baseDirectory, schemaPathTemplate, file string) (map[string]string, error) {
- if schemaPathTemplate == "" {
- return nil, nil
- }
-
- // Escape "." characters to match literals instead of using it as a wildcard.
- schemaFilePathRegex := strings.ReplaceAll(schemaPathTemplate, ".", `\.`)
-
- placeholders := []string{
- "ENV_NAME",
- "DB_NAME",
- }
- for _, placeholder := range placeholders {
- schemaFilePathRegex = strings.ReplaceAll(schemaFilePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))
- }
-
- // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.
- re, err := regexp.Compile(path.Join(baseDirectory, schemaFilePathRegex))
- if err != nil {
- return nil, errors.Wrap(err, "compile schema file path regex")
- }
- match := re.FindStringSubmatch(file)
- if len(match) == 0 {
- return nil, nil
- }
-
- info := make(map[string]string)
- // Skip the first item because it is always the empty string, see docstring of
- // the SubexpNames() method.
- for i, name := range re.SubexpNames()[1:] {
- info[name] = match[i+1]
- }
- return info, nil
-}
-
// computeDatabaseSchemaDiff computes the diff between current database schema
// and the given schema. It returns an empty string if there is no applicable
// diff.
diff --git a/server/webhook_test.go b/server/webhook_test.go
index c5cd3ae41c..a8a76274e1 100644
--- a/server/webhook_test.go
+++ b/server/webhook_test.go
@@ -4,7 +4,6 @@ import (
"testing"
"github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
)
func TestValidateGitHubWebhookSignature256(t *testing.T) {
@@ -78,65 +77,3 @@ func TestParseBranchNameFromGitHubRefs(t *testing.T) {
}
}
}
-
-func TestParseSchemaFileInfo(t *testing.T) {
- tests := []struct {
- name string
- baseDirectory string
- schemaPathTemplate string
- file string
- schemaInfo map[string]string
- }{
- {
- name: "no schemaPathTemplate",
- baseDirectory: "",
- schemaPathTemplate: "",
- file: "Test/testdb__LATEST.sql",
- schemaInfo: nil,
- },
- {
- name: "only has DB_NAME",
- baseDirectory: "",
- schemaPathTemplate: "{{DB_NAME}}__LATEST.sql",
- file: "testdb__LATEST.sql",
- schemaInfo: map[string]string{
- "DB_NAME": "testdb",
- },
- },
- {
- name: "has both ENV_NAME and DB_NAME",
- baseDirectory: "",
- schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
- file: "Test/testdb__LATEST.sql",
- schemaInfo: map[string]string{
- "ENV_NAME": "Test",
- "DB_NAME": "testdb",
- },
- },
-
- {
- name: "baseDirectory does not match",
- baseDirectory: "bytebase",
- schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
- file: "Test/testdb__LATEST.sql",
- schemaInfo: nil,
- },
- {
- name: "baseDirectory with both ENV_NAME and DB_NAME",
- baseDirectory: "bytebase",
- schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
- file: "bytebase/Test/testdb__LATEST.sql",
- schemaInfo: map[string]string{
- "ENV_NAME": "Test",
- "DB_NAME": "testdb",
- },
- },
- }
- for _, test := range tests {
- t.Run(test.name, func(t *testing.T) {
- got, err := parseSchemaFileInfo(test.baseDirectory, test.schemaPathTemplate, test.file)
- require.NoError(t, err)
- assert.Equal(t, test.schemaInfo, got)
- })
- }
-}