-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_helpers.go
71 lines (58 loc) · 1.68 KB
/
test_helpers.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package bun
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/mysqldialect"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/dialect/sqlitedialect"
"github.com/uptrace/bun/driver/sqliteshim"
"os"
"strings"
)
func NewDB() (*bun.DB, error) {
var db *bun.DB
var err error
// A DSN must always begin with a scheme for tests
dsnRaw, ok := os.LookupEnv("DSN")
if !ok {
return nil, fmt.Errorf("you must provide a dsn")
}
switch {
case strings.HasPrefix(dsnRaw, "postgres://"):
fmt.Println("Connecting to Postgres")
// Postgres via pgx supports a full DSN including scheme
config, err := pgx.ParseConfig(dsnRaw)
if err != nil {
return nil, err
}
config.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
sqldb := stdlib.OpenDB(*config)
db = bun.NewDB(sqldb, pgdialect.New())
case strings.HasPrefix(dsnRaw, "mysql://"):
fmt.Println("Connecting to MySQL")
// The DSN for MySQL does not work with a scheme
dsnMysql, ok := strings.CutPrefix(dsnRaw, "mysql://")
if !ok {
return nil, fmt.Errorf("could not remove scheme from mysql dsn")
}
sqldb, err := sql.Open("mysql", dsnMysql)
if err != nil {
return nil, err
}
db = bun.NewDB(sqldb, mysqldialect.New())
case strings.HasPrefix(dsnRaw, "sqlserver://"):
return nil, fmt.Errorf("mssql is not supported")
case strings.HasPrefix(dsnRaw, "file::memory"):
fmt.Println("Connecting to SQLite")
sqldb, err := sql.Open(sqliteshim.ShimName, dsnRaw)
if err != nil {
return nil, err
}
db = bun.NewDB(sqldb, sqlitedialect.New())
}
return db, err
}