forked from slicebit/qb
-
Notifications
You must be signed in to change notification settings - Fork 2
/
compiler.go
373 lines (316 loc) · 10.6 KB
/
compiler.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package qb
import (
"fmt"
"strings"
)
// NewCompilerContext initialize a new compiler context
func NewCompilerContext(dialect Dialect) *CompilerContext {
return &CompilerContext{
Dialect: dialect,
Compiler: dialect.GetCompiler(),
Vars: make(map[string]interface{}),
Binds: []interface{}{},
}
}
// CompilerContext is a data structure passed to all the Compiler visit
// functions. It contains the bindings, links to the Dialect and Compiler
// being used, and some contextual informations that can be used by the
// compiler functions to communicate during the compilation.
type CompilerContext struct {
Binds []interface{}
DefaultTableName string
InSubQuery bool
Vars map[string]interface{}
Dialect Dialect
Compiler Compiler
}
// Compiler is a visitor that produce SQL from various types of Clause
type Compiler interface {
VisitAggregate(*CompilerContext, AggregateClause) string
VisitAlias(*CompilerContext, AliasClause) string
VisitBinary(*CompilerContext, BinaryExpressionClause) string
VisitBind(*CompilerContext, BindClause) string
VisitColumn(*CompilerContext, ColumnElem) string
VisitCombiner(*CompilerContext, CombinerClause) string
VisitDelete(*CompilerContext, DeleteStmt) string
VisitExists(*CompilerContext, ExistsClause) string
VisitForUpdate(*CompilerContext, ForUpdateClause) string
VisitHaving(*CompilerContext, HavingClause) string
VisitIn(*CompilerContext, InClause) string
VisitInsert(*CompilerContext, InsertStmt) string
VisitJoin(*CompilerContext, JoinClause) string
VisitLabel(*CompilerContext, string) string
VisitList(*CompilerContext, ListClause) string
VisitOrderBy(*CompilerContext, OrderByClause) string
VisitSelect(*CompilerContext, SelectStmt) string
VisitTable(*CompilerContext, TableElem) string
VisitText(*CompilerContext, TextClause) string
VisitUpdate(*CompilerContext, UpdateStmt) string
VisitUpsert(*CompilerContext, UpsertStmt) string
VisitWhere(*CompilerContext, WhereClause) string
}
// NewSQLCompiler returns a new SQLCompiler
func NewSQLCompiler(dialect Dialect) SQLCompiler {
return SQLCompiler{Dialect: dialect}
}
// SQLCompiler aims to provide a SQL ANSI-92 implementation of Compiler
type SQLCompiler struct {
Dialect Dialect
}
// VisitAggregate compiles aggregate functions (COUNT, SUM...)
func (c SQLCompiler) VisitAggregate(context *CompilerContext, aggregate AggregateClause) string {
return fmt.Sprintf("%s(%s)", aggregate.fn, aggregate.clause.Accept(context))
}
// VisitAlias compiles a '<selectable> AS <aliasname>' SQL clause
func (SQLCompiler) VisitAlias(context *CompilerContext, alias AliasClause) string {
return fmt.Sprintf(
"%s AS %s",
alias.Selectable.Accept(context),
context.Dialect.Escape(alias.Name),
)
}
// VisitBinary compiles LEFT <op> RIGHT expressions
func (c SQLCompiler) VisitBinary(context *CompilerContext, binary BinaryExpressionClause) string {
return fmt.Sprintf(
"%s %s %s",
binary.Left.Accept(context),
binary.Op,
binary.Right.Accept(context),
)
}
// VisitBind renders a bounded value
func (SQLCompiler) VisitBind(context *CompilerContext, bind BindClause) string {
context.Binds = append(context.Binds, bind.Value)
return "?"
}
// VisitColumn returns a column name, optionnaly escaped depending on the dialect
// configuration
func (c SQLCompiler) VisitColumn(context *CompilerContext, column ColumnElem) string {
sql := ""
if context.InSubQuery || context.DefaultTableName != column.Table {
sql += c.Dialect.Escape(column.Table) + "."
}
sql += c.Dialect.Escape(column.Name)
return sql
}
// VisitCombiner compiles AND and OR sql clauses
func (c SQLCompiler) VisitCombiner(context *CompilerContext, combiner CombinerClause) string {
sqls := []string{}
for _, c := range combiner.clauses {
sql := c.Accept(context)
sqls = append(sqls, sql)
}
return fmt.Sprintf("(%s)", strings.Join(sqls, fmt.Sprintf(" %s ", combiner.operator)))
}
// VisitDelete compiles a DELETE statement
func (c SQLCompiler) VisitDelete(context *CompilerContext, delete DeleteStmt) string {
sql := "DELETE FROM " + delete.table.Accept(context)
if delete.where != nil {
sql += "\n" + delete.where.Accept(context)
}
returning := []string{}
for _, c := range delete.returning {
returning = append(returning, context.Dialect.Escape(c.Name))
}
if len(returning) > 0 {
sql += "\nRETURNING " + strings.Join(returning, ", ")
}
return sql
}
// VisitExists compile a EXISTS clause
func (SQLCompiler) VisitExists(context *CompilerContext, exists ExistsClause) string {
var sql string
if exists.Not {
sql = "NOT "
}
sql += "EXISTS(%s)"
context.InSubQuery = true
defer func() { context.InSubQuery = false }()
return fmt.Sprintf(sql, exists.Select.Accept(context))
}
// VisitForUpdate compiles a 'FOR UPDATE' clause
func (c SQLCompiler) VisitForUpdate(context *CompilerContext, forUpdate ForUpdateClause) string {
var sql = "FOR UPDATE"
if len(forUpdate.Tables) != 0 {
var tablenames []string
for _, table := range forUpdate.Tables {
tablenames = append(tablenames, table.Name)
}
sql += " OF " + strings.Join(tablenames, ", ")
}
return sql
}
// VisitHaving compiles a HAVING clause
func (c SQLCompiler) VisitHaving(context *CompilerContext, having HavingClause) string {
aggSQL := having.aggregate.Accept(context)
return fmt.Sprintf("HAVING %s %s %s", aggSQL, having.op, Bind(having.value).Accept(context))
}
// VisitIn compiles a <left> (NOT) IN (<right>)
func (c SQLCompiler) VisitIn(context *CompilerContext, in InClause) string {
return fmt.Sprintf(
"%s %s (%s)",
in.Left.Accept(context),
in.Op,
in.Right.Accept(context),
)
}
// VisitInsert compiles a INSERT statement
func (c SQLCompiler) VisitInsert(context *CompilerContext, insert InsertStmt) string {
context.DefaultTableName = insert.table.Name
defer func() { context.DefaultTableName = "" }()
cols := List()
values := List()
for k, v := range insert.values {
cols.Clauses = append(cols.Clauses, insert.table.C(k))
values.Clauses = append(values.Clauses, Bind(v))
}
sql := fmt.Sprintf(
"INSERT INTO %s(%s)\nVALUES(%s)",
insert.table.Accept(context),
cols.Accept(context),
values.Accept(context),
)
returning := []string{}
for _, r := range insert.returning {
returning = append(returning, r.Accept(context))
}
if len(insert.returning) > 0 {
sql += fmt.Sprintf(
"\nRETURNING %s",
strings.Join(returning, ", "),
)
}
return sql
}
// VisitJoin compiles a JOIN (ON) clause
func (c SQLCompiler) VisitJoin(context *CompilerContext, join JoinClause) string {
sql := fmt.Sprintf(
"%s\n%s %s",
join.Left.Accept(context),
join.JoinType,
join.Right.Accept(context),
)
if join.OnClause != nil {
sql += " ON " + join.OnClause.Accept(context)
}
return sql
}
// VisitLabel returns a single label, optionally escaped
func (c SQLCompiler) VisitLabel(context *CompilerContext, label string) string {
return c.Dialect.Escape(label)
}
// VisitList compiles a list of values
func (c SQLCompiler) VisitList(context *CompilerContext, list ListClause) string {
var clauses []string
for _, clause := range list.Clauses {
clauses = append(clauses, clause.Accept(context))
}
return strings.Join(clauses, ", ")
}
// VisitOrderBy compiles a ORDER BY sql clause
func (c SQLCompiler) VisitOrderBy(context *CompilerContext, OrderByClause OrderByClause) string {
cols := []string{}
for _, c := range OrderByClause.columns {
cols = append(cols, c.Accept(context))
}
return fmt.Sprintf("ORDER BY %s %s", strings.Join(cols, ", "), OrderByClause.t)
}
// VisitSelect compiles a SELECT statement
func (c SQLCompiler) VisitSelect(context *CompilerContext, selectStmt SelectStmt) string {
lines := []string{}
addLine := func(s string) {
lines = append(lines, s)
}
if !context.InSubQuery && selectStmt.FromClause != nil {
context.DefaultTableName = selectStmt.FromClause.DefaultName()
}
// select
columns := []string{}
for _, c := range selectStmt.SelectList {
sql := c.Accept(context)
columns = append(columns, sql)
}
addLine(fmt.Sprintf("SELECT %s", strings.Join(columns, ", ")))
// from
if selectStmt.FromClause != nil {
addLine(fmt.Sprintf("FROM %s", selectStmt.FromClause.Accept(context)))
}
// where
if selectStmt.WhereClause != nil {
addLine(selectStmt.WhereClause.Accept(context))
}
// group by
groupByCols := []string{}
for _, c := range selectStmt.GroupByClause {
groupByCols = append(groupByCols, context.Dialect.Escape(c.Name))
}
if len(groupByCols) > 0 {
addLine(fmt.Sprintf("GROUP BY %s", strings.Join(groupByCols, ", ")))
}
// having
for _, h := range selectStmt.HavingClause {
sql := h.Accept(context)
addLine(sql)
}
// order by
if selectStmt.OrderByClause != nil {
sql := selectStmt.OrderByClause.Accept(context)
addLine(sql)
}
if (selectStmt.OffsetValue != nil) || (selectStmt.LimitValue != nil) {
var tokens []string
if selectStmt.LimitValue != nil {
tokens = append(tokens, fmt.Sprintf("LIMIT %d", *selectStmt.LimitValue))
}
if selectStmt.OffsetValue != nil {
tokens = append(tokens, fmt.Sprintf("OFFSET %d", *selectStmt.OffsetValue))
}
addLine(strings.Join(tokens, " "))
}
if selectStmt.ForUpdateClause != nil {
addLine(selectStmt.ForUpdateClause.Accept(context))
}
return strings.Join(lines, "\n")
}
// VisitTable returns a table name, optionally escaped
func (SQLCompiler) VisitTable(context *CompilerContext, table TableElem) string {
return context.Compiler.VisitLabel(context, table.Name)
}
// VisitText return a raw SQL clause as is
func (SQLCompiler) VisitText(context *CompilerContext, text TextClause) string {
return text.Text
}
// VisitUpdate compiles a UPDATE statement
func (c SQLCompiler) VisitUpdate(context *CompilerContext, update UpdateStmt) string {
context.DefaultTableName = update.table.Name
defer func() { context.DefaultTableName = "" }()
sql := "UPDATE " + update.table.Accept(context)
sets := List()
for k, v := range update.values {
sets.Clauses = append(sets.Clauses,
Eq(update.table.C(k), Bind(v)))
}
if len(sets.Clauses) > 0 {
sql += "\nSET " + sets.Accept(context)
}
if update.where != nil {
sql += "\n" + update.where.Accept(context)
}
returning := []string{}
for _, c := range update.returning {
returning = append(returning, context.Dialect.Escape(c.Name))
}
if len(returning) > 0 {
sql += "\nRETURNING " + strings.Join(returning, ", ")
}
return sql
}
// VisitUpsert is not implemented and will panic.
// It should be implemented in each dialect
func (c SQLCompiler) VisitUpsert(context *CompilerContext, upsert UpsertStmt) string {
panic("Upsert is not Implemented in this compiler")
}
// VisitWhere compiles a WHERE clause
func (c SQLCompiler) VisitWhere(context *CompilerContext, where WhereClause) string {
return fmt.Sprintf("WHERE %s", where.clause.Accept(context))
}