forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgresql.go
248 lines (211 loc) · 5.51 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package pop
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"github.com/jmoiron/sqlx"
// Load PostgreSQL Go driver
_ "github.com/lib/pq"
"github.com/gobuffalo/pop/columns"
"github.com/gobuffalo/pop/fizz"
"github.com/gobuffalo/pop/fizz/translators"
"github.com/markbates/going/defaults"
"github.com/pkg/errors"
)
var _ dialect = &postgresql{}
type postgresql struct {
translateCache map[string]string
mu sync.Mutex
ConnectionDetails *ConnectionDetails
}
func (p *postgresql) Details() *ConnectionDetails {
return p.ConnectionDetails
}
func (p *postgresql) Create(s store, model *Model, cols columns.Columns) error {
keyType := model.PrimaryKeyType()
switch keyType {
case "int", "int64":
cols.Remove("id")
id := struct {
ID int `db:"id"`
}{}
w := cols.Writeable()
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s) returning id", model.TableName(), w.String(), w.SymbolizedString())
Log(query)
stmt, err := s.PrepareNamed(query)
if err != nil {
return errors.WithStack(err)
}
err = stmt.Get(&id, model.Value)
if err != nil {
return errors.WithStack(err)
}
model.setID(id.ID)
return nil
case "UUID":
return genericCreate(s, model, cols)
}
return errors.Errorf("can not use %s as a primary key type!", keyType)
}
func (p *postgresql) Update(s store, model *Model, cols columns.Columns) error {
return genericUpdate(s, model, cols)
}
func (p *postgresql) Destroy(s store, model *Model) error {
return genericDestroy(s, model)
}
func (p *postgresql) SelectOne(s store, model *Model, query Query) error {
return genericSelectOne(s, model, query)
}
func (p *postgresql) SelectMany(s store, models *Model, query Query) error {
return genericSelectMany(s, models, query)
}
func (p *postgresql) CreateDB() error {
// createdb -h db -p 5432 -U postgres enterprise_development
deets := p.ConnectionDetails
db, err := sqlx.Open(deets.Dialect, p.urlWithoutDb())
if err != nil {
return errors.Wrapf(err, "error creating PostgreSQL database %s", deets.Database)
}
defer db.Close()
query := fmt.Sprintf("CREATE DATABASE \"%s\"", deets.Database)
Log(query)
_, err = db.Exec(query)
if err != nil {
return errors.Wrapf(err, "error creating PostgreSQL database %s", deets.Database)
}
fmt.Printf("created database %s\n", deets.Database)
return nil
}
func (p *postgresql) DropDB() error {
deets := p.ConnectionDetails
db, err := sqlx.Open(deets.Dialect, p.urlWithoutDb())
if err != nil {
return errors.Wrapf(err, "error dropping PostgreSQL database %s", deets.Database)
}
defer db.Close()
query := fmt.Sprintf("DROP DATABASE \"%s\"", deets.Database)
Log(query)
_, err = db.Exec(query)
if err != nil {
return errors.Wrapf(err, "error dropping PostgreSQL database %s", deets.Database)
}
fmt.Printf("dropped database %s\n", deets.Database)
return nil
}
func (p *postgresql) URL() string {
c := p.ConnectionDetails
if c.URL != "" {
return c.URL
}
ssl := defaults.String(c.Options["sslmode"], "disable")
s := "postgres://%s:%s@%s:%s/%s?sslmode=%s"
return fmt.Sprintf(s, c.User, c.Password, c.Host, c.Port, c.Database, ssl)
}
func (p *postgresql) urlWithoutDb() string {
c := p.ConnectionDetails
ssl := defaults.String(c.Options["sslmode"], "disable")
s := "postgres://%s:%s@%s:%s/?sslmode=%s"
return fmt.Sprintf(s, c.User, c.Password, c.Host, c.Port, ssl)
}
func (p *postgresql) MigrationURL() string {
return p.URL()
}
func (p *postgresql) TranslateSQL(sql string) string {
defer p.mu.Unlock()
p.mu.Lock()
if csql, ok := p.translateCache[sql]; ok {
return csql
}
curr := 1
out := make([]byte, 0, len(sql))
for i := 0; i < len(sql); i++ {
if sql[i] == '?' {
str := "$" + strconv.Itoa(curr)
for _, char := range str {
out = append(out, byte(char))
}
curr++
} else {
out = append(out, sql[i])
}
}
csql := string(out)
p.translateCache[sql] = csql
return csql
}
func (p *postgresql) FizzTranslator() fizz.Translator {
return translators.NewPostgres()
}
func (p *postgresql) Lock(fn func() error) error {
return fn()
}
func (p *postgresql) DumpSchema(w io.Writer) error {
cmd := exec.Command("pg_dump", "-s", fmt.Sprintf("--dbname=%s", p.URL()))
Log(strings.Join(cmd.Args, " "))
cmd.Stdout = w
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return err
}
fmt.Printf("dumped schema for %s\n", p.Details().Database)
return nil
}
func (p *postgresql) LoadSchema(r io.Reader) error {
cmd := exec.Command("psql", p.URL())
in, err := cmd.StdinPipe()
if err != nil {
return err
}
go func() {
defer in.Close()
io.Copy(in, r)
}()
Log(strings.Join(cmd.Args, " "))
bb := &bytes.Buffer{}
cmd.Stdout = bb
cmd.Stderr = bb
err = cmd.Start()
if err != nil {
return errors.WithMessage(err, bb.String())
}
err = cmd.Wait()
if err != nil {
return errors.WithMessage(err, bb.String())
}
fmt.Printf("loaded schema for %s\n", p.Details().Database)
return nil
}
func (p *postgresql) TruncateAll(tx *Connection) error {
return tx.RawQuery(pgTruncate).Exec()
}
func newPostgreSQL(deets *ConnectionDetails) dialect {
cd := &postgresql{
ConnectionDetails: deets,
translateCache: map[string]string{},
mu: sync.Mutex{},
}
return cd
}
const pgTruncate = `DO
$func$
DECLARE
_tbl text;
_sch text;
BEGIN
FOR _sch, _tbl IN
SELECT schemaname, tablename
FROM pg_tables
WHERE schemaname = 'public'
LOOP
--RAISE ERROR '%',
EXECUTE -- dangerous, test before you execute!
format('TRUNCATE TABLE %I.%I CASCADE', _sch, _tbl);
END LOOP;
END
$func$;`