-
Notifications
You must be signed in to change notification settings - Fork 4
/
data.go
44 lines (35 loc) · 963 Bytes
/
data.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package postgres
import (
"context"
"embed"
"github.com/jackc/pgx/v5"
"github.com/pkg/errors"
)
var (
//go:embed sql/*
f embed.FS
SampleURIs = []string{
"postgres://username:password@localhost:5432/db",
"postgres://localhost/db?user=other&password=secret",
"postgres://localhost/db",
}
)
func getDB(ctx context.Context, uri string) (*pgx.Conn, error) {
if uri == "" {
return nil, errors.New("missing data uri")
}
conn, err := pgx.Connect(ctx, uri)
if err != nil {
return nil, errors.Wrapf(err, "failed to connect to database: %s", uri)
}
// the ddl script is idempotent so we can run it every time
b, err := f.ReadFile("sql/ddl.sql")
if err != nil {
return nil, errors.Wrap(err, "failed to read the schema creation file")
}
// will create schema if it does not exist
if _, err := conn.Exec(ctx, string(b)); err != nil {
return nil, errors.Wrapf(err, "failed to create database schema in: %s", uri)
}
return conn, nil
}