-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
61 lines (48 loc) · 1.2 KB
/
db.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
package pgengine
import (
"database/sql"
"fmt"
_ "github.com/jackc/pgx/v4/stdlib"
)
type DB struct {
connOpts ConnectionOptions
dropped bool
}
func (d *DB) GetName() string {
return d.connOpts[ConnectionOptionDatabase]
}
func (d *DB) GetConnOpts() ConnectionOptions {
return d.connOpts
}
func (d *DB) GetDSN() string {
return d.GetConnOpts().ToDSN()
}
// DropDB drops the database
func (d *DB) DropDB() error {
if d.dropped {
return nil
}
// Use the pgDsn as we are dropping the test database
db, err := sql.Open("pgx", d.GetConnOpts().With(ConnectionOptionDatabase, "postgres").ToDSN())
if err != nil {
return err
}
defer db.Close()
// Disallow further connections to the test database, except for superusers
_, err = db.Exec(fmt.Sprintf("ALTER DATABASE \"%s\" CONNECTION LIMIT 0", d.GetName()))
if err != nil {
return err
}
// Drop existing connections, so that we can drop the database
_, err = db.Exec("SELECT PG_TERMINATE_BACKEND(pid) FROM pg_stat_activity WHERE datname = $1", d.GetName())
if err != nil {
return err
}
// Finally, drop the table
_, err = db.Exec(fmt.Sprintf("DROP DATABASE \"%s\"", d.GetName()))
if err != nil {
return err
}
d.dropped = true
return nil
}