This repository has been archived by the owner on Oct 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathtravis.setup_redshift.go
114 lines (101 loc) · 2.26 KB
/
travis.setup_redshift.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// +build travis
package main
import (
"database/sql"
"fmt"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
_ "github.com/lib/pq"
)
func main() {
var cmd string
if len(os.Args) == 2 {
cmd = os.Args[1]
}
switch cmd {
case "setup":
setup()
case "destroy":
destroy()
default:
fmt.Fprintf(os.Stderr, "usage: %s {setup|destroy}\n", filepath.Base(os.Args[0]))
os.Exit(1)
}
}
func setup() {
dsn := os.Getenv("REDSHIFT_DATABASE_DSN")
newdb := "goose-" + strconv.FormatInt(time.Now().UnixNano(), 36)
var newDSN string
if strings.HasPrefix(dsn, "postgres://") {
u, err := url.Parse(dsn)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not parse $REDSHIFT_DATABASE_DSN\n")
os.Exit(1)
}
u.Path = newdb
newDSN = u.String()
} else {
foundDBName := false
for _, f := range strings.Fields(dsn) {
kv := strings.SplitN(f, "=", 2)
if kv[0] == "dbname" {
f = "dbname=" + newdb
foundDBName = true
}
newDSN = newDSN + f + " "
}
if !foundDBName {
newDSN = newDSN + "dbname=" + newdb
}
}
db, err := sql.Open("postgres", dsn)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not connect to Redshift: %s\n", err)
os.Exit(1)
}
_, err = db.Exec(fmt.Sprintf("create database %q", newdb))
if err != nil {
fmt.Fprintf(os.Stderr, "Could not create database: %s\n", err)
os.Exit(1)
}
fmt.Printf("REDSHIFT_DATABASE_DSN=%s\n", newDSN)
os.Exit(0)
}
func destroy() {
dsn := os.Getenv("REDSHIFT_DATABASE_DSN")
var dbname string
if strings.HasPrefix(dsn, "postgres://") {
u, err := url.Parse(dsn)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not parse $REDSHIFT_DATABASE_DSN\n")
os.Exit(1)
}
dbname = u.Path
} else {
for _, f := range strings.Fields(dsn) {
kv := strings.SplitN(f, "=", 2)
if len(kv) != 2 || kv[0] == "dbname" {
dbname = kv[1]
break
}
}
}
if dbname == "" {
fmt.Fprintf(os.Stderr, "Could not find db name in $REDSHIFT_DATABASE_DSN\n")
os.Exit(1)
}
db, err := sql.Open("postgres", strings.Replace(dsn, dbname, "dev", 1))
if err != nil {
fmt.Fprintf(os.Stderr, "Could not connect to Redshift: %s\n", err)
os.Exit(1)
}
_, err = db.Exec(fmt.Sprintf("drop database %q", dbname))
if err != nil {
fmt.Fprintf(os.Stderr, "Could not drop database: %s\n", err)
os.Exit(1)
}
}