-
Notifications
You must be signed in to change notification settings - Fork 0
/
cte.go
95 lines (74 loc) · 2.24 KB
/
cte.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
package sqext
import (
"bytes"
"database/sql"
"fmt"
sq "github.com/Masterminds/squirrel"
"github.com/lann/builder"
)
type cteData struct {
PlaceholderFormat sq.PlaceholderFormat
RunWith sq.BaseRunner
AuxStatements []sq.Sqlizer
}
func (c *cteData) Exec() (sql.Result, error) {
if c.RunWith == nil {
return nil, sq.RunnerNotSet
}
return sq.ExecWith(c.RunWith, c)
}
func (c *cteData) ToSql() (string, []interface{}, error) {
if len(c.AuxStatements) == 0 {
return "", []interface{}{}, fmt.Errorf("CTE must contain at least one auxillary statement")
}
var sql bytes.Buffer
var args []interface{}
sql.WriteString("WITH ")
for i, stmt := range c.AuxStatements {
var err error
args, err = appendToSql(stmt, &sql, args)
if err != nil {
return "", []interface{}{}, err
}
if i != len(c.AuxStatements)-1 {
sql.WriteString(", ")
}
}
sqlStr, err := c.PlaceholderFormat.ReplacePlaceholders(sql.String())
if err != nil {
return "", []interface{}{}, err
}
return sqlStr, args, nil
}
// Builder
// CTEBuilder builds SQL WITH statement, also known as Common Table Expression (CTE).
type CTEBuilder builder.Builder
func init() {
builder.Register(CTEBuilder{}, cteData{})
}
// Format methods
// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the
// query.
func (b CTEBuilder) PlaceholderFormat(f sq.PlaceholderFormat) CTEBuilder {
return builder.Set(b, "PlaceholderFormat", f).(CTEBuilder)
}
// Runner methods
// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec.
// For most cases runner will be a database connection.
func (b CTEBuilder) RunWith(runner sq.BaseRunner) CTEBuilder {
return setRunWith(b, runner).(CTEBuilder)
}
// Exec builds and Execs the query with the Runner set by RunWith.
func (b CTEBuilder) Exec() (sql.Result, error) {
data := builder.GetStruct(b).(cteData)
return data.Exec()
}
// ToSql builds the query into a SQL string and bound args.
func (b CTEBuilder) ToSql() (string, []interface{}, error) {
data := builder.GetStruct(b).(cteData)
return data.ToSql()
}
// AuxStatements assigns auxillary statements to CTE.
func (b CTEBuilder) AuxStatements(auxStmts ...AuxBuilder) CTEBuilder {
return builder.Extend(b, "AuxStatements", auxStmts).(CTEBuilder)
}