-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpublish_entries_pg.go
95 lines (79 loc) · 1.75 KB
/
publish_entries_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
95
package gontentful
import (
"bytes"
"fmt"
"text/template"
"github.com/jmoiron/sqlx"
)
const publishEntriesTemplate = `
UPDATE {{ .SchemaName }}.{{ .TableName }}
SET _status='published',
_version = _version + 1,
_published_at = to_timestamp('{{ .PublishedAt }}','YYYY-MM-DDThh24:mi:ssZ'),
_published_by = '{{ .PublishedBy }}'
WHERE _sys_id IN(
{{- range $idx, $id := $.SysIDs -}}
{{- if $idx -}},{{- end -}}'{{- $id -}}'
{{- end -}}
);`
type PGPublishEntries struct {
SchemaName string
TableName string
SysIDs []string
PublishedAt string
PublishedBy string
}
func NewPGPublishEntries(schemaName string, tableName string, sysIDs []string, publishedBy string, publishedAt string) *PGPublishEntries {
return &PGPublishEntries{
SchemaName: schemaName,
TableName: tableName,
SysIDs: sysIDs,
PublishedAt: publishedAt,
PublishedBy: publishedBy,
}
}
func (s *PGPublishEntries) 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 name
_, err = txn.Exec(fmt.Sprintf("SET search_path='%s'", s.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 *PGPublishEntries) Render() (string, error) {
tmpl, err := template.New("").Parse(publishEntriesTemplate)
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
}