Use fs.FS
This commit is contained in:
parent
fdc83faba0
commit
1bec960e38
21
migrate.go
21
migrate.go
|
@ -5,14 +5,14 @@ import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Options contains all settings
|
// Options contains all settings
|
||||||
type Options struct {
|
type Options struct {
|
||||||
TableName string // Name used for version info table; defaults to DefaultTableName if not set
|
TableName string // Name used for version info table; defaults to DefaultTableName if not set
|
||||||
Schema string // Schema used for version info table; For PostgreSQL, ignored if not set
|
Schema string // Schema used for version info table; For PostgreSQL, ignored if not set
|
||||||
AssetPrefix string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DefaultTableName is the name used when no TableName is specified in Options
|
// DefaultTableName is the name used when no TableName is specified in Options
|
||||||
|
@ -29,15 +29,20 @@ const fileFormat = `%04d.sql`
|
||||||
// AssetFunc is a function that returns the data for the given name
|
// AssetFunc is a function that returns the data for the given name
|
||||||
type AssetFunc func(string) ([]byte, error)
|
type AssetFunc func(string) ([]byte, error)
|
||||||
|
|
||||||
// Migrate executes migrations to get to the desired version
|
// Migrate executes all migrations
|
||||||
|
// Filenames need to have incrementing numbers
|
||||||
// Downgrading is not supported as it could result in data loss
|
// Downgrading is not supported as it could result in data loss
|
||||||
func Migrate(db *sql.DB, version int, o Options, asset AssetFunc) error {
|
func Migrate(db *sql.DB, o Options, assets fs.FS) error {
|
||||||
|
entries, err := fs.ReadDir(assets, `.`)
|
||||||
|
if err != nil {
|
||||||
|
panic(`failed to read list of files`)
|
||||||
|
}
|
||||||
|
version := len(entries)
|
||||||
|
|
||||||
if o.TableName == `` {
|
if o.TableName == `` {
|
||||||
o.TableName = DefaultTableName
|
o.TableName = DefaultTableName
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
|
||||||
|
|
||||||
searchPath := `public`
|
searchPath := `public`
|
||||||
_ = db.QueryRow(`SHOW search_path`).Scan(&searchPath)
|
_ = db.QueryRow(`SHOW search_path`).Scan(&searchPath)
|
||||||
|
|
||||||
|
@ -74,7 +79,7 @@ func Migrate(db *sql.DB, version int, o Options, asset AssetFunc) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := v + 1; i <= version; i++ {
|
for i := v + 1; i <= version; i++ {
|
||||||
script, err := asset(fmt.Sprintf(o.AssetPrefix+fileFormat, i))
|
script, err := fs.ReadFile(assets, fmt.Sprintf(fileFormat, i))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ErrUpdatesMissing
|
return ErrUpdatesMissing
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue