diff --git a/README.md b/README.md index 8376fb1..6abc465 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,18 @@ if err != nil { list, err := q.List(context.Background()) ``` +### 5. Set migration files directory before creating migration file + +If you want to set migration files directory before creating migration file, you can use `SetMigrationFilesDir` method. This is useful when you want to dynamically set the migration files directory, e.g. passing it as a command-line argument. + +```go +q.SetMigrationFilesDir("migrations") +q.Create("add_users_table") + +// or using chain +q.SetMigrationFilesDir("migrations").Create("add_users_table") +``` + ## 📁 Migration Interface Each migration must implement the following interface: @@ -306,4 +318,4 @@ func main() { MIT License ---- \ No newline at end of file +--- diff --git a/gomigration.go b/gomigration.go index 83810dc..24dcf60 100644 --- a/gomigration.go +++ b/gomigration.go @@ -43,10 +43,6 @@ func New(config *Config) (*GoMigration, error) { return nil, fmt.Errorf("invalid migration table name: %w", err) } - if !migrationDirExists(config.MigrationFilesDir) { - return nil, fmt.Errorf("migration directory %q does not exist", config.MigrationFilesDir) - } - config.Driver.SetMigrationTableName(config.MigrationTableName) return &GoMigration{ @@ -77,9 +73,19 @@ func (q *GoMigration) Register(migrations ...Migration) error { return nil } +// Set migration files directory. +func (q *GoMigration) SetMigrationFilesDir(dir string) *GoMigration { + q.migrationFilesDir = dir + return q +} + // Create generates a new migration file using the given name. // The generated file includes a timestamp prefix and basic template content. func (q *GoMigration) Create(fileName string) error { + if !migrationDirExists(q.migrationFilesDir) { + return fmt.Errorf("migration directory %q does not exist", q.migrationFilesDir) + } + if fileName == "" { return ErrMigrationNameNotProvided } diff --git a/gomigration_test.go b/gomigration_test.go index e113e40..fa19ba2 100644 --- a/gomigration_test.go +++ b/gomigration_test.go @@ -151,6 +151,12 @@ func TestGoMigration_List(t *testing.T) { driver.AssertExpectations(t) } +func TestSetMigrationFilesDir(t *testing.T) { + q := &GoMigration{} + q.SetMigrationFilesDir("migrations") + assert.Equal(t, "migrations", q.migrationFilesDir) +} + // dummyMigration is a simple implementation of the Migration interface for testing. type dummyMigration struct { name string diff --git a/helper.go b/helper.go index 6d2c1c9..819934d 100644 --- a/helper.go +++ b/helper.go @@ -90,7 +90,7 @@ func sanitizeMigrationName(name string) (string, error) { // sanitizeTableName validates the table name. Returns an error if it contains // invalid characters. func sanitizeTableName(name string) (string, error) { - valid := regexp.MustCompile(`^[a-zA-Z0-9_]+$`) + valid := regexp.MustCompile(`^[a-zA-Z0-9_.]+$`) if !valid.MatchString(name) { return "", fmt.Errorf("invalid table name: %s", name) }