-
Notifications
You must be signed in to change notification settings - Fork 372
/
query.go
331 lines (273 loc) · 9.05 KB
/
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
// Copyright 2021 FerretDB Inc.
//
// 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 postgresql
import (
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/FerretDB/FerretDB/internal/backends/postgresql/metadata"
"github.com/FerretDB/FerretDB/internal/handler/sjson"
"github.com/FerretDB/FerretDB/internal/types"
"github.com/FerretDB/FerretDB/internal/util/iterator"
"github.com/FerretDB/FerretDB/internal/util/lazyerrors"
"github.com/FerretDB/FerretDB/internal/util/must"
)
// selectParams contains params that specify how prepareSelectClause function will
// build the SELECT SQL query.
type selectParams struct {
Schema string
Table string
Comment string
Capped bool
OnlyRecordIDs bool
}
// prepareSelectClause returns SELECT clause for default column of provided schema and table name.
//
// For capped collection with onlyRecordIDs, it returns select clause for recordID column.
//
// For capped collection, it returns select clause for recordID column and default column.
func prepareSelectClause(params *selectParams) string {
if params == nil {
params = new(selectParams)
}
if params.Comment != "" {
params.Comment = strings.ReplaceAll(params.Comment, "/*", "/ *")
params.Comment = strings.ReplaceAll(params.Comment, "*/", "* /")
params.Comment = `/* ` + params.Comment + ` */`
}
if params.Capped && params.OnlyRecordIDs {
return fmt.Sprintf(
`SELECT %s %s FROM %s`,
params.Comment,
metadata.RecordIDColumn,
pgx.Identifier{params.Schema, params.Table}.Sanitize(),
)
}
if params.Capped {
return fmt.Sprintf(
`SELECT %s %s, %s FROM %s`,
params.Comment,
metadata.RecordIDColumn,
metadata.DefaultColumn,
pgx.Identifier{params.Schema, params.Table}.Sanitize(),
)
}
return fmt.Sprintf(
`SELECT %s %s FROM %s`,
params.Comment,
metadata.DefaultColumn,
pgx.Identifier{params.Schema, params.Table}.Sanitize(),
)
}
// prepareWhereClause adds WHERE clause with given filters to the query and returns the query and arguments.
func prepareWhereClause(p *metadata.Placeholder, sqlFilters *types.Document) (string, []any, error) {
var filters []string
var args []any
iter := sqlFilters.Iterator()
defer iter.Close()
// iterate through root document
for {
rootKey, rootVal, err := iter.Next()
if err != nil {
if errors.Is(err, iterator.ErrIteratorDone) {
break
}
return "", nil, lazyerrors.Error(err)
}
keyOperator := "->" // keyOperator is the operator that is used to access the field. (->/#>)
// key can be either a string '"v"' or PostgreSQL path '{v,foo}'.
// We use path type only for dot notation due to simplicity of SQL queries, and the fact
// that path doesn't handle empty keys.
var key any = rootKey
// don't pushdown $comment, as it's attached to query with select clause
//
// all of the other top-level operators such as `$or` do not support pushdown yet
if strings.HasPrefix(rootKey, "$") {
continue
}
path, err := types.NewPathFromString(rootKey)
var pe *types.PathError
switch {
case err == nil:
if path.Len() > 1 {
keyOperator = "#>"
key = path.Slice() // '{v,foo}'
}
case errors.As(err, &pe):
// ignore empty key error, otherwise return error
if pe.Code() != types.ErrPathElementEmpty {
return "", nil, lazyerrors.Error(err)
}
default:
panic("Invalid error type: PathError expected")
}
switch v := rootVal.(type) {
case *types.Document:
iter := v.Iterator()
defer iter.Close()
// iterate through subdocument, as it may contain operators
for {
k, v, err := iter.Next()
if err != nil {
if errors.Is(err, iterator.ErrIteratorDone) {
break
}
return "", nil, lazyerrors.Error(err)
}
switch k {
case "$eq":
if f, a := filterEqual(p, key, v, keyOperator); f != "" {
filters = append(filters, f)
args = append(args, a...)
}
case "$ne":
sql := `NOT ( ` +
// does document contain the key,
// it is necessary, as NOT won't work correctly if the key does not exist.
`%[1]s ? %[2]s AND ` +
// does the value under the key is equal to filter value
`%[1]s->%[2]s @> %[3]s AND ` +
// does the value type is equal to the filter's one
`%[1]s->'$s'->'p'->%[2]s->'t' = '"%[4]s"' )`
switch v := v.(type) {
case *types.Document, *types.Array, types.Binary,
types.NullType, types.Regex, types.Timestamp:
// type not supported for pushdown
case float64, bool, int32, int64:
filters = append(filters, fmt.Sprintf(
sql,
metadata.DefaultColumn,
p.Next(),
p.Next(),
sjson.GetTypeOfValue(v),
))
// merge with the case below?
// TODO https://github.com/FerretDB/FerretDB/issues/3626
args = append(args, rootKey, v)
case string, types.ObjectID, time.Time:
filters = append(filters, fmt.Sprintf(
sql,
metadata.DefaultColumn,
p.Next(),
p.Next(),
sjson.GetTypeOfValue(v),
))
// merge with the case above?
// TODO https://github.com/FerretDB/FerretDB/issues/3626
args = append(args, rootKey, string(must.NotFail(sjson.MarshalSingleValue(v))))
default:
panic(fmt.Sprintf("Unexpected type of value: %v", v))
}
default:
// $gt and $lt
// TODO https://github.com/FerretDB/FerretDB/issues/1875
continue
}
}
case *types.Array, types.Binary, types.NullType, types.Regex, types.Timestamp:
// type not supported for pushdown
case float64, string, types.ObjectID, bool, time.Time, int32, int64:
if f, a := filterEqual(p, key, v, keyOperator); f != "" {
filters = append(filters, f)
args = append(args, a...)
}
default:
panic(fmt.Sprintf("Unexpected type of value: %v", v))
}
}
var filter string
if len(filters) > 0 {
filter = ` WHERE ` + strings.Join(filters, " AND ")
}
return filter, args, nil
}
// prepareOrderByClause returns ORDER BY clause with arguments for given sort document.
//
// The provided sort document should be already validated.
// Provided document should only contain a single value.
func prepareOrderByClause(sort *types.Document) (string, []any) {
if sort.Len() != 1 {
return "", nil
}
v := must.NotFail(sort.Get("$natural"))
var order string
switch v.(int64) {
case 1:
// Ascending order
case -1:
order = " DESC"
default:
panic("not reachable")
}
return fmt.Sprintf(" ORDER BY %s%s", metadata.RecordIDColumn, order), nil
}
// filterEqual returns the proper SQL filter with arguments that filters documents
// where the value under k is equal to v.
func filterEqual(p *metadata.Placeholder, k any, v any, operator string) (filter string, args []any) {
// Select if value under the key is equal to provided value.
sql := `%[1]s%[2]s%[3]s @> %[4]s`
switch v := v.(type) {
case *types.Document, *types.Array, types.Binary,
types.NullType, types.Regex, types.Timestamp:
// type not supported for pushdown
case float64:
// If value is not safe double, fetch all numbers out of safe range.
// TODO https://github.com/FerretDB/FerretDB/issues/3626
switch {
case v > types.MaxSafeDouble:
sql = `%[1]s%[2]s%[3]s > %[4]s`
v = types.MaxSafeDouble
case v < -types.MaxSafeDouble:
sql = `%[1]s%[2]s%[3]s < %[4]s`
v = -types.MaxSafeDouble
default:
// don't change the default eq query
}
filter = fmt.Sprintf(sql, metadata.DefaultColumn, operator, p.Next(), p.Next())
args = append(args, k, v)
case string, types.ObjectID, time.Time:
// merge with the case below?
// TODO https://github.com/FerretDB/FerretDB/issues/3626
// don't change the default eq query
filter = fmt.Sprintf(sql, metadata.DefaultColumn, operator, p.Next(), p.Next())
args = append(args, k, string(must.NotFail(sjson.MarshalSingleValue(v))))
case bool, int32:
// merge with the case above?
// TODO https://github.com/FerretDB/FerretDB/issues/3626
// don't change the default eq query
filter = fmt.Sprintf(sql, metadata.DefaultColumn, operator, p.Next(), p.Next())
args = append(args, k, v)
case int64:
// TODO https://github.com/FerretDB/FerretDB/issues/3626
maxSafeDouble := int64(types.MaxSafeDouble)
// If value cannot be safe double, fetch all numbers out of the safe range.
switch {
case v > maxSafeDouble:
sql = `%[1]s%[2]s%[3]s > %[4]s`
v = maxSafeDouble
case v < -maxSafeDouble:
sql = `%[1]s%[2]s%[3]s < %[4]s`
v = -maxSafeDouble
default:
// don't change the default eq query
}
filter = fmt.Sprintf(sql, metadata.DefaultColumn, operator, p.Next(), p.Next())
args = append(args, k, v)
default:
panic(fmt.Sprintf("Unexpected type of value: %v", v))
}
return
}