76 lines
1.5 KiB
Go
76 lines
1.5 KiB
Go
|
// go:build postgres
|
||
|
|
||
|
package postgres
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"embed"
|
||
|
|
||
|
"github.com/golang-migrate/migrate/v4"
|
||
|
"github.com/golang-migrate/migrate/v4/database/postgres"
|
||
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||
|
)
|
||
|
|
||
|
type PostgresStorage struct {
|
||
|
db *sql.DB
|
||
|
fs embed.FS
|
||
|
}
|
||
|
|
||
|
func NewStoragePostgres(fs embed.FS) func(*sql.DB) (interface{}, error) {
|
||
|
return func(db *sql.DB) (interface{}, error) {
|
||
|
return &PostgresStorage{db: db, fs: fs}, nil
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (s *PostgresStorage) MigrateUp() error {
|
||
|
driver, err := postgres.WithInstance(s.db, &postgres.Config{
|
||
|
MigrationsTable: postgres.DefaultMigrationsTable,
|
||
|
DatabaseName: "template",
|
||
|
})
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
source, err := iofs.New(s.fs, "migrations/postgres")
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
// TODO: pass own logger
|
||
|
m, err := migrate.NewWithInstance("fs", source, "template", driver)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if err = m.Up(); err != nil && err != migrate.ErrNoChange {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (s *PostgresStorage) MigrateDown() error {
|
||
|
driver, err := postgres.WithInstance(s.db, &postgres.Config{
|
||
|
MigrationsTable: postgres.DefaultMigrationsTable,
|
||
|
DatabaseName: "template",
|
||
|
})
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
source, err := iofs.New(s.fs, "migrations/postgres")
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
// TODO: pass own logger
|
||
|
m, err := migrate.NewWithInstance("fs", source, "template", driver)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if err = m.Down(); err != nil && err != migrate.ErrNoChange {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|