-
Notifications
You must be signed in to change notification settings - Fork 19
/
database.go
57 lines (49 loc) · 1.47 KB
/
database.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
package helpers
import (
"database/sql"
"fmt"
"net/url"
"strings"
"testing"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/rotisserie/eris"
)
func GenerateDatabaseURI(t *testing.T, backend string) (string, error) {
switch backend {
case "sqlite":
return fmt.Sprintf("sqlite://%s/test.db", t.TempDir()), nil
case "sqlcipher":
return fmt.Sprintf("sqlite://%s/test.db?_key=passphrase", t.TempDir()), nil
case "postgres":
// temporary directory name contains some not allowed character to be in database name. filter it.
tmpDir := strings.ReplaceAll(t.TempDir(), "-", "_")
tmpDir = strings.ReplaceAll(tmpDir, "/", "_")
return getPostgresDatabase(t, GetPostgresUri(), strings.ToLower(tmpDir))
default:
return "", fmt.Errorf("unknown backend: %s", backend)
}
}
func getPostgresDatabase(t *testing.T, dsn string, name string) (string, error) {
uri, err := url.Parse(dsn)
if err != nil {
return "", eris.Wrapf(err, "failed to parse dsn %q", dsn)
}
db, err := sql.Open("pgx", dsn)
if err != nil {
return "", eris.Wrapf(err, "failed to open database %q", dsn)
}
_, err = db.Exec("CREATE DATABASE " + name)
if err != nil {
return "", eris.Wrapf(err, "failed to create database %q on %q", name, dsn)
}
t.Cleanup(func() {
// nolint:errcheck
defer db.Close()
_, err := db.Exec("DROP DATABASE " + name + " WITH (FORCE)")
if err != nil {
t.Errorf("failed to drop database %q on %q: %v", name, dsn, err)
}
})
uri.Path = name
return uri.String(), nil
}