Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using files (go:embed) with gomigrate package

Tags:

migration

go

I want to be able to embed migration files within the output binary.

So that i can get those files as variables then use them to call the migrate functions.

The package I use is github.com/DavidHuie/gomigrate

The code below reads from the folder called ./migrations which includes a file 1_add_users_table_up.sql as well as a _down.sql.

I want to embed them using go:embed and use them directly in the function as a file.

func MigrateUp(db *sqlx.DB) error {
    migrator, _ := gomigrate.NewMigrator(db.DB, gomigrate.Postgres{}, "./migrations")

    err := migrator.Migrate()
    if err != nil {
        return err
    }

    return nil
}

EDIT:

I ended up using the package github.com/golang-migrate/migrate instead since it provides embedding the migration files.

like image 862
Hazem Hadi Avatar asked Mar 27 '26 20:03

Hazem Hadi


1 Answers

I'm using iofs driver from the example:

import "github.com/golang-migrate/migrate/v4/source/iofs"

//go:embed migrations
var migrations embed.FS

source, err := iofs.New(migrations, "migrations")
m, err := migrate.NewWithInstance("iofs", source, "postgres", db)
like image 121
Maxim Modestov Avatar answered Mar 29 '26 21:03

Maxim Modestov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!