| 1 |
// Copyright 2019 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// TODO(jba): figure out how to get filters with uints to work: since they are represented as |
| 16 |
// int64s, the sign is wrong. |
| 17 |
|
| 18 |
package gcpfirestore |
| 19 |
|
| 20 |
import ( |
| 21 |
"context" |
| 22 |
"fmt" |
| 23 |
"math" |
| 24 |
"path" |
| 25 |
"reflect" |
| 26 |
"strings" |
| 27 |
"time" |
| 28 |
|
| 29 |
pb "cloud.google.com/go/firestore/apiv1/firestorepb" |
| 30 |
"gocloud.dev/docstore/driver" |
| 31 |
"gocloud.dev/internal/gcerr" |
| 32 |
"google.golang.org/protobuf/types/known/wrapperspb" |
| 33 |
) |
| 34 |
|
| 35 |
func (c *collection) RunGetQuery(ctx context.Context, q *driver.Query) (driver.DocumentIterator, error) { |
| 36 |
return c.newDocIterator(ctx, q) |
| 37 |
} |
| 38 |
|
| 39 |
func (c *collection) newDocIterator(ctx context.Context, q *driver.Query) (*docIterator, error) { |
| 40 |
sq, localFilters, err := c.queryToProto(q) |
| 41 |
if err != nil { |
| 42 |
return nil, err |
| 43 |
} |
| 44 |
req := &pb.RunQueryRequest{ |
| 45 |
Parent: path.Dir(c.collPath), |
| 46 |
QueryType: &pb.RunQueryRequest_StructuredQuery{sq}, |
| 47 |
} |
| 48 |
if q.BeforeQuery != nil { |
| 49 |
if err := q.BeforeQuery(driver.AsFunc(req)); err != nil { |
| 50 |
return nil, err |
| 51 |
} |
| 52 |
} |
| 53 |
ctx, cancel := context.WithCancel(ctx) |
| 54 |
sc, err := c.client.RunQuery(withResourceHeader(ctx, c.dbPath), req) |
| 55 |
if err != nil { |
| 56 |
cancel() |
| 57 |
return nil, err |
| 58 |
} |
| 59 |
return &docIterator{ |
| 60 |
streamClient: sc, |
| 61 |
nameField: c.nameField, |
| 62 |
revField: c.opts.RevisionField, |
| 63 |
localFilters: localFilters, |
| 64 |
cancel: cancel, |
| 65 |
}, nil |
| 66 |
} |
| 67 |
|
| 68 |
// ////////////////////////////////////////////////////////////// |
| 69 |
// The code below is adapted from cloud.google.com/go/firestore. |
| 70 |
|
| 71 |
type docIterator struct { |
| 72 |
streamClient pb.Firestore_RunQueryClient |
| 73 |
nameField, revField string |
| 74 |
localFilters []driver.Filter |
| 75 |
// We call cancel to make sure the stream client doesn't leak resources. |
| 76 |
// We don't need to call it if Recv() returns a non-nil error. |
| 77 |
// See https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. |
| 78 |
cancel func() |
| 79 |
} |
| 80 |
|
| 81 |
func (it *docIterator) Next(ctx context.Context, doc driver.Document) error { |
| 82 |
res, err := it.nextResponse(ctx) |
| 83 |
if err != nil { |
| 84 |
return err |
| 85 |
} |
| 86 |
return decodeDoc(res.Document, doc, it.nameField, it.revField) |
| 87 |
} |
| 88 |
|
| 89 |
func (it *docIterator) nextResponse(ctx context.Context) (*pb.RunQueryResponse, error) { |
| 90 |
for { |
| 91 |
res, err := it.streamClient.Recv() |
| 92 |
if err != nil { |
| 93 |
return nil, err |
| 94 |
} |
| 95 |
// No document => partial progress; keep receiving. |
| 96 |
if res.Document == nil { |
| 97 |
continue |
| 98 |
} |
| 99 |
match, err := it.evaluateLocalFilters(res.Document) |
| 100 |
if err != nil { |
| 101 |
return nil, err |
| 102 |
} |
| 103 |
if match { |
| 104 |
return res, nil |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
// Report whether the filters are true of the document. |
| 110 |
func (it *docIterator) evaluateLocalFilters(pdoc *pb.Document) (bool, error) { |
| 111 |
if len(it.localFilters) == 0 { |
| 112 |
return true, nil |
| 113 |
} |
| 114 |
// TODO(jba): optimization: evaluate the filter directly on the proto document, without decoding. |
| 115 |
m := map[string]any{} |
| 116 |
doc, err := driver.NewDocument(m) |
| 117 |
if err != nil { |
| 118 |
return false, err |
| 119 |
} |
| 120 |
if err := decodeDoc(pdoc, doc, it.nameField, it.revField); err != nil { |
| 121 |
return false, err |
| 122 |
} |
| 123 |
for _, f := range it.localFilters { |
| 124 |
if !evaluateFilter(f, doc) { |
| 125 |
return false, nil |
| 126 |
} |
| 127 |
} |
| 128 |
return true, nil |
| 129 |
} |
| 130 |
|
| 131 |
func evaluateFilter(f driver.Filter, doc driver.Document) bool { |
| 132 |
val, err := doc.Get(f.FieldPath) |
| 133 |
if err != nil { |
| 134 |
// Treat a missing field as false. |
| 135 |
return false |
| 136 |
} |
| 137 |
// Compare times. |
| 138 |
if t1, ok := val.(time.Time); ok { |
| 139 |
if t2, ok := f.Value.(time.Time); ok { |
| 140 |
return applyComparison(f.Op, driver.CompareTimes(t1, t2)) |
| 141 |
} |
| 142 |
return false |
| 143 |
} |
| 144 |
lhs := reflect.ValueOf(val) |
| 145 |
rhs := reflect.ValueOf(f.Value) |
| 146 |
if lhs.Kind() == reflect.String { |
| 147 |
if rhs.Kind() != reflect.String { |
| 148 |
return false |
| 149 |
} |
| 150 |
return applyComparison(f.Op, strings.Compare(lhs.String(), rhs.String())) |
| 151 |
} |
| 152 |
|
| 153 |
if lhs.Kind() == reflect.Bool { |
| 154 |
if rhs.Kind() != reflect.Bool { |
| 155 |
return false |
| 156 |
} |
| 157 |
cmp := 0 |
| 158 |
if lhs.Bool() != rhs.Bool() { |
| 159 |
cmp = -1 |
| 160 |
} |
| 161 |
return applyComparison(f.Op, cmp) |
| 162 |
} |
| 163 |
|
| 164 |
cmp, err := driver.CompareNumbers(lhs, rhs) |
| 165 |
if err != nil { |
| 166 |
return false |
| 167 |
} |
| 168 |
return applyComparison(f.Op, cmp) |
| 169 |
} |
| 170 |
|
| 171 |
// op is one of the five permitted docstore operators ("=", "<", etc.) |
| 172 |
// c is the result of strings.Compare or the like. |
| 173 |
func applyComparison(op string, c int) bool { |
| 174 |
switch op { |
| 175 |
case driver.EqualOp: |
| 176 |
return c == 0 |
| 177 |
case ">": |
| 178 |
return c > 0 |
| 179 |
case "<": |
| 180 |
return c < 0 |
| 181 |
case ">=": |
| 182 |
return c >= 0 |
| 183 |
case "<=": |
| 184 |
return c <= 0 |
| 185 |
default: |
| 186 |
panic("bad op") |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
func (it *docIterator) Stop() { it.cancel() } |
| 191 |
|
| 192 |
func (it *docIterator) As(i any) bool { |
| 193 |
p, ok := i.(*pb.Firestore_RunQueryClient) |
| 194 |
if !ok { |
| 195 |
return false |
| 196 |
} |
| 197 |
*p = it.streamClient |
| 198 |
return true |
| 199 |
} |
| 200 |
|
| 201 |
// Converts the query to a Firestore proto. Also returns filters that need to be |
| 202 |
// evaluated on the client. |
| 203 |
func (c *collection) queryToProto(q *driver.Query) (*pb.StructuredQuery, []driver.Filter, error) { |
| 204 |
// The collection ID is the last component of the collection path. |
| 205 |
collID := path.Base(c.collPath) |
| 206 |
p := &pb.StructuredQuery{ |
| 207 |
From: []*pb.StructuredQuery_CollectionSelector{{CollectionId: collID}}, |
| 208 |
} |
| 209 |
if len(q.FieldPaths) > 0 { |
| 210 |
p.Select = &pb.StructuredQuery_Projection{} |
| 211 |
for _, fp := range q.FieldPaths { |
| 212 |
p.Select.Fields = append(p.Select.Fields, fieldRef(fp)) |
| 213 |
} |
| 214 |
} |
| 215 |
// Apply offset. |
| 216 |
if q.Offset > 0 { |
| 217 |
p.Offset = int32(q.Offset) |
| 218 |
} |
| 219 |
// Apply limit. |
| 220 |
if q.Limit > 0 { |
| 221 |
p.Limit = &wrapperspb.Int32Value{Value: int32(q.Limit)} |
| 222 |
} |
| 223 |
|
| 224 |
// TODO(jba): make sure we retrieve the fields needed for local filters. |
| 225 |
sendFilters, localFilters := splitFilters(q.Filters) |
| 226 |
if len(localFilters) > 0 && !c.opts.AllowLocalFilters { |
| 227 |
return nil, nil, gcerr.Newf(gcerr.InvalidArgument, nil, "query requires local filters; set Options.AllowLocalFilters to true to enable") |
| 228 |
} |
| 229 |
|
| 230 |
// If there is only one filter, use it directly. Otherwise, construct |
| 231 |
// a CompositeFilter. |
| 232 |
var pfs []*pb.StructuredQuery_Filter |
| 233 |
for _, f := range sendFilters { |
| 234 |
pf, err := c.filterToProto(f) |
| 235 |
if err != nil { |
| 236 |
return nil, nil, err |
| 237 |
} |
| 238 |
pfs = append(pfs, pf) |
| 239 |
} |
| 240 |
if len(pfs) == 1 { |
| 241 |
p.Where = pfs[0] |
| 242 |
} else if len(pfs) > 1 { |
| 243 |
p.Where = &pb.StructuredQuery_Filter{ |
| 244 |
FilterType: &pb.StructuredQuery_Filter_CompositeFilter{&pb.StructuredQuery_CompositeFilter{ |
| 245 |
Op: pb.StructuredQuery_CompositeFilter_AND, |
| 246 |
Filters: pfs, |
| 247 |
}}, |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
if q.OrderByField != "" { |
| 252 |
// TODO(jba): reorder filters so order-by one is first of inequalities? |
| 253 |
// TODO(jba): see if it's OK if filter inequality direction differs from sort direction. |
| 254 |
fref := []string{q.OrderByField} |
| 255 |
if q.OrderByField == c.nameField { |
| 256 |
fref[0] = "__name__" |
| 257 |
} |
| 258 |
var dir pb.StructuredQuery_Direction |
| 259 |
if q.OrderAscending { |
| 260 |
dir = pb.StructuredQuery_ASCENDING |
| 261 |
} else { |
| 262 |
dir = pb.StructuredQuery_DESCENDING |
| 263 |
} |
| 264 |
p.OrderBy = []*pb.StructuredQuery_Order{{Field: fieldRef(fref), Direction: dir}} |
| 265 |
} |
| 266 |
|
| 267 |
// TODO(jba): cursors (start/end) |
| 268 |
return p, localFilters, nil |
| 269 |
} |
| 270 |
|
| 271 |
// splitFilters separates the list of query filters into those we can send to the Firestore service, |
| 272 |
// and those we must evaluate here on the client. |
| 273 |
func splitFilters(fs []driver.Filter) (sendToFirestore, evaluateLocally []driver.Filter) { |
| 274 |
// Enforce that only one field can have an inequality. |
| 275 |
var rangeFP []string |
| 276 |
for _, f := range fs { |
| 277 |
if f.Op == driver.EqualOp { |
| 278 |
sendToFirestore = append(sendToFirestore, f) |
| 279 |
} else { |
| 280 |
if rangeFP == nil || driver.FieldPathsEqual(rangeFP, f.FieldPath) { |
| 281 |
// Multiple inequality filters on the same field are OK. |
| 282 |
rangeFP = f.FieldPath |
| 283 |
sendToFirestore = append(sendToFirestore, f) |
| 284 |
} else { |
| 285 |
evaluateLocally = append(evaluateLocally, f) |
| 286 |
} |
| 287 |
} |
| 288 |
} |
| 289 |
return sendToFirestore, evaluateLocally |
| 290 |
} |
| 291 |
|
| 292 |
func (c *collection) filterToProto(f driver.Filter) (*pb.StructuredQuery_Filter, error) { |
| 293 |
// Treat filters on the name field specially. |
| 294 |
if c.nameField != "" && driver.FieldPathEqualsField(f.FieldPath, c.nameField) { |
| 295 |
v := reflect.ValueOf(f.Value) |
| 296 |
if v.Kind() != reflect.String { |
| 297 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, |
| 298 |
"name field filter value %v of type %[1]T is not a string", f.Value) |
| 299 |
} |
| 300 |
return newFieldFilter([]string{"__name__"}, f.Op, |
| 301 |
&pb.Value{ValueType: &pb.Value_ReferenceValue{c.collPath + "/" + v.String()}}) |
| 302 |
} |
| 303 |
// "= nil" and "= NaN" are handled specially. |
| 304 |
if uop, ok := unaryOpFor(f.Value); ok { |
| 305 |
if f.Op != driver.EqualOp { |
| 306 |
return nil, fmt.Errorf("firestore: must use '=' when comparing %v", f.Value) |
| 307 |
} |
| 308 |
return &pb.StructuredQuery_Filter{ |
| 309 |
FilterType: &pb.StructuredQuery_Filter_UnaryFilter{ |
| 310 |
UnaryFilter: &pb.StructuredQuery_UnaryFilter{ |
| 311 |
OperandType: &pb.StructuredQuery_UnaryFilter_Field{ |
| 312 |
Field: fieldRef(f.FieldPath), |
| 313 |
}, |
| 314 |
Op: uop, |
| 315 |
}, |
| 316 |
}, |
| 317 |
}, nil |
| 318 |
} |
| 319 |
pv, err := encodeValue(f.Value) |
| 320 |
if err != nil { |
| 321 |
return nil, err |
| 322 |
} |
| 323 |
return newFieldFilter(f.FieldPath, f.Op, pv) |
| 324 |
} |
| 325 |
|
| 326 |
func unaryOpFor(value any) (pb.StructuredQuery_UnaryFilter_Operator, bool) { |
| 327 |
switch { |
| 328 |
case value == nil: |
| 329 |
return pb.StructuredQuery_UnaryFilter_IS_NULL, true |
| 330 |
case isNaN(value): |
| 331 |
return pb.StructuredQuery_UnaryFilter_IS_NAN, true |
| 332 |
default: |
| 333 |
return pb.StructuredQuery_UnaryFilter_OPERATOR_UNSPECIFIED, false |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
func isNaN(x any) bool { |
| 338 |
switch x := x.(type) { |
| 339 |
case float32: |
| 340 |
return math.IsNaN(float64(x)) |
| 341 |
case float64: |
| 342 |
return math.IsNaN(x) |
| 343 |
default: |
| 344 |
return false |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
func fieldRef(fp []string) *pb.StructuredQuery_FieldReference { |
| 349 |
return &pb.StructuredQuery_FieldReference{FieldPath: toServiceFieldPath(fp)} |
| 350 |
} |
| 351 |
|
| 352 |
func newFieldFilter(fp []string, op string, val *pb.Value) (*pb.StructuredQuery_Filter, error) { |
| 353 |
var fop pb.StructuredQuery_FieldFilter_Operator |
| 354 |
switch op { |
| 355 |
case "<": |
| 356 |
fop = pb.StructuredQuery_FieldFilter_LESS_THAN |
| 357 |
case "<=": |
| 358 |
fop = pb.StructuredQuery_FieldFilter_LESS_THAN_OR_EQUAL |
| 359 |
case ">": |
| 360 |
fop = pb.StructuredQuery_FieldFilter_GREATER_THAN |
| 361 |
case ">=": |
| 362 |
fop = pb.StructuredQuery_FieldFilter_GREATER_THAN_OR_EQUAL |
| 363 |
case driver.EqualOp: |
| 364 |
fop = pb.StructuredQuery_FieldFilter_EQUAL |
| 365 |
case "in": |
| 366 |
fop = pb.StructuredQuery_FieldFilter_IN |
| 367 |
case "not-in": |
| 368 |
fop = pb.StructuredQuery_FieldFilter_NOT_IN |
| 369 |
// TODO(jba): can we support array-contains portably? |
| 370 |
// case "array-contains": |
| 371 |
// fop = pb.StructuredQuery_FieldFilter_ARRAY_CONTAINS |
| 372 |
default: |
| 373 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "invalid operator: %q", op) |
| 374 |
} |
| 375 |
return &pb.StructuredQuery_Filter{ |
| 376 |
FilterType: &pb.StructuredQuery_Filter_FieldFilter{ |
| 377 |
FieldFilter: &pb.StructuredQuery_FieldFilter{ |
| 378 |
Field: fieldRef(fp), |
| 379 |
Op: fop, |
| 380 |
Value: val, |
| 381 |
}, |
| 382 |
}, |
| 383 |
}, nil |
| 384 |
} |
| 385 |
|
| 386 |
func (c *collection) QueryPlan(q *driver.Query) (string, error) { |
| 387 |
return "unknown", nil |
| 388 |
} |