/
delete_query.go
442 lines (419 loc) · 11.4 KB
/
delete_query.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package sq
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"reflect"
"strconv"
"strings"
"time"
)
// DeleteQuery represents a DELETE query.
type DeleteQuery struct {
nested bool
// WITH
CTEs []CTE
// DELETE FROM
FromTable BaseTable
// USING
UsingTable Table
JoinTables JoinTables
// WHERE
WherePredicate VariadicPredicate
// RETURNING
ReturningFields Fields
// DB
DB DB
RowMapper func(*Row)
Accumulator func()
// Logging
Log Logger
LogFlag LogFlag
logSkip int
}
// ToSQL marshals the DeleteQuery into a query string and args slice.
func (q DeleteQuery) ToSQL() (string, []interface{}) {
q.logSkip += 1
buf := &strings.Builder{}
var args []interface{}
q.AppendSQL(buf, &args, nil)
return buf.String(), args
}
// AppendSQL marshals the DeleteQuery into a buffer and args slice.
func (q DeleteQuery) AppendSQL(buf *strings.Builder, args *[]interface{}, params map[string]int) {
// WITH
if !q.nested {
appendCTEs(buf, args, q.CTEs, nil, q.JoinTables)
}
// DELETE FROM
buf.WriteString("DELETE FROM ")
if q.FromTable == nil {
buf.WriteString("NULL")
} else {
switch v := q.FromTable.(type) {
case Query:
buf.WriteString("(")
v.NestThis().AppendSQL(buf, args, nil)
buf.WriteString(")")
default:
q.FromTable.AppendSQL(buf, args, nil)
}
alias := q.FromTable.GetAlias()
if alias != "" {
buf.WriteString(" AS ")
buf.WriteString(alias)
}
}
// USING
if q.UsingTable != nil {
buf.WriteString(" USING ")
switch v := q.UsingTable.(type) {
case Query:
buf.WriteString("(")
v.NestThis().AppendSQL(buf, args, nil)
buf.WriteString(")")
default:
q.FromTable.AppendSQL(buf, args, nil)
}
alias := q.UsingTable.GetAlias()
if alias != "" {
buf.WriteString(" AS ")
buf.WriteString(alias)
}
}
// JOIN
if len(q.JoinTables) > 0 {
buf.WriteString(" ")
q.JoinTables.AppendSQL(buf, args, nil)
}
// WHERE
if len(q.WherePredicate.Predicates) > 0 {
buf.WriteString(" WHERE ")
q.WherePredicate.toplevel = true
q.WherePredicate.AppendSQLExclude(buf, args, nil, nil)
}
// RETURNING
if len(q.ReturningFields) > 0 {
buf.WriteString(" RETURNING ")
q.ReturningFields.AppendSQLExcludeWithAlias(buf, args, nil, nil)
}
if !q.nested {
query := buf.String()
buf.Reset()
questionToDollarPlaceholders(buf, query)
if q.Log != nil {
var logOutput string
switch {
case Lstats&q.LogFlag != 0:
logOutput = "\n----[ Executing query ]----\n" + buf.String() + " " + fmt.Sprint(*args) +
"\n----[ with bind values ]----\n" + questionInterpolate(query, *args...)
case Linterpolate&q.LogFlag != 0:
logOutput = questionInterpolate(query, *args...)
default:
logOutput = buf.String() + " " + fmt.Sprint(*args)
}
switch q.Log.(type) {
case *log.Logger:
_ = q.Log.Output(q.logSkip+2, logOutput)
default:
_ = q.Log.Output(q.logSkip+1, logOutput)
}
}
}
}
// NestThis indicates to the DeleteQuery that it is nested.
func (q DeleteQuery) NestThis() Query {
q.nested = true
return q
}
// DeleteFrom creates a new DeleteQuery.
func DeleteFrom(table BaseTable) DeleteQuery {
return DeleteQuery{
FromTable: table,
}
}
// With appends the CTEs into the DeleteQuery.
func (q DeleteQuery) With(ctes ...CTE) DeleteQuery {
q.CTEs = append(q.CTEs, ctes...)
return q
}
// DeleteFrom sets the table to be deleted from in the DeleteQuery.
func (q DeleteQuery) DeleteFrom(table BaseTable) DeleteQuery {
q.FromTable = table
return q
}
// Using adds a new table to the DeleteQuery.
func (q DeleteQuery) Using(table Table) DeleteQuery {
q.UsingTable = table
return q
}
// Join joins a new table to the DeleteQuery based on the predicates.
func (q DeleteQuery) Join(table Table, predicate Predicate, predicates ...Predicate) DeleteQuery {
predicates = append([]Predicate{predicate}, predicates...)
q.JoinTables = append(q.JoinTables, JoinTable{
JoinType: JoinTypeInner,
Table: table,
OnPredicates: VariadicPredicate{
Predicates: predicates,
},
})
return q
}
// LeftJoin left joins a new table to the DeleteQuery based on the predicates.
func (q DeleteQuery) LeftJoin(table Table, predicate Predicate, predicates ...Predicate) DeleteQuery {
predicates = append([]Predicate{predicate}, predicates...)
q.JoinTables = append(q.JoinTables, JoinTable{
JoinType: JoinTypeLeft,
Table: table,
OnPredicates: VariadicPredicate{
Predicates: predicates,
},
})
return q
}
// RightJoin right joins a new table to the DeleteQuery based on the predicates.
func (q DeleteQuery) RightJoin(table Table, predicate Predicate, predicates ...Predicate) DeleteQuery {
predicates = append([]Predicate{predicate}, predicates...)
q.JoinTables = append(q.JoinTables, JoinTable{
JoinType: JoinTypeRight,
Table: table,
OnPredicates: VariadicPredicate{
Predicates: predicates,
},
})
return q
}
// FullJoin full joins a table to the DeleteQuery based on the predicates.
func (q DeleteQuery) FullJoin(table Table, predicate Predicate, predicates ...Predicate) DeleteQuery {
predicates = append([]Predicate{predicate}, predicates...)
q.JoinTables = append(q.JoinTables, JoinTable{
JoinType: JoinTypeFull,
Table: table,
OnPredicates: VariadicPredicate{
Predicates: predicates,
},
})
return q
}
// CustomJoin custom joins a table to the DeleteQuery. The join type can be
// specified with a string, e.g. "CROSS JOIN".
func (q DeleteQuery) CustomJoin(joinType JoinType, table Table, predicates ...Predicate) DeleteQuery {
q.JoinTables = append(q.JoinTables, JoinTable{
JoinType: joinType,
Table: table,
OnPredicates: VariadicPredicate{
Predicates: predicates,
},
})
return q
}
// Where appends the predicates to the WHERE clause in the DeleteQuery.
func (q DeleteQuery) Where(predicates ...Predicate) DeleteQuery {
q.WherePredicate.Predicates = append(q.WherePredicate.Predicates, predicates...)
return q
}
// Returning appends the fields to the RETURNING clause of the DeleteQuery.
func (q DeleteQuery) Returning(fields ...Field) DeleteQuery {
q.ReturningFields = append(q.ReturningFields, fields...)
return q
}
// ReturningOne sets the RETURNING clause to RETURNING 1 in the DeleteQuery.
func (q DeleteQuery) ReturningOne() DeleteQuery {
q.ReturningFields = Fields{FieldLiteral("1")}
return q
}
// Returningx sets the rowmapper and accumulator function of the DeleteQuery.
func (q DeleteQuery) Returningx(mapper func(*Row), accumulator func()) DeleteQuery {
q.RowMapper = mapper
q.Accumulator = accumulator
return q
}
// ReturningRowx sets the rowmapper function of the DeleteQuery.
func (q DeleteQuery) ReturningRowx(mapper func(*Row)) DeleteQuery {
q.RowMapper = mapper
return q
}
// Fetch will run DeleteQuery with the given DB. It then maps the results based
// on the mapper function (and optionally runs the accumulator function).
func (q DeleteQuery) Fetch(db DB) (err error) {
q.logSkip += 1
return q.FetchContext(nil, db)
}
// FetchContext will run DeleteQuery with the given DB and context. It then
// maps the results based on the mapper function (and optionally runs the
// accumulator function).
func (q DeleteQuery) FetchContext(ctx context.Context, db DB) (err error) {
if db == nil {
if q.DB == nil {
return errors.New("DB cannot be nil")
}
db = q.DB
}
if q.RowMapper == nil {
return fmt.Errorf("cannot call Fetch/FetchContext without a mapper")
}
logBuf := &strings.Builder{}
start := time.Now()
var rowcount int
defer func() {
if r := recover(); r != nil {
switch v := r.(type) {
case ExitCode:
if v != ExitPeacefully {
err = v
}
case error:
err = v
default:
err = fmt.Errorf("%#v", r)
}
return
}
if q.Log == nil {
return
}
elapsed := time.Since(start)
if Lresults&q.LogFlag != 0 && rowcount > 5 {
logBuf.WriteString("\n...")
}
if Lstats&q.LogFlag != 0 {
logBuf.WriteString("\n(Fetched ")
logBuf.WriteString(strconv.Itoa(rowcount))
logBuf.WriteString(" rows in ")
logBuf.WriteString(elapsed.String())
logBuf.WriteString(")")
}
if logBuf.Len() > 0 {
switch q.Log.(type) {
case *log.Logger:
_ = q.Log.Output(q.logSkip+2, logBuf.String())
default:
_ = q.Log.Output(q.logSkip+1, logBuf.String())
}
}
}()
r := &Row{}
q.RowMapper(r)
q.ReturningFields = r.fields
tmpbuf := &strings.Builder{}
var tmpargs []interface{}
q.logSkip += 1
q.AppendSQL(tmpbuf, &tmpargs, nil)
if ctx == nil {
r.rows, err = db.Query(tmpbuf.String(), tmpargs...)
} else {
r.rows, err = db.QueryContext(ctx, tmpbuf.String(), tmpargs...)
}
if err != nil {
return err
}
defer r.rows.Close()
if len(r.dest) == 0 {
return nil
}
for r.rows.Next() {
rowcount++
err = r.rows.Scan(r.dest...)
if err != nil {
errbuf := &strings.Builder{}
for i := range r.dest {
tmpbuf.Reset()
tmpargs = tmpargs[:0]
r.fields[i].AppendSQLExclude(tmpbuf, &tmpargs, nil, nil)
errbuf.WriteString("\n" +
strconv.Itoa(i) + ") " +
dollarInterpolate(tmpbuf.String(), tmpargs...) + " => " +
reflect.TypeOf(r.dest[i]).String())
}
return fmt.Errorf("Please check if your mapper function is correct:%s\n%w", errbuf.String(), err)
}
if q.Log != nil && Lresults&q.LogFlag != 0 && rowcount <= 5 {
logBuf.WriteString("\n----[ Row ")
logBuf.WriteString(strconv.Itoa(rowcount))
logBuf.WriteString(" ]----")
for i := range r.dest {
tmpbuf.Reset()
tmpargs = tmpargs[:0]
r.fields[i].AppendSQLExclude(tmpbuf, &tmpargs, nil, nil)
logBuf.WriteString("\n")
logBuf.WriteString(dollarInterpolate(tmpbuf.String(), tmpargs...))
logBuf.WriteString(": ")
logBuf.WriteString(appendSQLDisplay(r.dest[i]))
}
}
r.index = 0
q.RowMapper(r)
if q.Accumulator == nil {
break
}
q.Accumulator()
}
if rowcount == 0 && q.Accumulator == nil {
return sql.ErrNoRows
}
if e := r.rows.Close(); e != nil {
return e
}
return r.rows.Err()
}
// Exec will execute the DeleteQuery with the given DB. It will only compute
// the rowsAffected if the ErowsAffected Execflag is passed to it.
func (q DeleteQuery) Exec(db DB, flag ExecFlag) (rowsAffected int64, err error) {
q.logSkip += 1
return q.ExecContext(nil, db, flag)
}
// ExecContext will execute the DeleteQuery with the given DB and context. It will
// only compute the rowsAffected if the ErowsAffected Execflag is passed to it.
func (q DeleteQuery) ExecContext(ctx context.Context, db DB, flag ExecFlag) (rowsAffected int64, err error) {
if db == nil {
if q.DB == nil {
return rowsAffected, errors.New("DB cannot be nil")
}
db = q.DB
}
logBuf := &strings.Builder{}
start := time.Now()
defer func() {
if q.Log == nil {
return
}
elapsed := time.Since(start)
if Lstats&q.LogFlag != 0 && ErowsAffected&flag != 0 {
logBuf.WriteString("\n(Deleted ")
logBuf.WriteString(strconv.FormatInt(rowsAffected, 10))
logBuf.WriteString(" rows in ")
logBuf.WriteString(elapsed.String())
logBuf.WriteString(")")
}
if logBuf.Len() > 0 {
switch q.Log.(type) {
case *log.Logger:
_ = q.Log.Output(q.logSkip+2, logBuf.String())
default:
_ = q.Log.Output(q.logSkip+1, logBuf.String())
}
}
}()
var res sql.Result
tmpbuf := &strings.Builder{}
var tmpargs []interface{}
q.logSkip += 1
q.AppendSQL(tmpbuf, &tmpargs, nil)
if ctx == nil {
res, err = db.Exec(tmpbuf.String(), tmpargs...)
} else {
res, err = db.ExecContext(ctx, tmpbuf.String(), tmpargs...)
}
if err != nil {
return rowsAffected, err
}
if res != nil && ErowsAffected&flag != 0 {
rowsAffected, err = res.RowsAffected()
if err != nil {
return rowsAffected, err
}
}
return rowsAffected, nil
}