postgres.go53 lines, 1.4 KB
| 1 | // Package postgres opens the pool and runs the migrations. |
| 2 | package postgres |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "errors" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/fiston-user/murmur/db" |
| 10 | "github.com/golang-migrate/migrate/v4" |
| 11 | _ "github.com/golang-migrate/migrate/v4/database/pgx/v5" |
| 12 | "github.com/golang-migrate/migrate/v4/source/iofs" |
| 13 | "github.com/jackc/pgx/v5/pgxpool" |
| 14 | ) |
| 15 | |
| 16 | // Connect opens a pool of at least conns connections, and checks that the database answers. |
| 17 | func Connect(ctx context.Context, url string, conns int) (*pgxpool.Pool, error) { |
| 18 | cfg, err := pgxpool.ParseConfig(url) |
| 19 | if err != nil { |
| 20 | return nil, err |
| 21 | } |
| 22 | cfg.MaxConns = max(cfg.MaxConns, int32(conns)) |
| 23 | // Our statements look rows up by a key, so one plan fits every call. |
| 24 | // Left to itself, Postgres plans some of them again and again. |
| 25 | cfg.ConnConfig.RuntimeParams["plan_cache_mode"] = "force_generic_plan" |
| 26 | pool, err := pgxpool.NewWithConfig(ctx, cfg) |
| 27 | if err != nil { |
| 28 | return nil, err |
| 29 | } |
| 30 | if err := pool.Ping(ctx); err != nil { |
| 31 | pool.Close() |
| 32 | return nil, err |
| 33 | } |
| 34 | return pool, nil |
| 35 | } |
| 36 | |
| 37 | // Migrate applies the migrations that haven't run yet. |
| 38 | func Migrate(url string) error { |
| 39 | src, err := iofs.New(db.Migrations, "migrations") |
| 40 | if err != nil { |
| 41 | return err |
| 42 | } |
| 43 | target := strings.Replace(url, "postgres://", "pgx5://", 1) |
| 44 | m, err := migrate.NewWithSourceInstance("iofs", src, target) |
| 45 | if err != nil { |
| 46 | return err |
| 47 | } |
| 48 | defer m.Close() |
| 49 | if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { |
| 50 | return err |
| 51 | } |
| 52 | return nil |
| 53 | } |