-
Notifications
You must be signed in to change notification settings - Fork 1
/
historyTable.go
76 lines (68 loc) · 2.07 KB
/
historyTable.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
package shifter
import (
"fmt"
"github.com/go-pg/pg"
"github.com/mayur-tolexo/flaw"
"github.com/mayur-tolexo/pg-shifter/util"
)
//Create history table
func (s *Shifter) createHistory(tx *pg.Tx, tableName string) (err error) {
if s.isSkip(tableName) == false {
historyTable := util.GetHistoryTableName(tableName)
if tableExists := tableExists(tx, historyTable); tableExists == false {
if err = s.execHistoryTable(tx, tableName, historyTable); err == nil {
if err = s.dropHistoryConstraint(tx, historyTable); err == nil {
err = s.createTrigger(tx, tableName)
}
}
}
}
return
}
//dropHistory will drop history table
func (s *Shifter) dropHistory(tx *pg.Tx, tableName string, cascade bool) (err error) {
historyTable := util.GetHistoryTableName(tableName)
if tableExists := tableExists(tx, historyTable); tableExists == true {
err = execTableDrop(tx, historyTable, cascade)
}
return
}
//dropHistoryConstraint will drop history table constraints
func (s *Shifter) dropHistoryConstraint(tx *pg.Tx, historyTable string) (err error) {
sql := `
ALTER TABLE %v DROP COLUMN IF EXISTS updated_at;
ALTER TABLE %v ADD COLUMN IF NOT EXISTS created_at timetz DEFAULT now();`
sql = fmt.Sprintf(sql, historyTable, historyTable)
if _, err = tx.Exec(sql); err != nil {
msg := `History Table Error: ` + historyTable + `
SQL:` + sql
err = flaw.ExecError(err, msg)
fmt.Println(msg, err)
}
return
}
//execHistoryTable will execute history table creation
func (s *Shifter) execHistoryTable(tx *pg.Tx, tableName, historyTable string) (err error) {
sql := `
CREATE TABLE %v (
id BIGSERIAL PRIMARY key,
action VARCHAR(20),
LIKE %v
);
`
sql = fmt.Sprintf(sql, historyTable, tableName)
if _, err = tx.Exec(fmt.Sprintf(sql)); err != nil {
msg := fmt.Sprintf("Table: %v", tableName)
err = flaw.ExecError(err, msg)
fmt.Println("History Error:", msg, err)
}
return
}
//IsSkip will check table contain skip tags
func (s *Shifter) isSkip(tableName string) (flag bool) {
tableModel, isValid := s.table[tableName]
if isValid {
flag = util.SkipTag(tableModel)
}
return
}