Skip to content

Commit

Permalink
Allow class member values in projection and distinct queries (#214)
Browse files Browse the repository at this point in the history
Cloud datastore needs projection and distinct properties to be strings.  This commit sets the converted properties so they may be used by the rest of the query. (Fixes #212)
  • Loading branch information
chmoder authored and Chris Rossi committed Oct 1, 2019
1 parent ac3b7be commit f491fd1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
6 changes: 4 additions & 2 deletions google/cloud/ndb/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -1406,7 +1406,8 @@ def __init__(
"projection must be a tuple, list or None; "
"received {}".format(projection)
)
self._check_properties(self._to_property_names(projection))
projection = self._to_property_names(projection)
self._check_properties(projection)
self.projection = tuple(projection)

if distinct_on is not None and group_by is not None:
Expand All @@ -1426,7 +1427,8 @@ def __init__(
"distinct_on must be a tuple, list or None; "
"received {}".format(distinct_on)
)
self._check_properties(self._to_property_names(distinct_on))
distinct_on = self._to_property_names(distinct_on)
self._check_properties(distinct_on)
self.distinct_on = tuple(distinct_on)

def __repr__(self):
Expand Down
38 changes: 38 additions & 0 deletions tests/unit/test_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -1165,6 +1165,44 @@ def test_constructor_with_ancestor_parameterized_thing():
query = query_module.Query(ancestor=query_module.ParameterizedThing())
assert isinstance(query.ancestor, query_module.ParameterizedThing)

@staticmethod
@pytest.mark.usefixtures("in_context")
@unittest.mock.patch("google.cloud.ndb.query._datastore_query")
def test_constructor_with_class_attribute_projection(_datastore_query):
class Foo(model.Model):
string_attr = model.StringProperty()

class Bar(model.Model):
bar_attr = model.StructuredProperty(Foo)

query = Bar.query(projection=[Bar.bar_attr.string_attr])

assert query.projection[0] == ("bar_attr.string_attr",)[0]

query.fetch()

@staticmethod
@pytest.mark.usefixtures("in_context")
@unittest.mock.patch("google.cloud.ndb.query._datastore_query")
def test_constructor_with_class_attribute_projection_and_distinct(
_datastore_query
):
class Foo(model.Model):
string_attr = model.StringProperty()

class Bar(model.Model):
bar_attr = model.StructuredProperty(Foo)

query = Bar.query(
projection=[Bar.bar_attr.string_attr],
distinct_on=[Bar.bar_attr.string_attr],
)

assert query.projection[0] == ("bar_attr.string_attr",)[0]
assert query.distinct_on[0] == ("bar_attr.string_attr",)[0]

query.fetch()

@staticmethod
@pytest.mark.usefixtures("in_context")
def test_constructor_with_projection():
Expand Down

0 comments on commit f491fd1

Please sign in to comment.