-
-
Notifications
You must be signed in to change notification settings - Fork 177
/
build.go
118 lines (94 loc) · 2.24 KB
/
build.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package core
import (
"bytes"
"encoding/json"
"fmt"
"sync"
"github.com/dosco/graphjin/core/internal/psql"
"github.com/dosco/graphjin/core/internal/qcode"
)
type queryComp struct {
sync.Once
qr queryReq
st stmt
}
type stmt struct {
role *Role
qc *qcode.QCode
md psql.Metadata
sql string
}
func (gj *GraphJin) compileQuery(qr queryReq, role string) (*queryComp, error) {
var qc *queryComp
var err error
var ok bool
var vm map[string]json.RawMessage
if len(qr.vars) != 0 {
if err := json.Unmarshal(qr.vars, &vm); err != nil {
return nil, fmt.Errorf("variables: %w", err)
}
}
if gj.allowList == nil || !gj.prod {
st, err := gj.compileQueryRole(qr, vm, role)
if err != nil {
return nil, err
}
return &queryComp{qr: qr, st: st}, nil
}
// In production mode enforce the allow list and
// compile and cache the result else compile each time
if qc, ok = gj.queries[(qr.name + role)]; !ok {
return nil, errNotFound
}
ov := qc.qr.order[0]
// If order variable is set
if ov != "" {
if qc, err = gj.orderQuery(ov, qc, vm, role); err != nil {
return nil, err
}
}
if qc.st.sql == "" {
qc.Do(func() {
qc.st, err = gj.compileQueryRole(qc.qr, vm, role)
})
}
return qc, err
}
func (gj *GraphJin) orderQuery(
ov string,
qc *queryComp,
vm map[string]json.RawMessage, role string) (*queryComp, error) {
var oval string
v, ok := vm[ov]
if !ok || v[0] != '"' || len(v) == 2 {
return nil, fmt.Errorf("required variable not set: %s", ov)
}
oval = string(v[1:(len(v) - 1)])
if qc, ok := gj.queries[(qc.qr.name + role + oval)]; ok {
return qc, nil
} else {
return nil, fmt.Errorf("invalid value for variable (%s): %s", ov, oval)
}
}
func (gj *GraphJin) compileQueryRole(
qr queryReq,
vm map[string]json.RawMessage, role string) (stmt, error) {
var st stmt
var err error
var ok bool
if st.role, ok = gj.roles[role]; !ok {
return st, fmt.Errorf(`roles '%s' not defined in c.gj.config`, role)
}
if qr.order[0] != "" {
vm[qr.order[0]] = json.RawMessage(qr.order[1])
}
if st.qc, err = gj.qc.Compile(qr.query, vm, st.role.Name); err != nil {
return st, err
}
var w bytes.Buffer
if st.md, err = gj.pc.Compile(&w, st.qc); err != nil {
return st, err
}
st.sql = w.String()
return st, nil
}