go-project-template/db/helpers.go
2024-05-05 15:10:32 -07:00

54 lines
972 B
Go

package db
import (
"context"
"database/sql"
"embed"
pgx "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
_ "github.com/jackc/pgx/v5/stdlib"
goose "github.com/pressly/goose/v3"
"github.com/sirupsen/logrus"
"git.janky.solutions/finn/go-project-template/config"
)
func Get(ctx context.Context) (*Queries, *pgx.Conn, error) {
db, err := pgx.Connect(ctx, config.C.Database)
if err != nil {
return nil, nil, err
}
return New(db), db, nil
}
//go:embed migrations
var migrations embed.FS
func Migrate(ctx context.Context) error {
logrus.Info("migrating database")
db, err := sql.Open("pgx/v5", config.C.Database)
if err != nil {
return err
}
defer db.Close()
if err = goose.SetDialect("postgres"); err != nil {
return err
}
goose.SetBaseFS(migrations)
if err = goose.Up(db, "migrations"); err != nil {
return err
}
return nil
}
func NullString(s string) pgtype.Text {
return pgtype.Text{
Valid: s != "",
String: s,
}
}