forked from ecodeclub/eorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
353 lines (318 loc) · 7.4 KB
/
builder.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
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package eorm
import (
"context"
"database/sql"
"github.com/ecodeclub/eorm/internal/errs"
"github.com/ecodeclub/eorm/internal/model"
"github.com/valyala/bytebufferpool"
)
var _ Executor = &Inserter[any]{}
var _ Executor = &Updater[any]{}
var _ Executor = &Deleter[any]{}
// Query 代表一个查询
type Query struct {
SQL string
Args []any
}
// Querier 查询器,代表最基本的查询
type Querier[T any] struct {
core
Session
qc *QueryContext
}
// RawQuery 创建一个 Querier 实例
// 泛型参数 T 是目标类型。
// 例如,如果查询 User 的数据, 那么 T 就是 User
func RawQuery[T any](sess Session, sql string, args ...any) Querier[T] {
return Querier[T]{
core: sess.getCore(),
Session: sess,
qc: &QueryContext{
q: &Query{
SQL: sql,
Args: args,
},
Type: RAW,
},
}
}
func newQuerier[T any](sess Session, q *Query, meta *model.TableMeta, typ string) Querier[T] {
return Querier[T]{
core: sess.getCore(),
Session: sess,
qc: &QueryContext{
q: q,
meta: meta,
Type: typ,
},
}
}
// Exec 执行 SQL
func (q Querier[T]) Exec(ctx context.Context) Result {
var handler HandleFunc = func(ctx context.Context, qc *QueryContext) *QueryResult {
res, err := q.Session.execContext(ctx, qc.q.SQL, qc.q.Args...)
return &QueryResult{Result: res, Err: err}
}
ms := q.ms
for i := len(ms) - 1; i >= 0; i-- {
handler = ms[i](handler)
}
qr := handler(ctx, q.qc)
var res sql.Result
if qr.Result != nil {
res = qr.Result.(sql.Result)
}
return Result{err: qr.Err, res: res}
}
// Get 执行查询并且返回第一行数据
// 注意在不同的数据库里面,排序可能会不同
// 在没有查找到数据的情况下,会返回 ErrNoRows
func (q Querier[T]) Get(ctx context.Context) (*T, error) {
res := get[T](ctx, q.Session, q.core, q.qc)
if res.Err != nil {
return nil, res.Err
}
return res.Result.(*T), nil
}
type selectorBuilder struct {
builder
columns []Selectable
where []Predicate
distinct bool
having []Predicate
groupBy []string
orderBy []OrderBy
offset int
limit int
}
type builder struct {
core
// 使用 bytebufferpool 以减少内存分配
// 每次调用 Get 之后不要忘记再调用 Put
buffer *bytebufferpool.ByteBuffer
meta *model.TableMeta
args []interface{}
// aliases map[string]struct{}
}
func (b *builder) quote(val string) {
b.writeByte(b.dialect.Quote)
b.writeString(val)
b.writeByte(b.dialect.Quote)
}
func (b *builder) space() {
b.writeByte(' ')
}
func (b *builder) point() {
b.writeByte('.')
}
func (b *builder) writeString(val string) {
_, _ = b.buffer.WriteString(val)
}
func (b *builder) writeByte(c byte) {
_ = b.buffer.WriteByte(c)
}
func (b *builder) end() {
b.writeByte(';')
}
func (b *builder) comma() {
b.writeByte(',')
}
func (b *builder) parameter(arg interface{}) {
if b.args == nil {
// TODO 4 may be not a good number
b.args = make([]interface{}, 0, 4)
}
b.writeByte('?')
b.args = append(b.args, arg)
}
func (b *builder) buildExpr(expr Expr) error {
switch e := expr.(type) {
case nil:
case RawExpr:
b.buildRawExpr(e)
case Column:
// _, ok := b.aliases[e.name]
// if ok {
// b.quote(e.name)
// return nil
// }
return b.buildColumn(e)
case Aggregate:
if err := b.buildHavingAggregate(e); err != nil {
return err
}
case valueExpr:
b.parameter(e.val)
case binaryExpr:
if err := b.buildBinaryExpr(e); err != nil {
return err
}
case Predicate:
if err := b.buildBinaryExpr(binaryExpr(e)); err != nil {
return err
}
case values:
if err := b.buildIns(e); err != nil {
return err
}
case Subquery:
return b.buildSubquery(e, false)
case SubqueryExpr:
b.writeString(e.pred)
b.writeByte(' ')
return b.buildSubquery(e.s, false)
default:
return errs.NewErrUnsupportedExpressionType()
}
return nil
}
func (b *builder) buildPredicates(predicates []Predicate) error {
p := predicates[0]
for i := 1; i < len(predicates); i++ {
p = p.And(predicates[i])
}
return b.buildExpr(p)
}
func (b *builder) buildHavingAggregate(aggregate Aggregate) error {
b.writeString(aggregate.fn)
b.writeByte('(')
if aggregate.distinct {
b.writeString("DISTINCT ")
}
cMeta, ok := b.meta.FieldMap[aggregate.arg]
if !ok {
return errs.NewInvalidFieldError(aggregate.arg)
}
b.quote(cMeta.ColumnName)
b.writeByte(')')
return nil
}
func (b *builder) buildBinaryExpr(e binaryExpr) error {
err := b.buildSubExpr(e.left)
if err != nil {
return err
}
b.writeString(e.op.text)
return b.buildSubExpr(e.right)
}
func (b *builder) buildRawExpr(e RawExpr) {
b.writeString(e.raw)
b.args = append(b.args, e.args...)
}
func (b *builder) buildSubExpr(subExpr Expr) error {
switch r := subExpr.(type) {
case MathExpr:
b.writeByte('(')
if err := b.buildBinaryExpr(binaryExpr(r)); err != nil {
return err
}
b.writeByte(')')
case Predicate:
b.writeByte('(')
if err := b.buildBinaryExpr(binaryExpr(r)); err != nil {
return err
}
b.writeByte(')')
default:
if err := b.buildExpr(r); err != nil {
return err
}
}
return nil
}
func (b *builder) buildIns(is values) error {
b.writeByte('(')
for idx, inVal := range is.data {
if idx > 0 {
b.writeByte(',')
}
b.args = append(b.args, inVal)
b.writeByte('?')
}
b.writeByte(')')
return nil
}
func (q Querier[T]) GetMulti(ctx context.Context) ([]*T, error) {
res := getMulti[T](ctx, q.Session, q.core, q.qc)
if res.Err != nil {
return nil, res.Err
}
return res.Result.([]*T), nil
}
func (b *builder) buildColumn(c Column) error {
switch table := c.table.(type) {
case nil:
fd, ok := b.meta.FieldMap[c.name]
// 字段不对,或者说列不对
if !ok {
return errs.NewInvalidFieldError(c.name)
}
b.quote(fd.ColumnName)
if c.alias != "" {
// b.aliases[c.alias] = struct{}{}
b.writeString(" AS ")
b.quote(c.alias)
}
case Table:
m, err := b.metaRegistry.Get(table.entity)
if err != nil {
return err
}
fd, ok := m.FieldMap[c.name]
if !ok {
return errs.NewInvalidFieldError(c.name)
}
if table.alias != "" {
b.quote(table.alias)
b.point()
}
b.quote(fd.ColumnName)
if c.alias != "" {
b.writeString(" AS ")
b.quote(c.alias)
}
default:
return errs.NewUnsupportedTableReferenceError(table)
}
return nil
}
// buildSubquery 構建子查詢 SQL,
// useAlias 決定是否顯示別名,即使有別名
func (b *builder) buildSubquery(sub Subquery, useAlias bool) error {
query, err := sub.q.Build()
if err != nil {
return err
}
b.writeByte('(')
// 拿掉最後 ';'
b.writeString(query.SQL[:len(query.SQL)-1])
// 因為有 build() ,所以理應 args 也需要跟 SQL 一起處理
if len(query.Args) > 0 {
b.addArgs(query.Args...)
}
b.writeByte(')')
if useAlias {
b.writeString(" AS ")
b.quote(sub.getAlias())
}
return nil
}
func (b *builder) addArgs(args ...any) {
if b.args == nil {
b.args = make([]any, 0, 8)
}
b.args = append(b.args, args...)
}