-
Notifications
You must be signed in to change notification settings - Fork 0
/
join.go
62 lines (51 loc) · 1.39 KB
/
join.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
package squrl
import "fmt"
type joinType string
const (
LeftJoin joinType = "LEFT"
InnerJoin joinType = "INNER"
RightJoin joinType = "RIGHT"
OuterJoin joinType = "OUTER"
)
type JoinTables struct {
Left string
Right string
}
type JoinTerm struct {
Fields []string
On JoinTables
Pk interface{}
Tables JoinTables
JoinType joinType
}
func (s *SQURL) Join(join JoinTerm) *SQURL {
if s.joinTerms == nil {
joinTerms := make(map[string]bool)
s.joinTerms = &joinTerms
}
if s.joinTableKeys == nil {
joinTableKeys := make(map[string]bool)
s.joinTableKeys = &joinTableKeys
}
for _, field := range join.Fields {
(*s.fields)[fmt.Sprintf(`"%v".%v`, join.Tables.Right, field)] = true
}
schema := ""
if s.schema != "" {
schema = fmt.Sprintf("%v.", s.schema)
}
joinTerm := fmt.Sprintf(`%v JOIN %v"%v"`, join.JoinType, schema, join.Tables.Right)
on := fmt.Sprintf(`%vON %v"%v".%v = %v"%v".%v%v`, s.delimiter, schema, join.Tables.Left, join.On.Left, schema, join.Tables.Right, join.On.Right, s.delimiter)
(*s.joinTerms)[joinTerm+on] = true
switch v := join.Pk.(type) {
case string:
(*s.joinTableKeys)[fmt.Sprintf(`"%v".%v`, join.Tables.Right, v)] = true
case []string:
for _, col := range v {
(*s.joinTableKeys)[fmt.Sprintf(`"%v".%v`, join.Tables.Right, col)] = true
}
default:
(*s.joinTableKeys)[fmt.Sprintf(`"%v".id`, join.Tables.Right)] = true
}
return s
}