forked from pgpkg/pgpkg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp.go
More file actions
79 lines (65 loc) · 2.25 KB
/
temp.go
File metadata and controls
79 lines (65 loc) · 2.25 KB
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
package pgpkg
import (
"database/sql"
"fmt"
"math/rand"
"os"
)
// These functions create and destroy tempoarary databases.
// They are used in pgpkg repl and pgpkg test, but are also
// useful when writing unit tests in Go.
// MkTempDbName returns a SAFE, random, database name fragment.
// Take care to ensure that any changes to this function return names that are always safe to use
// in un-escaped SQL statements.
func MkTempDbName() string {
const letters = "abcdefghijklmnopqrstuvwxyz"
b := make([]byte, 8)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
// CreateTempDB creats a temporary database with a random name.
// We do this by connecting to the database using the environment,
// and running "create database". We return the database name.
func CreateTempDB(dsn string) (string, error) {
db, err := sql.Open("postgres", dsn)
if err != nil {
return "", fmt.Errorf("unable to open database: %w", err)
}
// important: ensure that the dbname only ever contains alphanumeric characters
dbname := "pgpkg." + MkTempDbName()
mkdbcmd := fmt.Sprintf("create database \"%s\"", dbname)
_, err = db.Exec(mkdbcmd)
if err != nil {
return "", fmt.Errorf("unable to create temp database \"%s\": %w", dbname, err)
}
if err := db.Close(); err != nil {
return "", fmt.Errorf("unable to close database: %w", err)
}
return dbname, nil
}
// DropTempDB drops the given database. WARNING: it will actually drop any database
// you ask it to, so take care only to use the database created by CreateTempDb
func DropTempDB(dsn string, dbname string) error {
db, err := sql.Open("postgres", dsn)
if err != nil {
return fmt.Errorf("unable to open database: %w", err)
}
// important: ensure that the dbname only ever contains alphanumeric characters
mkdbcmd := fmt.Sprintf("drop database \"%s\"", dbname)
_, err = db.Exec(mkdbcmd)
if err != nil {
return fmt.Errorf("unable to drop temp database \"%s\": %w", dbname, err)
}
if err = db.Close(); err != nil {
return fmt.Errorf("unable to close database: %w", err)
}
return nil
}
func DropTempDBOrExit(dsn string, replDb string) {
if err := DropTempDB(dsn, replDb); err != nil {
fmt.Fprintf(os.Stderr, "unable to drop REPL database %s: %v\n", replDb, err)
os.Exit(1)
}
}