-
Notifications
You must be signed in to change notification settings - Fork 2
/
postgresql.go
81 lines (64 loc) · 1.83 KB
/
postgresql.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
72
73
74
75
76
77
78
79
80
81
package services
import (
"database/sql"
"fmt"
"net"
"net/url"
"os"
)
type PostgresqlDatabaseBase interface {
// Host returns the host for connecting to this database.
Host() string
// Port returns the port for connecting to this database.
Port() string
// Username returns the username for connecting to this database.
Username() string
// Password returns the password for connecting to the database.
Password() string
// Database returns the name of the database on the PostgreSQL server.
Database() string
// Cleanup removes the PostgreSQL database.
Cleanup()
}
// PostgresqlDatabase wraps the PostgresqlDatabaseBase interface and adds some helper functions.
type PostgresqlDatabase struct {
PostgresqlDatabaseBase
}
var _ RelationalDatabase = PostgresqlDatabase{}
func (p PostgresqlDatabase) IcingaDbType() string {
return "pgsql"
}
func (p PostgresqlDatabase) Driver() string {
return "postgres"
}
func (p PostgresqlDatabase) DSN() string {
u := url.URL{
Scheme: "postgres",
User: url.UserPassword(p.Username(), p.Password()),
Host: net.JoinHostPort(p.Host(), p.Port()),
Path: "/" + url.PathEscape(p.Database()),
RawQuery: "sslmode=disable&binary_parameters=yes",
}
return u.String()
}
func (p PostgresqlDatabase) Open() (*sql.DB, error) {
return sql.Open(p.Driver(), p.DSN())
}
func (p PostgresqlDatabase) ImportIcingaDbSchema() {
key := "ICINGA_TESTING_ICINGADB_SCHEMA_PGSQL"
schemaFile, ok := os.LookupEnv(key)
if !ok {
panic(fmt.Errorf("environment variable %s must be set", key))
}
schema, err := os.ReadFile(schemaFile)
if err != nil {
panic(fmt.Errorf("failed to read icingadb schema file %q: %w", schemaFile, err))
}
db, err := PostgresqlDatabase{PostgresqlDatabaseBase: p}.Open()
if err != nil {
panic(err)
}
if _, err := db.Exec(string(schema)); err != nil {
panic(err)
}
}