-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdelete_contenttype_pg.go
94 lines (78 loc) · 1.83 KB
/
delete_contenttype_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
89
90
91
92
93
94
package gontentful
import (
"bytes"
"fmt"
"text/template"
"github.com/jmoiron/sqlx"
)
const delContentTypeTemplate = `
DROP TABLE IF EXISTS {{ $.SchemaName }}.{{ $.TableName }} CASCADE;
--
DROP FUNCTION IF EXISTS {{ $.SchemaName }}._get_{{ $.TableName }}_items CASCADE;
--
DROP FUNCTION IF EXISTS {{ $.SchemaName }}.{{ $.TableName }}_items CASCADE;
--
DROP FUNCTION IF EXISTS {{ $.SchemaName }}.{{ $.TableName }}_query CASCADE;
--
DELETE FROM {{ $.SchemaName }}.{{ $.SchemaTableName }} WHERE table_name = '{{ $.TableName }}';
`
type PGDeleteContentType struct {
SchemaName string
TableName string
SysID string
SchemaTableName string
}
func NewPGDeleteContentType(schemaName string, sys *Sys) *PGDeleteContentType {
return &PGDeleteContentType{
SchemaName: schemaName,
TableName: toSnakeCase(sys.ID),
SysID: sys.ID,
SchemaTableName: SCHEMA_TABLE_NAME,
}
}
func (s *PGDeleteContentType) Exec(databaseURL string) error {
str, err := s.Render()
if err != nil {
return err
}
db, err := sqlx.Connect("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 *PGDeleteContentType) Render() (string, error) {
tmpl, err := template.New("").Parse(delContentTypeTemplate)
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
}