fixed migrator and added logging

This commit is contained in:
fanir 2022-02-22 20:06:34 +01:00
parent a7d08500f5
commit baddf9745e
3 changed files with 23 additions and 7 deletions

View file

@ -2,6 +2,7 @@ package database
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"log" "log"
"time" "time"
@ -14,7 +15,10 @@ var LogName string
// ParseConfig parses the database config string and sets LogName. // ParseConfig parses the database config string and sets LogName.
func ParseConfig(config string) (*pgxpool.Config, error) { func ParseConfig(config string) (*pgxpool.Config, error) {
dbConfig, err := pgxpool.ParseConfig(config) dbConfig, err := pgxpool.ParseConfig(config)
LogName = fmt.Sprintf("%s@%s:%s/%s", dbConfig.ConnConfig.User, dbConfig.ConnConfig.Host, dbConfig.ConnConfig.Port, dbConfig.ConnConfig.Database) LogName = fmt.Sprintf("%s@%s:%d/%s", dbConfig.ConnConfig.User, dbConfig.ConnConfig.Host, dbConfig.ConnConfig.Port, dbConfig.ConnConfig.Database)
if dbConfig.ConnConfig.Database == "" {
return nil, errors.New("database name not set, please check your connection string")
}
return dbConfig, err return dbConfig, err
} }

View file

@ -0,0 +1,14 @@
package migrator
import "log"
type Logger struct {
}
// Printf is like fmt.Printf
func (l *Logger) Printf(format string, v ...interface{}) {
log.Printf("migrator: "+format, v...)
}
// Verbose should return true when verbose logging output is wanted
func (l *Logger) Verbose() bool { return true }

View file

@ -4,9 +4,9 @@ import (
"github.com/golang-migrate/migrate/v4" "github.com/golang-migrate/migrate/v4"
migratePGX "github.com/golang-migrate/migrate/v4/database/pgx" migratePGX "github.com/golang-migrate/migrate/v4/database/pgx"
"github.com/golang-migrate/migrate/v4/source/iofs" "github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/stdlib" "github.com/jackc/pgx/v4/stdlib"
"git.zom.bi/fanir/feedizer/cmd/feedizer/internal/database"
"git.zom.bi/fanir/feedizer/models/migrations" "git.zom.bi/fanir/feedizer/models/migrations"
) )
@ -23,14 +23,11 @@ func New(dbConfig string) *Migrator {
return &Migrator{err: err} return &Migrator{err: err}
} }
connConfig, err := pgx.ParseConfig(dbConfig) poolConfig, err := database.ParseConfig(dbConfig)
if err != nil { if err != nil {
return &Migrator{err: err} return &Migrator{err: err}
} }
connString := stdlib.RegisterConnConfig(connConfig) driver, err := migratePGX.WithInstance(stdlib.OpenDB(*poolConfig.ConnConfig), &migratePGX.Config{})
var p migratePGX.Postgres
driver, err := p.Open(connString)
if err != nil { if err != nil {
return &Migrator{err: err} return &Migrator{err: err}
} }
@ -39,6 +36,7 @@ func New(dbConfig string) *Migrator {
if err != nil { if err != nil {
return &Migrator{err: err} return &Migrator{err: err}
} }
m.Log = &Logger{}
return &Migrator{m: m} return &Migrator{m: m}
} }