-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreferences_pg.go
74 lines (60 loc) · 1.15 KB
/
references_pg.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
package gontentful
import (
"bytes"
"fmt"
"text/template"
"github.com/jmoiron/sqlx"
)
type PGReferences struct {
Schema *PGSQLSchema
}
func NewPGReferences(schema *PGSQLSchema) *PGReferences {
return &PGReferences{
Schema: schema,
}
}
func (s *PGReferences) Exec(databaseURL string) error {
str, err := s.Render()
if err != nil {
return err
}
db, err := sqlx.Open("postgres", databaseURL)
if err != nil {
return err
}
defer db.Close()
txn, err := db.Beginx()
if err != nil {
return err
}
defer txn.Rollback()
if s.Schema.SchemaName != "" {
// set schema in use
_, err = txn.Exec(fmt.Sprintf("SET search_path='%s'", s.Schema.SchemaName))
if err != nil {
return err
}
}
_, err = txn.Exec(str)
if err != nil {
return err
}
err = txn.Commit()
if err != nil {
return err
}
return nil
}
func (s *PGReferences) Render() (string, error) {
tmpl, err := template.New("referencesTemplate").Parse(pgReferencesTemplate)
if err != nil {
return "", err
}
var buff bytes.Buffer
err = tmpl.Execute(&buff, s)
if err != nil {
return "", err
}
// os.WriteFile("/tmp/refs", buff.Bytes(), 0644)
return buff.String(), nil
}