Thursday, 19 June 2025

GO LANG MIGRATION with embed

 GO LANG migration init by default takes a string but when using embed, it wont work, there is a work aoround:



The error "cannot use migrationFS (variable of type embed.FS) as string value in argument to migrate.New" indicates a type mismatch when attempting to use Go's embed.FS with the migrate library. The migrate.New function, when used with a file system source, expects a string path or a fs.FS interface, not directly an embed.FS variable passed as a string.
To resolve this, two common approaches are available:
  • Using migrate.NewWithSource with io/fs.FSThis is the recommended and most direct approach for embed.FSThe migrate library provides migrate.NewWithSource which can accept an io/fs.FS interface. Since embed.FS implements io/fs.FS, it can be directly passed to this function.


    import (
        "embed"
        "io/fs"

        "github.com/golang-migrate/migrate/v4"
        _ "github.com/golang-migrate/migrate/v4/database/your_database_driver" // Replace with your database driver
        "github.com/golang-migrate/migrate/v4/source/iofs"
    )

    //go:embed migrations/*.sql
    var migrationFS embed.FS

    func main() {
        // ... database connection string ...
        driver, err := iofs.New(migrationFS, "migrations") // "migrations" is the sub-directory within embed.FS
        if err != nil {
            // handle error
        }

        m, err := migrate.NewWithSourceInstance("iofs", driver, "your_database_connection_string")
        if err != nil {
            // handle error
        }

        // ... run migrations ...
    }

No comments:

Post a Comment