/
stmt_with.go
75 lines (57 loc) · 1.42 KB
/
stmt_with.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
package builder
import (
"context"
"strings"
)
type BuildSubQuery func(table *Table) SqlExpr
func WithRecursive(t *Table, build BuildSubQuery) *WithStmt {
return With(t, build, "RECURSIVE")
}
func With(t *Table, build BuildSubQuery, modifiers ...string) *WithStmt {
return (&WithStmt{modifiers: modifiers}).With(t, build)
}
type WithStmt struct {
modifiers []string
tables []*Table
asList []BuildSubQuery
statement func(tables ...*Table) SqlExpr
}
func (w *WithStmt) IsNil() bool {
return w == nil || len(w.tables) == 0 || len(w.asList) == 0 || w.statement == nil
}
func (w WithStmt) With(t *Table, build BuildSubQuery) *WithStmt {
w.tables = append(w.tables, t)
w.asList = append(w.asList, build)
return &w
}
func (w WithStmt) Exec(statement func(tables ...*Table) SqlExpr) *WithStmt {
w.statement = statement
return &w
}
func (w *WithStmt) Ex(ctx context.Context) *Ex {
e := Expr("WITH ")
if len(w.modifiers) > 0 {
e.WriteQuery(strings.Join(w.modifiers, " "))
e.WriteQuery(" ")
}
for i := range w.tables {
if i > 0 {
e.WriteQuery(", ")
}
table := w.tables[i]
e.WriteExpr(table)
e.WriteGroup(func(e *Ex) {
e.WriteExpr(&table.Columns)
})
e.WriteQuery(" AS ")
build := w.asList[i]
e.WriteGroup(func(e *Ex) {
e.WriteQueryByte('\n')
e.WriteExpr(build(table))
e.WriteQueryByte('\n')
})
}
e.WriteQueryByte('\n')
e.WriteExpr(w.statement(w.tables...))
return e.Ex(ctx)
}