-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathquery.dart
More file actions
1194 lines (1079 loc) · 39.4 KB
/
query.dart
File metadata and controls
1194 lines (1079 loc) · 39.4 KB
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
part of '../firestore.dart';
@immutable
base class Query<T> {
const Query._({
required this.firestore,
required _QueryOptions<T> queryOptions,
}) : _queryOptions = queryOptions;
static List<Object?> _extractFieldValues(
DocumentSnapshot<Object?> documentSnapshot,
List<_FieldOrder> fieldOrders,
) {
return fieldOrders.map((fieldOrder) {
if (fieldOrder.fieldPath == FieldPath.documentId) {
return documentSnapshot.ref;
}
final fieldValue = documentSnapshot.get(fieldOrder.fieldPath);
if (fieldValue == null) {
throw StateError(
'Field "${fieldOrder.fieldPath}" is missing in the provided DocumentSnapshot. '
'Please provide a document that contains values for all specified orderBy() '
'and where() constraints.',
);
}
return fieldValue.value;
}).toList();
}
final Firestore firestore;
final _QueryOptions<T> _queryOptions;
/// Applies a custom data converter to this Query, allowing you to use your
/// own custom model objects with Firestore. When you call [get] on the
/// returned [Query], the provided converter will convert between Firestore
/// data and your custom type U.
///
/// Using the converter allows you to specify generic type arguments when
/// storing and retrieving objects from Firestore.
///
/// Passing `null` for both parameters removes the current converter and
/// returns an untyped `Query<DocumentData>`.
@mustBeOverridden
Query<U> withConverter<U>({
FromFirestore<U>? fromFirestore,
ToFirestore<U>? toFirestore,
}) {
// If null, use the default JSON converter
final converter = (fromFirestore == null || toFirestore == null)
? _jsonConverter as _FirestoreDataConverter<U>
: (fromFirestore: fromFirestore, toFirestore: toFirestore);
return Query<U>._(
firestore: firestore,
queryOptions: _queryOptions.withConverter(converter),
);
}
_QueryCursor _createCursor(
List<_FieldOrder> fieldOrders, {
List<Object?>? fieldValues,
DocumentSnapshot<Object?>? snapshot,
required bool before,
}) {
if (fieldValues != null && snapshot != null) {
throw ArgumentError(
'You cannot specify both "fieldValues" and "snapshot".',
);
}
final effectiveFieldValues = snapshot != null
? Query._extractFieldValues(snapshot, fieldOrders)
: fieldValues;
if (effectiveFieldValues == null) {
throw ArgumentError('You must specify "fieldValues" or "snapshot".');
}
if (effectiveFieldValues.length > fieldOrders.length) {
throw ArgumentError(
'Too many cursor values specified. The specified '
'values must match the orderBy() constraints of the query.',
);
}
final cursorValues = <firestore_v1.Value>[];
final cursor = _QueryCursor(before: before, values: cursorValues);
for (var i = 0; i < effectiveFieldValues.length; ++i) {
final fieldValue = effectiveFieldValues[i];
if (fieldOrders[i].fieldPath == FieldPath.documentId &&
fieldValue is! DocumentReference) {
throw ArgumentError(
'When ordering with FieldPath.documentId(), '
'the cursor must be a DocumentReference.',
);
}
_validateQueryValue('$i', fieldValue);
cursor.values.add(firestore._serializer.encodeValue(fieldValue)!);
}
return cursor;
}
(_QueryCursor, List<_FieldOrder>) _cursorFromValues({
List<Object?>? fieldValues,
DocumentSnapshot<Object?>? snapshot,
required bool before,
}) {
if (fieldValues != null && fieldValues.isEmpty) {
throw ArgumentError.value(
fieldValues,
'fieldValues',
'Value must not be an empty List.',
);
}
final fieldOrders = _createImplicitOrderBy(snapshot);
final cursor = _createCursor(
fieldOrders,
fieldValues: fieldValues,
snapshot: snapshot,
before: before,
);
return (cursor, fieldOrders);
}
/// Computes the backend ordering semantics for DocumentSnapshot cursors.
List<_FieldOrder> _createImplicitOrderBy(
DocumentSnapshot<Object?>? snapshot,
) {
// Add an implicit orderBy if the only cursor value is a DocumentSnapshot
// or a DocumentReference.
if (snapshot == null) return _queryOptions.fieldOrders;
final fieldOrders = _queryOptions.fieldOrders.toList();
// If no explicit ordering is specified, use the first inequality to
// define an implicit order.
if (fieldOrders.isEmpty) {
for (final filter in _queryOptions.filters) {
final fieldReference = filter.firstInequalityField;
if (fieldReference != null) {
fieldOrders.add(_FieldOrder(fieldPath: fieldReference));
break;
}
}
}
final hasDocumentId = fieldOrders.any(
(fieldOrder) => fieldOrder.fieldPath == FieldPath.documentId,
);
if (!hasDocumentId) {
// Add implicit sorting by name, using the last specified direction.
final lastDirection = fieldOrders.isEmpty
? _Direction.ascending
: fieldOrders.last.direction;
fieldOrders.add(
_FieldOrder(fieldPath: FieldPath.documentId, direction: lastDirection),
);
}
return fieldOrders;
}
/// Creates and returns a new [Query] that starts at the provided
/// set of field values relative to the order of the query. The order of the
/// provided values must match the order of the order by clauses of the query.
///
/// - [fieldValues] The field values to start this query at,
/// in order of the query's order by.
///
/// ```dart
/// final query = firestore.collection('col');
///
/// query.orderBy('foo').startAt(42).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> startAt(List<Object?> fieldValues) {
final (startAt, fieldOrders) = _cursorFromValues(
fieldValues: fieldValues,
before: true,
);
final options = _queryOptions.copyWith(
fieldOrders: fieldOrders,
startAt: startAt,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that starts at the provided
/// set of field values relative to the order of the query. The order of the
/// provided values must match the order of the order by clauses of the query.
///
/// - [documentSnapshot] The snapshot of the document the query results
/// should start at, in order of the query's order by.
Query<T> startAtDocument(DocumentSnapshot<Object?> documentSnapshot) {
final (startAt, fieldOrders) = _cursorFromValues(
snapshot: documentSnapshot,
before: true,
);
final options = _queryOptions.copyWith(
fieldOrders: fieldOrders,
startAt: startAt,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that starts after the
/// provided set of field values relative to the order of the query. The order
/// of the provided values must match the order of the order by clauses of the
/// query.
///
/// - [fieldValues]: The field values to
/// start this query after, in order of the query's order by.
///
/// ```dart
/// final query = firestore.collection('col');
///
/// query.orderBy('foo').startAfter(42).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> startAfter(List<Object?> fieldValues) {
final (startAt, fieldOrders) = _cursorFromValues(
fieldValues: fieldValues,
before: false,
);
final options = _queryOptions.copyWith(
fieldOrders: fieldOrders,
startAt: startAt,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that starts after the
/// provided set of field values relative to the order of the query. The order
/// of the provided values must match the order of the order by clauses of the
/// query.
///
/// - [snapshot]: The snapshot of the document the query results
/// should start at, in order of the query's order by.
Query<T> startAfterDocument(DocumentSnapshot<Object?> snapshot) {
final (startAt, fieldOrders) = _cursorFromValues(
snapshot: snapshot,
before: false,
);
final options = _queryOptions.copyWith(
fieldOrders: fieldOrders,
startAt: startAt,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that ends before the set of
/// field values relative to the order of the query. The order of the provided
/// values must match the order of the order by clauses of the query.
///
/// - [fieldValues]: The field values to
/// end this query before, in order of the query's order by.
///
/// ```dart
/// final query = firestore.collection('col');
///
/// query.orderBy('foo').endBefore(42).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> endBefore(List<Object?> fieldValues) {
final (endAt, fieldOrders) = _cursorFromValues(
fieldValues: fieldValues,
before: true,
);
final options = _queryOptions.copyWith(
fieldOrders: fieldOrders,
endAt: endAt,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that ends before the set of
/// field values relative to the order of the query. The order of the provided
/// values must match the order of the order by clauses of the query.
///
/// - [snapshot]: The snapshot
/// of the document the query results should end before.
Query<T> endBeforeDocument(DocumentSnapshot<Object?> snapshot) {
final (endAt, fieldOrders) = _cursorFromValues(
snapshot: snapshot,
before: true,
);
final options = _queryOptions.copyWith(
fieldOrders: fieldOrders,
endAt: endAt,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that ends at the provided
/// set of field values relative to the order of the query. The order of the
/// provided values must match the order of the order by clauses of the query.
///
/// - [fieldValues]: The field values to end
/// this query at, in order of the query's order by.
///
/// ```dart
/// final query = firestore.collection('col');
///
/// query.orderBy('foo').endAt(42).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> endAt(List<Object?> fieldValues) {
final (endAt, fieldOrders) = _cursorFromValues(
fieldValues: fieldValues,
before: false,
);
final options = _queryOptions.copyWith(
fieldOrders: fieldOrders,
endAt: endAt,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that ends at the provided
/// set of field values relative to the order of the query. The order of the
/// provided values must match the order of the order by clauses of the query.
///
/// - [snapshot]: The snapshot
/// of the document the query results should end at, in order of the query's order by.
/// ```
Query<T> endAtDocument(DocumentSnapshot<Object?> snapshot) {
final (endAt, fieldOrders) = _cursorFromValues(
snapshot: snapshot,
before: false,
);
final options = _queryOptions.copyWith(
fieldOrders: fieldOrders,
endAt: endAt,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Executes the query and returns the results as a [QuerySnapshot].
///
/// ```dart
/// final query = firestore.collection('col').where('foo', WhereFilter.equal, 'bar');
///
/// query.get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Future<QuerySnapshot<T>> get() => _get(transactionId: null);
/// Plans and optionally executes this query, returning an [ExplainResults]
/// object which contains information about the planning, and optionally
/// the execution statistics and results.
///
/// ```dart
/// final query = firestore.collection('col').where('foo', WhereFilter.equal, 'bar');
///
/// // Get query plan without executing
/// final explainResults = await query.explain();
/// print('Indexes used: ${explainResults.metrics.planSummary.indexesUsed}');
///
/// // Get query plan and execute
/// final explainResultsWithData = await query.explain(ExplainOptions(analyze: true));
/// print('Results: ${explainResultsWithData.snapshot?.docs.length}');
/// print('Read operations: ${explainResultsWithData.metrics.executionStats?.readOperations}');
/// ```
Future<ExplainResults<QuerySnapshot<T>?>> explain([
ExplainOptions? options,
]) async {
final response = await firestore._firestoreClient.v1((
api,
projectId,
) async {
final request = _toProto(transactionId: null, readTime: null);
request.explainOptions =
options?.toProto() ?? firestore_v1.ExplainOptions();
return api.projects.databases.documents.runQuery(
request,
_buildProtoParentPath(),
);
});
ExplainMetrics? metrics;
QuerySnapshot<T>? snapshot;
Timestamp? readTime;
final docs = <QueryDocumentSnapshot<T>>[];
for (final element in response) {
// Extract explain metrics if present
if (element.explainMetrics != null) {
metrics = ExplainMetrics._fromProto(element.explainMetrics!);
}
// Extract document if present (when analyze: true)
final document = element.document;
if (document != null) {
final docSnapshot = DocumentSnapshot._fromDocument(
document,
element.readTime,
firestore,
);
final finalDoc =
_DocumentSnapshotBuilder(
docSnapshot.ref.withConverter<T>(
fromFirestore: _queryOptions.converter.fromFirestore,
toFirestore: _queryOptions.converter.toFirestore,
),
)
..fieldsProto = firestore_v1.MapValue(fields: document.fields)
..readTime = docSnapshot.readTime
..createTime = docSnapshot.createTime
..updateTime = docSnapshot.updateTime;
docs.add(finalDoc.build() as QueryDocumentSnapshot<T>);
}
if (element.readTime != null) {
readTime = Timestamp._fromString(element.readTime!);
}
}
// Create snapshot only if we have documents (analyze: true)
if (docs.isNotEmpty || ((options?.analyze ?? false) && readTime != null)) {
snapshot = QuerySnapshot<T>._(
query: this,
readTime: readTime,
docs: docs,
);
}
if (metrics == null) {
throw StateError('No explain metrics returned from query');
}
return ExplainResults._create(metrics: metrics, snapshot: snapshot);
}
Future<QuerySnapshot<T>> _get({required String? transactionId}) async {
final response = await firestore._firestoreClient.v1((
api,
projectId,
) async {
return api.projects.databases.documents.runQuery(
_toProto(transactionId: transactionId, readTime: null),
_buildProtoParentPath(),
);
});
Timestamp? readTime;
final snapshots = response
.map((e) {
final document = e.document;
if (document == null) {
readTime = e.readTime.let(Timestamp._fromString);
return null;
}
final snapshot = DocumentSnapshot._fromDocument(
document,
e.readTime,
firestore,
);
final finalDoc =
_DocumentSnapshotBuilder(
snapshot.ref.withConverter<T>(
fromFirestore: _queryOptions.converter.fromFirestore,
toFirestore: _queryOptions.converter.toFirestore,
),
)
// Recreate the QueryDocumentSnapshot with the DocumentReference
// containing the original converter.
..fieldsProto = firestore_v1.MapValue(fields: document.fields)
..readTime = snapshot.readTime
..createTime = snapshot.createTime
..updateTime = snapshot.updateTime;
return finalDoc.build();
})
.nonNulls
// Specifying fieldsProto should cause the builder to create a query snapshot.
.cast<QueryDocumentSnapshot<T>>()
.toList();
return QuerySnapshot<T>._(query: this, readTime: readTime, docs: snapshots);
}
String _buildProtoParentPath() {
return _queryOptions.parentPath
._toQualifiedResourcePath(firestore.projectId, firestore.databaseId)
._formattedName;
}
firestore_v1.RunQueryRequest _toProto({
required String? transactionId,
required Timestamp? readTime,
firestore_v1.TransactionOptions? transactionOptions,
}) {
// Validate mutual exclusivity of transaction parameters
final providedParams = [
transactionId,
readTime,
transactionOptions,
].nonNulls.length;
if (providedParams > 1) {
throw ArgumentError(
'Only one of transactionId, readTime, or transactionOptions can be specified. '
'Got: transactionId=$transactionId, readTime=$readTime, transactionOptions=$transactionOptions',
);
}
final structuredQuery = _toStructuredQuery();
// For limitToLast queries, the structured query has to be translated to a version with
// reversed ordered, and flipped startAt/endAt to work properly.
if (_queryOptions.limitType == LimitType.last) {
if (!_queryOptions.hasFieldOrders) {
throw ArgumentError(
'limitToLast() queries require specifying at least one orderBy() clause.',
);
}
structuredQuery.orderBy = _queryOptions.fieldOrders.map((order) {
// Flip the orderBy directions since we want the last results
final dir = order.direction == _Direction.descending
? _Direction.ascending
: _Direction.descending;
return _FieldOrder(
fieldPath: order.fieldPath,
direction: dir,
)._toProto();
}).toList();
// Swap the cursors to match the now-flipped query ordering.
structuredQuery.startAt = _queryOptions.endAt != null
? _toCursor(
_QueryCursor(
values: _queryOptions.endAt!.values,
before: !_queryOptions.endAt!.before,
),
)
: null;
structuredQuery.endAt = _queryOptions.startAt != null
? _toCursor(
_QueryCursor(
values: _queryOptions.startAt!.values,
before: !_queryOptions.startAt!.before,
),
)
: null;
}
final runQueryRequest = firestore_v1.RunQueryRequest(
structuredQuery: structuredQuery,
);
if (transactionId != null) {
runQueryRequest.transaction = transactionId;
} else if (readTime != null) {
runQueryRequest.readTime = readTime._toProto().timestampValue;
} else if (transactionOptions != null) {
runQueryRequest.newTransaction = transactionOptions;
}
return runQueryRequest;
}
firestore_v1.StructuredQuery _toStructuredQuery() {
final structuredQuery = firestore_v1.StructuredQuery(
from: [firestore_v1.CollectionSelector()],
);
if (_queryOptions.allDescendants) {
structuredQuery.from![0].allDescendants = true;
}
// Kindless queries select all descendant documents, so we remove the
// collectionId field.
if (!_queryOptions.kindless) {
structuredQuery.from![0].collectionId = _queryOptions.collectionId;
}
if (_queryOptions.filters.isNotEmpty) {
structuredQuery.where = _CompositeFilterInternal(
filters: _queryOptions.filters,
op: _CompositeOperator.and,
).toProto();
}
if (_queryOptions.hasFieldOrders) {
structuredQuery.orderBy = _queryOptions.fieldOrders
.map((o) => o._toProto())
.toList();
}
structuredQuery.startAt = _toCursor(_queryOptions.startAt);
structuredQuery.endAt = _toCursor(_queryOptions.endAt);
final limit = _queryOptions.limit;
if (limit != null) structuredQuery.limit = limit;
structuredQuery.offset = _queryOptions.offset;
structuredQuery.select = _queryOptions.projection;
return structuredQuery;
}
/// Converts a QueryCursor to its proto representation.
firestore_v1.Cursor? _toCursor(_QueryCursor? cursor) {
if (cursor == null) return null;
return cursor.before
? firestore_v1.Cursor(before: true, values: cursor.values)
: firestore_v1.Cursor(values: cursor.values);
}
// TODO onSnapshot
// TODO stream
/// {@macro collection_reference.where}
Query<T> where(Object path, WhereFilter op, Object? value) {
final fieldPath = FieldPath.from(path);
return whereFieldPath(fieldPath, op, value);
}
/// {@template collection_reference.where}
/// Creates and returns a new [Query] with the additional filter
/// that documents must contain the specified field and that its value should
/// satisfy the relation constraint provided.
///
/// This function returns a new (immutable) instance of the Query (rather than
/// modify the existing instance) to impose the filter.
///
/// - [fieldPath]: The name of a property value to compare.
/// - [op]: A comparison operation in the form of a string.
/// Acceptable operator strings are "<", "<=", "==", "!=", ">=", ">", "array-contains",
/// "in", "not-in", and "array-contains-any".
/// - [value]: The value to which to compare the field for inclusion in
/// a query.
///
/// ```dart
/// final collectionRef = firestore.collection('col');
///
/// collectionRef.where('foo', WhereFilter.equal, 'bar').get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
/// {@endtemplate}
Query<T> whereFieldPath(FieldPath fieldPath, WhereFilter op, Object? value) {
return whereFilter(Filter.where(fieldPath, op, value));
}
/// Creates and returns a new [Query] with the additional filter
/// that documents should satisfy the relation constraint(s) provided.
///
/// This function returns a new (immutable) instance of the Query (rather than
/// modify the existing instance) to impose the filter.
///
/// - [filter] A unary or composite filter to apply to the Query.
///
/// ```dart
/// final collectionRef = firestore.collection('col');
///
/// collectionRef.where(Filter.and(Filter.where('foo', WhereFilter.equal, 'bar'), Filter.where('foo', WhereFilter.notEqual, 'baz'))).get()
/// .then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> whereFilter(Filter filter) {
if (_queryOptions.startAt != null || _queryOptions.endAt != null) {
throw ArgumentError(
'Cannot specify a where() filter after calling '
'startAt(), startAfter(), endBefore() or endAt().',
);
}
final parsedFilter = _parseFilter(filter);
if (parsedFilter.filters.isEmpty) {
// Return the existing query if not adding any more filters (e.g. an empty composite filter).
return this;
}
final options = _queryOptions.copyWith(
filters: [..._queryOptions.filters, parsedFilter],
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
_FilterInternal _parseFilter(Filter filter) {
switch (filter) {
case _UnaryFilter():
return _parseFieldFilter(filter);
case _CompositeFilter():
return _parseCompositeFilter(filter);
}
}
_FieldFilterInternal _parseFieldFilter(_UnaryFilter fieldFilterData) {
final value = fieldFilterData.value;
final operator = fieldFilterData.op;
final fieldPath = fieldFilterData.fieldPath;
_validateQueryValue('value', value);
if (fieldPath == FieldPath.documentId) {
switch (operator) {
case WhereFilter.arrayContains:
case WhereFilter.arrayContainsAny:
throw ArgumentError.value(
operator,
'op',
"Invalid query. You can't perform '$operator' queries on FieldPath.documentId().",
);
case WhereFilter.isIn:
case WhereFilter.notIn:
if (value is! List || value.isEmpty) {
throw ArgumentError.value(
value,
'value',
"Invalid query. A non-empty array is required for '$operator' filters.",
);
}
for (final item in value) {
if (item is! DocumentReference) {
throw ArgumentError.value(
value,
'value',
"Invalid query. When querying with '$operator', "
'you must provide a List of non-empty DocumentReference instances as the argument.',
);
}
}
default:
if (value is! DocumentReference) {
throw ArgumentError.value(
value,
'value',
'Invalid query. When querying by document ID you must provide a '
'DocumentReference instance.',
);
}
}
}
return _FieldFilterInternal(
serializer: firestore._serializer,
field: fieldPath,
op: operator,
value: value,
);
}
_FilterInternal _parseCompositeFilter(_CompositeFilter compositeFilterData) {
final parsedFilters = compositeFilterData.filters
.map(_parseFilter)
.where((filter) => filter.filters.isNotEmpty)
.toList();
// For composite filters containing 1 filter, return the only filter.
// For example: AND(FieldFilter1) == FieldFilter1
if (parsedFilters.length == 1) {
return parsedFilters.single;
}
return _CompositeFilterInternal(
filters: parsedFilters,
op: compositeFilterData.operator == _CompositeOperator.and
? _CompositeOperator.and
: _CompositeOperator.or,
);
}
/// Creates and returns a new [Query] instance that applies a
/// field mask to the result and returns only the specified subset of fields.
/// You can specify a list of field paths to return, or use an empty list to
/// only return the references of matching documents.
///
/// Queries that contain field masks cannot be listened to via `onSnapshot()`
/// listeners.
///
/// This function returns a new (immutable) instance of the Query (rather than
/// modify the existing instance) to impose the field mask.
///
/// - [fieldPaths] The field paths to return.
///
/// ```dart
/// final collectionRef = firestore.collection('col');
/// final documentRef = collectionRef.doc('doc');
///
/// return documentRef.set({x:10, y:5}).then(() {
/// return collectionRef.where('x', '>', 5).select('y').get();
/// }).then((res) {
/// print('y is ${res.docs[0].get('y')}.');
/// });
/// ```
Query<DocumentData> select([List<FieldPath> fieldPaths = const []]) {
final fields = <firestore_v1.FieldReference>[
if (fieldPaths.isEmpty)
firestore_v1.FieldReference(
fieldPath: FieldPath.documentId._formattedName,
)
else
for (final fieldPath in fieldPaths)
firestore_v1.FieldReference(fieldPath: fieldPath._formattedName),
];
return Query<DocumentData>._(
firestore: firestore,
queryOptions: _queryOptions
.copyWith(projection: firestore_v1.Projection(fields: fields))
.withConverter(
// By specifying a field mask, the query result no longer conforms to type
// `T`. We there return `Query<DocumentData>`.
_jsonConverter,
),
);
}
/// Creates and returns a new [Query] that's additionally sorted
/// by the specified field, optionally in descending order instead of
/// ascending.
///
/// This function returns a new (immutable) instance of the Query (rather than
/// modify the existing instance) to impose the field mask.
///
/// - [fieldPath]: The field to sort by.
/// - [descending] (false by default) Whether to obtain documents in descending order.
///
/// ```dart
/// final query = firestore.collection('col').where('foo', WhereFilter.equal, 42);
///
/// query.orderBy('foo', descending: true).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> orderByFieldPath(FieldPath fieldPath, {bool descending = false}) {
if (_queryOptions.startAt != null || _queryOptions.endAt != null) {
throw ArgumentError(
'Cannot specify an orderBy() constraint after calling '
'startAt(), startAfter(), endBefore() or endAt().',
);
}
final newOrder = _FieldOrder(
fieldPath: fieldPath,
direction: descending ? _Direction.descending : _Direction.ascending,
);
final options = _queryOptions.copyWith(
fieldOrders: [..._queryOptions.fieldOrders, newOrder],
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that's additionally sorted
/// by the specified field, optionally in descending order instead of
/// ascending.
///
/// This function returns a new (immutable) instance of the Query (rather than
/// modify the existing instance) to impose the field mask.
///
/// - [path]: The field to sort by.
/// - [descending] (false by default) Whether to obtain documents in descending order.
///
/// ```dart
/// final query = firestore.collection('col').where('foo', WhereFilter.equal, 42);
///
/// query.orderBy('foo', descending: true).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> orderBy(Object path, {bool descending = false}) {
return orderByFieldPath(FieldPath.from(path), descending: descending);
}
/// Creates and returns a new [Query] that only returns the first matching documents.
///
/// This function returns a new (immutable) instance of the Query (rather than
/// modify the existing instance) to impose the limit.
///
/// - [limit] The maximum number of items to return.
///
/// ```dart
/// final query = firestore.collection('col').where('foo', WhereFilter.equal, 42);
///
/// query.limit(1).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> limit(int limit) {
final options = _queryOptions.copyWith(
limit: limit,
limitType: LimitType.first,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Creates and returns a new [Query] that only returns the last matching
/// documents.
///
/// You must specify at least one [orderBy] clause for limitToLast queries,
/// otherwise an exception will be thrown during execution.
///
/// Results for limitToLast queries cannot be streamed.
///
/// ```dart
/// final query = firestore.collection('col').where('foo', '>', 42);
///
/// query.limitToLast(1).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Last matching document is ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> limitToLast(int limit) {
final options = _queryOptions.copyWith(
limit: limit,
limitType: LimitType.last,
);
return Query<T>._(firestore: firestore, queryOptions: options);
}
/// Specifies the offset of the returned results.
///
/// This function returns a new (immutable) instance of the [Query]
/// (rather than modify the existing instance) to impose the offset.
///
/// - [offset] The offset to apply to the Query results
///
/// ```dart
/// final query = firestore.collection('col').where('foo', WhereFilter.equal, 42);
///
/// query.limit(10).offset(20).get().then((querySnapshot) {
/// querySnapshot.forEach((documentSnapshot) {
/// print('Found document at ${documentSnapshot.ref.path}');
/// });
/// });
/// ```
Query<T> offset(int offset) {
final options = _queryOptions.copyWith(offset: offset);
return Query<T>._(firestore: firestore, queryOptions: options);
}
@mustBeOverridden
@override
bool operator ==(Object other) {
return other is Query<T> &&
runtimeType == other.runtimeType &&
_queryOptions == other._queryOptions;
}
@override
int get hashCode => Object.hash(runtimeType, _queryOptions);
/// Returns an [AggregateQuery] that can be used to execute one or more
/// aggregation queries over the result set of this query.
///
/// ## Limitations
/// - Aggregation queries are only supported through direct server response
/// - Cannot be used with real-time listeners or offline queries
/// - Must complete within 60 seconds or returns DEADLINE_EXCEEDED error