-
Notifications
You must be signed in to change notification settings - Fork 1
/
delete_pg.go
88 lines (72 loc) · 1.49 KB
/
delete_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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package gontentful
import (
"bytes"
"fmt"
"text/template"
"github.com/jmoiron/sqlx"
)
const deleteTemplate = "DELETE FROM {{ .SchemaName }}.{{ .TableName }} WHERE _sys_id = '{{ .SysID }}';"
type PGDelete struct {
SchemaName string
TableName string
SysID string
}
func NewPGDelete(schemaName string, sys *Sys) *PGDelete {
tableName := ""
if sys.Type == DELETED_ENTRY {
tableName = toSnakeCase(sys.ContentType.Sys.ID)
} else if sys.Type == DELETED_ASSET {
tableName = ASSET_TABLE_NAME
}
return &PGDelete{
SchemaName: schemaName,
TableName: tableName,
SysID: sys.ID,
}
}
func (s *PGDelete) 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.SchemaName != "" {
// set schema in use
_, err = txn.Exec(fmt.Sprintf("SET search_path='%s'", s.SchemaName))
if err != nil {
return err
}
}
// os.WriteFile("/tmp/func", buff.Bytes(), 0644)
_, err = txn.Exec(str)
if err != nil {
return err
}
err = txn.Commit()
if err != nil {
return err
}
return nil
}
func (s *PGDelete) Render() (string, error) {
tmpl, err := template.New("").Parse(deleteTemplate)
if err != nil {
return "", err
}
var buff bytes.Buffer
err = tmpl.Execute(&buff, s)
if err != nil {
return "", err
}
// fmt.Println(buff.String())
return buff.String(), nil
}