forked from oelmekki/pgrebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trigger.go
103 lines (84 loc) · 2.33 KB
/
trigger.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
96
97
98
99
100
101
102
103
package main
import (
"io/ioutil"
"fmt"
"regexp"
)
/*
* Load or reload all triggers found in FS.
*/
func LoadTriggers() ( err error ) {
successfulCount := len( Cfg.TriggerFiles )
errors := make( []string, 0 )
bypass := make(map[string]bool)
files, err := ResolveDependencies( Cfg.TriggerFiles, Cfg.SqlDirPath + "triggers" )
if err != nil { return err }
triggers := make( []*Trigger, 0 )
for i := len( files ) - 1 ; i >= 0 ; i-- {
file := files[ i ]
trigger := Trigger{}
trigger.Path = file
triggers = append( triggers, &trigger )
err = DownPass( &trigger, trigger.Path )
if err != nil {
successfulCount--
errors = append( errors, fmt.Sprintf( "%v\n", err ) )
bypass[ trigger.Path ] = true
}
}
for i := len( triggers ) - 1 ; i >= 0 ; i-- {
trigger := triggers[ i ]
if _, ignore := bypass[ trigger.Path ] ; ! ignore {
err = UpPass( trigger, trigger.Path )
if err != nil {
successfulCount--
errors = append( errors, fmt.Sprintf( "%v\n", err ) )
}
}
}
Report( "triggers", successfulCount, len( Cfg.TriggerFiles ), errors )
return
}
type Trigger struct {
CodeUnit
Table string
Function Function
}
/*
* Load trigger definition from file
*/
func ( trigger *Trigger ) Load() ( err error ) {
definition, err := ioutil.ReadFile( trigger.Path )
if err != nil { return err }
trigger.Definition = string( definition )
return
}
/*
* Parse trigger for name and signature
*/
func ( trigger *Trigger ) Parse() ( err error ) {
triggerFinder := regexp.MustCompile( `(?is)CREATE(?:\s+CONSTRAINT)?\s+TRIGGER\s+(\S+).*?ON\s+(\S+)` )
subMatches := triggerFinder.FindStringSubmatch( trigger.Definition )
if len( subMatches ) < 3 {
return fmt.Errorf( "Can't find a trigger in %s", trigger.Path )
}
trigger.Function = Function{ CodeUnit: CodeUnit{ Definition: trigger.Definition, Path: trigger.Path } }
trigger.Function.Parse()
trigger.Name = subMatches[1]
trigger.Table = subMatches[2]
return
}
/*
* Drop existing trigger from pg
*/
func ( trigger *Trigger ) Drop() ( err error ) {
err = trigger.CodeUnit.Drop( `DROP TRIGGER IF EXISTS ` + trigger.Name + ` ON ` + trigger.Table )
if err != nil { return err }
return trigger.Function.Drop()
}
/*
* Create the trigger in pg
*/
func ( trigger *Trigger ) Create() ( err error ) {
return trigger.CodeUnit.Create( trigger.Definition )
}