Adding a goose provider
Introduction
In this post, we'll explore the new Provider
feature recently added to the core goose package. If
you're new to goose, it's a tool for handling database migrations, available as a standalone CLI
tool and a package that can be used in Go applications.
Requires version v3.16.0 and above.
Adding a provider to your application is easy, here's a quick example:
provider, err := goose.NewProvider(
goose.DialectPostgres, // (1)!
db, // (2)!
os.DirFS("migrations"), // (3)!
)
results, err := provider.Up(ctx) // (4)!
-
The first argument is the dialect. It is the type of database technology you're using. In this case, we're using Postgres. But goose also supports:
clickhouse, mssql, mysql, postgres, redshift, sqlite3, tidb, vertica, ydb,
-
The second argument is the database connection. You can use any database driver you want, as long as it implements the
database/sql
interface.A popular choice for Postgres is pgx/v5
-
The last argument may be
nil
. Why? Because goose also supports the ability to register Go functions as migrations.However, in most cases, you'll be using SQL migrations and reading them from disk. In this case, you'll use os.DirFS or embed them into your binary and use embed.FS.
-
The last step is to invoke one of the migration methods. In this case, we're running the
Up
method, which will run all the migrations that haven't been run yet. Here's a list of all the methods:(p *Provider) ApplyVersion (p *Provider) Close (p *Provider) Down (p *Provider) DownTo (p *Provider) GetDBVersion (p *Provider) ListSources (p *Provider) Ping (p *Provider) Status (p *Provider) Up (p *Provider) UpByOne (p *Provider) UpTo