pkgdash/storage/postgres/storage.go

84 lines
1.6 KiB
Go
Raw Normal View History

package postgres
import (
"database/sql"
"embed"
"errors"
"go.unistack.org/unistack-org/pkgdash/config"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/pgx"
"github.com/golang-migrate/migrate/v4/source/iofs"
)
const (
pathMigration = `migrations/postgres`
)
type Postgres struct {
db *sql.DB
fs embed.FS
}
func NewStorage(db *sql.DB) (interface{}, error) {
return &Postgres{db: db}, nil
}
func NewStorageFS(fs embed.FS) func(*sql.DB) (interface{}, error) {
return func(db *sql.DB) (interface{}, error) {
return &Postgres{db: db, fs: fs}, nil
}
}
func (s *Postgres) MigrateUp() error {
driver, err := pgx.WithInstance(s.db, &pgx.Config{
MigrationsTable: pgx.DefaultMigrationsTable,
DatabaseName: config.ServiceName,
})
if err != nil {
return err
}
source, err := iofs.New(s.fs, pathMigration)
if err != nil {
return err
}
// TODO: pass own logger
m, err := migrate.NewWithInstance("fs", source, config.ServiceName, driver)
if err != nil {
return err
}
if err = m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
return err
}
return nil
}
func (s *Postgres) MigrateDown() error {
driver, err := pgx.WithInstance(s.db, &pgx.Config{
MigrationsTable: pgx.DefaultMigrationsTable,
DatabaseName: config.ServiceName,
})
if err != nil {
return err
}
source, err := iofs.New(s.fs, pathMigration)
if err != nil {
return err
}
// TODO: pass own logger
m, err := migrate.NewWithInstance("fs", source, config.ServiceName, driver)
if err != nil {
return err
}
if err = m.Down(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
return err
}
return nil
}