-
Notifications
You must be signed in to change notification settings - Fork 65
/
query.py
2376 lines (1973 loc) · 83.1 KB
/
query.py
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
# Copyright 2018 Google LLC
#
# 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
#
# https://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.
"""High-level wrapper for datastore queries.
The fundamental API here overloads the 6 comparison operators to represent
filters on property values, and supports AND and OR operations (implemented as
functions -- Python's 'and' and 'or' operators cannot be overloaded, and the
'&' and '|' operators have a priority that conflicts with the priority of
comparison operators).
For example::
class Employee(Model):
name = StringProperty()
age = IntegerProperty()
rank = IntegerProperty()
@classmethod
def demographic(cls, min_age, max_age):
return cls.query().filter(AND(cls.age >= min_age,
cls.age <= max_age))
@classmethod
def ranked(cls, rank):
return cls.query(cls.rank == rank).order(cls.age)
for emp in Employee.seniors(42, 5):
print(emp.name, emp.age, emp.rank)
The 'in' operator cannot be overloaded, but is supported through the IN()
method. For example::
Employee.query().filter(Employee.rank.IN([4, 5, 6]))
Sort orders are supported through the order() method; unary minus is
overloaded on the Property class to represent a descending order::
Employee.query().order(Employee.name, -Employee.age)
Besides using AND() and OR(), filters can also be combined by repeatedly
calling .filter()::
query1 = Employee.query() # A query that returns all employees
query2 = query1.filter(Employee.age >= 30) # Only those over 30
query3 = query2.filter(Employee.age < 40) # Only those in their 30s
A further shortcut is calling .filter() with multiple arguments; this implies
AND()::
query1 = Employee.query() # A query that returns all employees
query3 = query1.filter(Employee.age >= 30,
Employee.age < 40) # Only those in their 30s
And finally you can also pass one or more filter expressions directly to the
.query() method::
query3 = Employee.query(Employee.age >= 30,
Employee.age < 40) # Only those in their 30s
Query objects are immutable, so these methods always return a new Query object;
the above calls to filter() do not affect query1. On the other hand, operations
that are effectively no-ops may return the original Query object.
Sort orders can also be combined this way, and .filter() and .order() calls may
be intermixed::
query4 = query3.order(-Employee.age)
query5 = query4.order(Employee.name)
query6 = query5.filter(Employee.rank == 5)
Again, multiple .order() calls can be combined::
query5 = query3.order(-Employee.age, Employee.name)
The simplest way to retrieve Query results is a for-loop::
for emp in query3:
print emp.name, emp.age
Some other methods to run a query and access its results::
:meth:`Query.iter`() # Return an iterator; same as iter(q) but more
flexible.
:meth:`Query.fetch`(N) # Return a list of the first N results
:meth:`Query.get`() # Return the first result
:meth:`Query.count`(N) # Return the number of results, with a maximum of N
:meth:`Query.fetch_page`(N, start_cursor=cursor) # Return (results, cursor,
has_more)
All of the above methods take a standard set of additional query options,
in the form of keyword arguments such as keys_only=True. You can also pass
a QueryOptions object options=QueryOptions(...), but this is deprecated.
The most important query options are:
- keys_only: bool, if set the results are keys instead of entities.
- limit: int, limits the number of results returned.
- offset: int, skips this many results first.
- start_cursor: Cursor, start returning results after this position.
- end_cursor: Cursor, stop returning results after this position.
The following query options have been deprecated or are not supported in
datastore queries:
- batch_size: int, hint for the number of results returned per RPC.
- prefetch_size: int, hint for the number of results in the first RPC.
- produce_cursors: bool, return Cursor objects with the results.
All of the above methods except for iter() have asynchronous variants as well,
which return a Future; to get the operation's ultimate result, yield the Future
(when inside a tasklet) or call the Future's get_result() method (outside a
tasklet)::
:meth:`Query.fetch_async`(N)
:meth:`Query.get_async`()
:meth:`Query.count_async`(N)
:meth:`Query.fetch_page_async`(N, start_cursor=cursor)
Finally, there's an idiom to efficiently loop over the Query results in a
tasklet, properly yielding when appropriate::
it = query1.iter()
while (yield it.has_next_async()):
emp = it.next()
print(emp.name, emp.age)
"""
import functools
import logging
import six
from google.cloud.ndb import context as context_module
from google.cloud.ndb import exceptions
from google.cloud.ndb import _options
from google.cloud.ndb import tasklets
from google.cloud.ndb import utils
__all__ = [
"QueryOptions",
"PropertyOrder",
"RepeatedStructuredPropertyPredicate",
"ParameterizedThing",
"Parameter",
"ParameterizedFunction",
"Node",
"FalseNode",
"ParameterNode",
"FilterNode",
"PostFilterNode",
"ConjunctionNode",
"DisjunctionNode",
"AND",
"OR",
"Query",
"gql",
]
_EQ_OP = "="
_NE_OP = "!="
_IN_OP = "in"
_LT_OP = "<"
_GT_OP = ">"
_OPS = frozenset([_EQ_OP, _NE_OP, _LT_OP, "<=", _GT_OP, ">=", _IN_OP])
_log = logging.getLogger(__name__)
class PropertyOrder(object):
"""The sort order for a property name, to be used when ordering the
results of a query.
Args:
name (str): The name of the model property to use for ordering.
reverse (bool): Whether to reverse the sort order (descending)
or not (ascending). Default is False.
"""
def __init__(self, name, reverse=False):
self.name = name
self.reverse = reverse
def __repr__(self):
return "PropertyOrder(name='{}', reverse={})".format(self.name, self.reverse)
def __neg__(self):
reverse = not self.reverse
return self.__class__(name=self.name, reverse=reverse)
class RepeatedStructuredPropertyPredicate(object):
"""A predicate for querying repeated structured properties.
Called by ``model.StructuredProperty._compare``. This is used to handle
queries of the form::
Squad.query(Squad.members == Member(name="Joe", age=24, rank=5))
This query should find any squad with a member named "Joe" whose age is 24
and rank is 5.
Datastore, on its own, can find all squads with a team member named Joe, or
a team member whose age is 24, or whose rank is 5, but it can't be queried
for all 3 in a single subentity. This predicate must be applied client
side, therefore, to limit results to entities where all the keys match for
a single subentity.
Arguments:
name (str): Name of the repeated structured property being queried
(e.g. "members").
match_keys (list[str]): Property names to check on the subentities
being queried (e.g. ["name", "age", "rank"]).
entity_pb (google.cloud.datastore_v1.proto.entity_pb2.Entity): A
partial entity protocol buffer containing the values that must
match in a subentity of the repeated structured property. Should
contain a value for each key in ``match_keys``.
"""
def __init__(self, name, match_keys, entity_pb):
self.name = name
self.match_keys = match_keys
self.match_values = [entity_pb.properties[key] for key in match_keys]
def __call__(self, entity_pb):
prop_pb = entity_pb.properties.get(self.name)
if prop_pb:
subentities = prop_pb.array_value.values
for subentity in subentities:
properties = subentity.entity_value.properties
values = [properties.get(key) for key in self.match_keys]
if values == self.match_values:
return True
else:
# Backwards compatibility. Legacy NDB, rather than using
# Datastore's ability to embed subentities natively, used dotted
# property names.
prefix = self.name + "."
subentities = ()
for prop_name, prop_pb in entity_pb.properties.items():
if not prop_name.startswith(prefix):
continue
subprop_name = prop_name.split(".", 1)[1]
if not subentities:
subentities = [
{subprop_name: value} for value in prop_pb.array_value.values
]
else:
for subentity, value in zip(
subentities, prop_pb.array_value.values
):
subentity[subprop_name] = value
for subentity in subentities:
values = [subentity.get(key) for key in self.match_keys]
if values == self.match_values:
return True
return False
class ParameterizedThing(object):
"""Base class for :class:`Parameter` and :class:`ParameterizedFunction`.
This exists purely for :func:`isinstance` checks.
"""
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
eq = self.__eq__(other)
if eq is not NotImplemented:
eq = not eq
return eq
class Parameter(ParameterizedThing):
"""Represents a bound variable in a GQL query.
``Parameter(1)`` corresponds to a slot labeled ``:1`` in a GQL query.
``Parameter('something')`` corresponds to a slot labeled ``:something``.
The value must be set (bound) separately.
Args:
key (Union[str, int]): The parameter key.
Raises:
TypeError: If the ``key`` is not a string or integer.
"""
def __init__(self, key):
if not isinstance(key, six.integer_types + six.string_types):
raise TypeError(
"Parameter key must be an integer or string, not {}".format(key)
)
self._key = key
def __repr__(self):
return "{}({!r})".format(type(self).__name__, self._key)
def __eq__(self, other):
if not isinstance(other, Parameter):
return NotImplemented
return self._key == other._key
@property
def key(self):
"""Retrieve the key."""
return self._key
def resolve(self, bindings, used):
"""Resolve the current parameter from the parameter bindings.
Args:
bindings (dict): A mapping of parameter bindings.
used (Dict[Union[str, int], bool]): A mapping of already used
parameters. This will be modified if the current parameter
is in ``bindings``.
Returns:
Any: The bound value for the current parameter.
Raises:
.BadArgumentError: If the current parameter is not in ``bindings``.
"""
key = self._key
if key not in bindings:
raise exceptions.BadArgumentError("Parameter :{} is not bound.".format(key))
value = bindings[key]
used[key] = True
return value
class ParameterizedFunction(ParameterizedThing):
"""Represents a GQL function with parameterized arguments.
For example, ParameterizedFunction('key', [Parameter(1)]) stands for
the GQL syntax KEY(:1).
"""
def __init__(self, func, values):
self.func = func
self.values = values
from google.cloud.ndb import _gql # avoid circular import
_func = _gql.FUNCTIONS.get(func)
if _func is None:
raise ValueError("Unknown GQL function: {}".format(func))
self._func = _func
def __repr__(self):
return "ParameterizedFunction(%r, %r)" % (self.func, self.values)
def __eq__(self, other):
if not isinstance(other, ParameterizedFunction):
return NotImplemented
return self.func == other.func and self.values == other.values
def is_parameterized(self):
for value in self.values:
if isinstance(value, Parameter):
return True
return False
def resolve(self, bindings, used):
values = []
for value in self.values:
if isinstance(value, Parameter):
value = value.resolve(bindings, used)
values.append(value)
return self._func(values)
class Node(object):
"""Base class for filter expression tree nodes.
Tree nodes are considered immutable, even though they can contain
Parameter instances, which are not. In particular, two identical
trees may be represented by the same Node object in different
contexts.
Raises:
TypeError: Always, only subclasses are allowed.
"""
_multiquery = False
def __new__(cls):
if cls is Node:
raise TypeError("Cannot instantiate Node, only a subclass.")
return super(Node, cls).__new__(cls)
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
# Python 2.7 requires this method to be implemented.
eq = self.__eq__(other)
if eq is not NotImplemented:
eq = not eq
return eq
def __le__(self, unused_other):
raise TypeError("Nodes cannot be ordered")
def __lt__(self, unused_other):
raise TypeError("Nodes cannot be ordered")
def __ge__(self, unused_other):
raise TypeError("Nodes cannot be ordered")
def __gt__(self, unused_other):
raise TypeError("Nodes cannot be ordered")
def _to_filter(self, post=False):
"""Helper to convert to low-level filter.
Raises:
NotImplementedError: Always. This method is virtual.
"""
raise NotImplementedError
def _post_filters(self):
"""Helper to extract post-filter nodes, if any.
Returns:
None: Always. Because this is the base implementation.
"""
return None
def resolve(self, bindings, used):
"""Return a node with parameters replaced by the selected values.
.. note::
Both ``bindings`` and ``used`` are unused by this base class
implementation.
Args:
bindings (dict): A mapping of parameter bindings.
used (Dict[Union[str, int], bool]): A mapping of already used
parameters. This will be modified if the current parameter
is in ``bindings``.
Returns:
Node: The current node.
"""
return self
class FalseNode(Node):
"""Tree node for an always-failing filter."""
def __eq__(self, other):
"""Equality check.
An instance will always equal another :class:`FalseNode` instance. This
is because they hold no state.
"""
if not isinstance(other, FalseNode):
return NotImplemented
return True
def _to_filter(self, post=False):
"""(Attempt to) convert to a low-level filter instance.
Args:
post (bool): Indicates if this is a post-filter node.
Raises:
.BadQueryError: If ``post`` is :data:`False`, because there's no
point submitting a query that will never return anything.
"""
if post:
return None
raise exceptions.BadQueryError("Cannot convert FalseNode to predicate")
class ParameterNode(Node):
"""Tree node for a parameterized filter.
Args:
prop (~google.cloud.ndb.model.Property): A property describing a value
type.
op (str): The comparison operator. One of ``=``, ``!=``, ``<``, ``<=``,
``>``, ``>=`` or ``in``.
param (ParameterizedThing): The parameter corresponding to the node.
Raises:
TypeError: If ``prop`` is not a
:class:`~google.cloud.ndb.model.Property`.
TypeError: If ``op`` is not one of the accepted operators.
TypeError: If ``param`` is not a :class:`.Parameter` or
:class:`.ParameterizedFunction`.
"""
def __new__(cls, prop, op, param):
# Avoid circular import in Python 2.7
from google.cloud.ndb import model
if not isinstance(prop, model.Property):
raise TypeError("Expected a Property, got {!r}".format(prop))
if op not in _OPS:
raise TypeError("Expected a valid operator, got {!r}".format(op))
if not isinstance(param, ParameterizedThing):
raise TypeError("Expected a ParameterizedThing, got {!r}".format(param))
obj = super(ParameterNode, cls).__new__(cls)
obj._prop = prop
obj._op = op
obj._param = param
return obj
def __getnewargs__(self):
"""Private API used to specify ``__new__`` arguments when unpickling.
.. note::
This method only applies if the ``pickle`` protocol is 2 or
greater.
Returns:
Tuple[~google.cloud.ndb.model.Property, str, ParameterizedThing]:
A tuple containing the internal state: the property, operation and
parameter.
"""
return self._prop, self._op, self._param
def __repr__(self):
return "ParameterNode({!r}, {!r}, {!r})".format(
self._prop, self._op, self._param
)
def __eq__(self, other):
if not isinstance(other, ParameterNode):
return NotImplemented
return (
self._prop._name == other._prop._name
and self._op == other._op
and self._param == other._param
)
def _to_filter(self, post=False):
"""Helper to convert to low-level filter.
Args:
post (bool): Indicates if this is a post-filter node.
Raises:
.BadArgumentError: Always. This is because this node represents
a parameter, i.e. no value exists to be filtered on.
"""
raise exceptions.BadArgumentError(
"Parameter :{} is not bound.".format(self._param.key)
)
def resolve(self, bindings, used):
"""Return a node with parameters replaced by the selected values.
Args:
bindings (dict): A mapping of parameter bindings.
used (Dict[Union[str, int], bool]): A mapping of already used
parameters.
Returns:
Union[~google.cloud.ndb.query.DisjunctionNode, \
~google.cloud.ndb.query.FilterNode, \
~google.cloud.ndb.query.FalseNode]: A node corresponding to
the value substituted.
"""
value = self._param.resolve(bindings, used)
if self._op == _IN_OP:
return self._prop._IN(value)
else:
return self._prop._comparison(self._op, value)
class FilterNode(Node):
"""Tree node for a single filter expression.
For example ``FilterNode("a", ">", 3)`` filters for entities where the
value ``a`` is greater than ``3``.
.. warning::
The constructor for this type may not always return a
:class:`FilterNode`. For example:
* The filter ``name in (value1, ..., valueN)`` is converted into
``(name = value1) OR ... OR (name = valueN)`` (also a
:class:`DisjunctionNode`)
* The filter ``name in ()`` (i.e. a property is among an empty list
of values) is converted into a :class:`FalseNode`
* The filter ``name in (value1,)`` (i.e. a list with one element) is
converted into ``name = value1``, a related :class:`FilterNode`
with a different ``opsymbol`` and ``value`` than what was passed
to the constructor
Args:
name (str): The name of the property being filtered.
opsymbol (str): The comparison operator. One of ``=``, ``!=``, ``<``,
``<=``, ``>``, ``>=`` or ``in``.
value (Any): The value to filter on / relative to.
Raises:
TypeError: If ``opsymbol`` is ``"in"`` but ``value`` is not a
basic container (:class:`list`, :class:`tuple`, :class:`set` or
:class:`frozenset`)
"""
_name = None
_opsymbol = None
_value = None
def __new__(cls, name, opsymbol, value):
# Avoid circular import in Python 2.7
from google.cloud.ndb import model
if isinstance(value, model.Key):
value = value._key
if opsymbol == _IN_OP:
if not isinstance(value, (list, tuple, set, frozenset)):
raise TypeError(
"in expected a list, tuple or set of values; "
"received {!r}".format(value)
)
nodes = [FilterNode(name, _EQ_OP, sub_value) for sub_value in value]
if not nodes:
return FalseNode()
if len(nodes) == 1:
return nodes[0]
return DisjunctionNode(*nodes)
instance = super(FilterNode, cls).__new__(cls)
instance._name = name
instance._opsymbol = opsymbol
instance._value = value
return instance
def __getnewargs__(self):
"""Private API used to specify ``__new__`` arguments when unpickling.
.. note::
This method only applies if the ``pickle`` protocol is 2 or
greater.
Returns:
Tuple[str, str, Any]: A tuple containing the
internal state: the name, ``opsymbol`` and value.
"""
return self._name, self._opsymbol, self._value
def __repr__(self):
return "{}({!r}, {!r}, {!r})".format(
type(self).__name__, self._name, self._opsymbol, self._value
)
def __eq__(self, other):
if not isinstance(other, FilterNode):
return NotImplemented
return (
self._name == other._name
and self._opsymbol == other._opsymbol
and self._value == other._value
)
def _to_filter(self, post=False):
"""Helper to convert to low-level filter.
Args:
post (bool): Indicates if this is a post-filter node.
Returns:
Optional[query_pb2.PropertyFilter]: Returns :data:`None`, if
this is a post-filter, otherwise returns the protocol buffer
representation of the filter.
Raises:
NotImplementedError: If the ``opsymbol`` is ``in``, since
they should correspond to a composite filter. This should
never occur since the constructor will create ``OR`` nodes for
``in``
"""
# Avoid circular import in Python 2.7
from google.cloud.ndb import _datastore_query
if post:
return None
if self._opsymbol in (_IN_OP):
raise NotImplementedError(
"Inequality filters are not single filter "
"expressions and therefore cannot be converted "
"to a single filter ({!r})".format(self._opsymbol)
)
return _datastore_query.make_filter(self._name, self._opsymbol, self._value)
class PostFilterNode(Node):
"""Tree node representing an in-memory filtering operation.
This is used to represent filters that cannot be executed by the
datastore, for example a query for a structured value.
Args:
predicate (Callable[[Any], bool]): A filter predicate that
takes a datastore entity (typically as a protobuf) and
returns :data:`True` or :data:`False` if the entity matches
the given filter.
"""
def __new__(cls, predicate):
instance = super(PostFilterNode, cls).__new__(cls)
instance.predicate = predicate
return instance
def __getnewargs__(self):
"""Private API used to specify ``__new__`` arguments when unpickling.
.. note::
This method only applies if the ``pickle`` protocol is 2 or
greater.
Returns:
Tuple[Callable[[Any], bool],]: A tuple containing a single value,
the ``predicate`` attached to this node.
"""
return (self.predicate,)
def __repr__(self):
return "{}({})".format(type(self).__name__, self.predicate)
def __eq__(self, other):
if not isinstance(other, PostFilterNode):
return NotImplemented
return self is other or self.predicate == other.predicate
def _to_filter(self, post=False):
"""Helper to convert to low-level filter.
Args:
post (bool): Indicates if this is a post-filter node.
Returns:
Tuple[Callable[[Any], bool], None]: If this is a post-filter, this
returns the stored ``predicate``, otherwise it returns
:data:`None`.
"""
if post:
return self.predicate
else:
return None
class _BooleanClauses(object):
"""This type will be used for symbolically performing boolean operations.
Internally, the state will track a symbolic expression like::
A or (B and C) or (A and D)
as a list of the ``OR`` components::
[A, B and C, A and D]
When ``combine_or=False``, it will track ``AND`` statements as a list,
making the final simplified form of our example::
[[A], [B, C], [A, D]]
Via :meth:`add_node`, we will ensure that new nodes will be correctly
combined (via ``AND`` or ``OR``) with the current expression.
Args:
name (str): The name of the class that is tracking a
boolean expression.
combine_or (bool): Indicates if new nodes will be combined
with the current boolean expression via ``AND`` or ``OR``.
"""
def __init__(self, name, combine_or):
self.name = name
self.combine_or = combine_or
if combine_or:
# For ``OR()`` the parts are just nodes.
self.or_parts = []
else:
# For ``AND()`` the parts are "segments", i.e. node lists.
self.or_parts = [[]]
def add_node(self, node):
"""Update the current boolean expression.
This uses the distributive law for sets to combine as follows:
- ``(A or B or C or ...) or D`` -> ``A or B or C or ... or D``
- ``(A or B or C or ...) and D`` ->
``(A and D) or (B and D) or (C and D) or ...``
Args:
node (Node): A node to add to the list of clauses.
Raises:
TypeError: If ``node`` is not a :class:`.Node`.
"""
if not isinstance(node, Node):
raise TypeError(
"{}() expects Node instances as arguments; "
"received a non-Node instance {!r}".format(self.name, node)
)
if self.combine_or:
if isinstance(node, DisjunctionNode):
# [S1 or ... or Sn] or [A1 or ... or Am]
# -> S1 or ... Sn or A1 or ... or Am
self.or_parts.extend(node._nodes)
else:
# [S1 or ... or Sn] or [A1]
# -> S1 or ... or Sn or A1
self.or_parts.append(node)
else:
if isinstance(node, DisjunctionNode):
# [S1 or ... or Sn] and [A1 or ... or Am]
# -> [S1 and A1] or ... or [Sn and A1] or
# ... or [Sn and Am] or ... or [Sn and Am]
new_segments = []
for segment in self.or_parts:
# ``segment`` represents ``Si``
for sub_node in node:
# ``sub_node`` represents ``Aj``
new_segment = segment + [sub_node]
new_segments.append(new_segment)
# Replace wholesale.
self.or_parts[:] = new_segments
elif isinstance(node, ConjunctionNode):
# [S1 or ... or Sn] and [A1 and ... and Am]
# -> [S1 and A1 and ... and Am] or ... or
# [Sn and A1 and ... and Am]
for segment in self.or_parts:
# ``segment`` represents ``Si``
segment.extend(node._nodes)
else:
# [S1 or ... or Sn] and [A1]
# -> [S1 and A1] or ... or [Sn and A1]
for segment in self.or_parts:
segment.append(node)
class ConjunctionNode(Node):
"""Tree node representing a boolean ``AND`` operator on multiple nodes.
.. warning::
The constructor for this type may not always return a
:class:`ConjunctionNode`. For example:
* If the passed in ``nodes`` has only one entry, that single node
will be returned by the constructor
* If the resulting boolean expression has an ``OR`` in it, then a
:class:`DisjunctionNode` will be returned; e.g.
``AND(OR(A, B), C)`` becomes ``OR(AND(A, C), AND(B, C))``
Args:
nodes (Tuple[Node, ...]): A list of nodes to be joined.
Raises:
TypeError: If ``nodes`` is empty.
RuntimeError: If the ``nodes`` combine to an "empty" boolean
expression.
"""
def __new__(cls, *nodes):
if not nodes:
raise TypeError("ConjunctionNode() requires at least one node.")
elif len(nodes) == 1:
return nodes[0]
clauses = _BooleanClauses("ConjunctionNode", combine_or=False)
for node in nodes:
clauses.add_node(node)
if not clauses.or_parts:
# NOTE: The original implementation returned a ``FalseNode``
# here but as far as I can tell this code is unreachable.
raise RuntimeError("Invalid boolean expression")
if len(clauses.or_parts) > 1:
return DisjunctionNode(
*[ConjunctionNode(*segment) for segment in clauses.or_parts]
)
instance = super(ConjunctionNode, cls).__new__(cls)
instance._nodes = clauses.or_parts[0]
return instance
def __getnewargs__(self):
"""Private API used to specify ``__new__`` arguments when unpickling.
.. note::
This method only applies if the ``pickle`` protocol is 2 or
greater.
Returns:
Tuple[Node, ...]: The list of stored nodes, converted to a
:class:`tuple`.
"""
return tuple(self._nodes)
def __iter__(self):
return iter(self._nodes)
def __repr__(self):
all_nodes = ", ".join(map(str, self._nodes))
return "AND({})".format(all_nodes)
def __eq__(self, other):
if not isinstance(other, ConjunctionNode):
return NotImplemented
return self._nodes == other._nodes
def _to_filter(self, post=False):
"""Helper to convert to low-level filter.
Args:
post (bool): Indicates if this is a post-filter node.
Returns:
Optional[Node]: The single or composite filter corresponding to
the pre- or post-filter nodes stored. May return :data:`None`.
"""
# Avoid circular import in Python 2.7
from google.cloud.ndb import _datastore_query
filters = []
for node in self._nodes:
if isinstance(node, PostFilterNode) == post:
as_filter = node._to_filter(post=post)
if as_filter:
filters.append(as_filter)
if not filters:
return None
if len(filters) == 1:
return filters[0]
if post:
def composite_and_predicate(entity_pb):
return all((filter(entity_pb) for filter in filters))
return composite_and_predicate
return _datastore_query.make_composite_and_filter(filters)
def _post_filters(self):
"""Helper to extract post-filter nodes, if any.
Filters all of the stored nodes that are :class:`PostFilterNode`.
Returns:
Optional[Node]: One of the following:
* :data:`None` if there are no post-filter nodes in this ``AND()``
clause
* The single node if there is exactly one post-filter node, e.g.
if the only node in ``AND(A, B, ...)`` that is a post-filter
node is ``B``
* The current node if every stored node a post-filter node, e.g.
if all nodes ``A, B, ...`` in ``AND(A, B, ...)`` are
post-filter nodes
* A **new** :class:`ConjunctionNode` containing the post-filter
nodes, e.g. if only ``A, C`` are post-filter nodes in
``AND(A, B, C)``, then the returned node is ``AND(A, C)``
"""
post_filters = [
node for node in self._nodes if isinstance(node, PostFilterNode)