-
Notifications
You must be signed in to change notification settings - Fork 374
/
msg_find.go
201 lines (163 loc) · 5.92 KB
/
msg_find.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
// 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 sqlite
import (
"context"
"errors"
"fmt"
"time"
"github.com/FerretDB/FerretDB/internal/backends"
"github.com/FerretDB/FerretDB/internal/clientconn/conninfo"
"github.com/FerretDB/FerretDB/internal/clientconn/cursor"
"github.com/FerretDB/FerretDB/internal/handlers/common"
"github.com/FerretDB/FerretDB/internal/handlers/commonerrors"
"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"
"github.com/FerretDB/FerretDB/internal/wire"
)
// MsgFind implements HandlerInterface.
func (h *Handler) MsgFind(ctx context.Context, msg *wire.OpMsg) (*wire.OpMsg, error) {
document, err := msg.Document()
if err != nil {
return nil, lazyerrors.Error(err)
}
params, err := common.GetFindParams(document, h.L)
if err != nil {
return nil, err
}
username, _ := conninfo.Get(ctx).Auth()
db, err := h.b.Database(params.DB)
if err != nil {
if backends.ErrorCodeIs(err, backends.ErrorCodeDatabaseNameIsInvalid) {
msg := fmt.Sprintf("Invalid namespace specified '%s.%s'", params.DB, params.Collection)
return nil, commonerrors.NewCommandErrorMsgWithArgument(commonerrors.ErrInvalidNamespace, msg, "find")
}
return nil, lazyerrors.Error(err)
}
c, err := db.Collection(params.Collection)
if err != nil {
if backends.ErrorCodeIs(err, backends.ErrorCodeCollectionNameIsInvalid) {
msg := fmt.Sprintf("Invalid collection name: %s", params.Collection)
return nil, commonerrors.NewCommandErrorMsgWithArgument(commonerrors.ErrInvalidNamespace, msg, "find")
}
return nil, lazyerrors.Error(err)
}
qp := &backends.QueryParams{
Comment: params.Comment,
}
if params.Filter != nil {
if qp.Comment, err = common.GetOptionalParam(params.Filter, "$comment", qp.Comment); err != nil {
return nil, err
}
}
if !h.DisableFilterPushdown {
qp.Filter = params.Filter
}
// Skip sorting if there are more than one sort parameters
if h.EnableSortPushdown && params.Sort.Len() == 1 {
var order types.SortType
k := params.Sort.Keys()[0]
v := params.Sort.Values()[0]
order, err = common.GetSortType(k, v)
if err != nil {
return nil, err
}
qp.Sort = &backends.SortField{
Key: k,
Descending: order == types.Descending,
}
}
// Limit pushdown is not applied if:
// - `filter` is set, it must fetch all documents to filter them in memory;
// - `sort` is set but `EnableSortPushdown` is not set, it must fetch all documents
// and sort them in memory;
// - `skip` is non-zero value, skip pushdown is not supported yet.
if params.Filter.Len() == 0 && (params.Sort.Len() == 0 || h.EnableSortPushdown) && params.Skip == 0 {
qp.Limit = params.Limit
}
cancel := func() {}
if params.MaxTimeMS != 0 {
// It is not clear if maxTimeMS affects only find, or both find and getMore (as the current code does).
// TODO https://github.com/FerretDB/FerretDB/issues/2984
ctx, cancel = context.WithTimeout(ctx, time.Duration(params.MaxTimeMS)*time.Millisecond)
}
// closer accumulates all things that should be closed / canceled.
closer := iterator.NewMultiCloser(iterator.CloserFunc(cancel))
queryRes, err := c.Query(ctx, qp)
if err != nil {
closer.Close()
return nil, lazyerrors.Error(err)
}
closer.Add(queryRes.Iter)
iter := common.FilterIterator(queryRes.Iter, closer, params.Filter)
iter, err = common.SortIterator(iter, closer, params.Sort)
if err != nil {
closer.Close()
var pathErr *types.PathError
if errors.As(err, &pathErr) && pathErr.Code() == types.ErrPathElementEmpty {
return nil, commonerrors.NewCommandErrorMsgWithArgument(
commonerrors.ErrPathContainsEmptyElement,
"Empty field names in path are not allowed",
document.Command(),
)
}
return nil, lazyerrors.Error(err)
}
iter = common.SkipIterator(iter, closer, params.Skip)
iter = common.LimitIterator(iter, closer, params.Limit)
iter, err = common.ProjectionIterator(iter, closer, params.Projection, params.Filter)
if err != nil {
closer.Close()
return nil, lazyerrors.Error(err)
}
// Combine iterators chain and closer into a cursor to pass around.
// The context will be canceled when client disconnects or after maxTimeMS.
cursor := h.cursors.NewCursor(ctx, &cursor.NewParams{
Iter: iterator.WithClose(iterator.Interface[struct{}, *types.Document](iter), closer.Close),
DB: params.DB,
Collection: params.Collection,
Username: username,
})
cursorID := cursor.ID
firstBatchDocs, err := iterator.ConsumeValuesN(iterator.Interface[struct{}, *types.Document](cursor), int(params.BatchSize))
if err != nil {
cursor.Close()
return nil, lazyerrors.Error(err)
}
firstBatch := types.MakeArray(len(firstBatchDocs))
for _, doc := range firstBatchDocs {
firstBatch.Append(doc)
}
if params.SingleBatch || firstBatch.Len() < int(params.BatchSize) {
// support tailable cursors
// TODO https://github.com/FerretDB/FerretDB/issues/2283
// let the client know that there are no more results
cursorID = 0
cursor.Close()
}
var reply wire.OpMsg
must.NoError(reply.SetSections(wire.OpMsgSection{
Documents: []*types.Document{must.NotFail(types.NewDocument(
"cursor", must.NotFail(types.NewDocument(
"firstBatch", firstBatch,
"id", cursorID,
"ns", params.DB+"."+params.Collection,
)),
"ok", float64(1),
))},
}))
return &reply, nil
}