Skip to content

Commit 1857302

Browse files
feat(bigtable): Rerouted RowSet and RowRange to use ReadRows from data client (#18196)
Migrating over @gkevinzheng PR from bigtable monorepo googleapis/python-bigtable#1296 ### Original description: > > **Changes made:** > > - Refactored `_MappableAttributesMixin` to `helpers.py` for use in `RowRange`. > - Used `RowRange` and `ReadRowsQuery` from the data client as backing data sources for `RowRange` and `RowSet` respectively. > Note to reviewers: This PR has already been reviewed and merged to a staging branch, with the intention of doing a single merge to main. We are now planning to slowly rollout these changes back to the main branch. Minimal re-review should be necessary --------- Co-authored-by: Kevin Zheng <147537668+gkevinzheng@users.noreply.github.com>
1 parent ed25a5c commit 1857302

6 files changed

Lines changed: 144 additions & 124 deletions

File tree

‎packages/google-cloud-bigtable/google/cloud/bigtable/data/exceptions.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ def __repr__(self):
141141
return f"{self.__class__.__name__}({message!r}, {self.exceptions!r})"
142142

143143

144+
# TODO: When working on mutations batcher, rework exception handling to guarantee that
145+
# MutationsExceptionGroup only stores FailedMutationEntryErrors.
144146
class MutationsExceptionGroup(_BigtableExceptionGroup):
145147
"""
146148
Represents one or more exceptions that occur during a bulk mutation operation

‎packages/google-cloud-bigtable/google/cloud/bigtable/helpers.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,35 @@ def batched(iterable: Iterable[T], n) -> Generator[Tuple[T, ...], None, None]:
2828
while batch:
2929
yield batch
3030
batch = tuple(islice(it, n))
31+
32+
33+
class _MappableAttributesMixin:
34+
"""
35+
Mixin for classes that need some of their attribute names remapped.
36+
37+
This is for taking some of the classes from the data client row filters
38+
and row range classes that are 1:1 with their legacy client counterparts but with
39+
some of their attributes renamed. To use in a class, override the base class with this mixin
40+
class and define a map _attribute_map from legacy client attributes to data client
41+
attributes.
42+
43+
Attributes are remapped and redefined in __init__ as well as getattr/setattr.
44+
"""
45+
46+
def __init__(self, *args, **kwargs):
47+
new_kwargs = {self._attribute_map.get(k, k): v for (k, v) in kwargs.items()}
48+
super(_MappableAttributesMixin, self).__init__(*args, **new_kwargs)
49+
50+
def __getattr__(self, name):
51+
if name == "_attribute_map":
52+
raise AttributeError
53+
if name not in self._attribute_map:
54+
raise AttributeError
55+
return getattr(self, self._attribute_map[name])
56+
57+
def __setattr__(self, name, value):
58+
if name == "_attribute_map":
59+
super(_MappableAttributesMixin, self).__setattr__(name, value)
60+
return
61+
attribute = self._attribute_map.get(name, name)
62+
super(_MappableAttributesMixin, self).__setattr__(attribute, value)

‎packages/google-cloud-bigtable/google/cloud/bigtable/row_filters.py‎

Lines changed: 1 addition & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from google.cloud.bigtable.data.row_filters import (
5151
TimestampRangeFilter as BaseTimestampRangeFilter,
5252
)
53+
from google.cloud.bigtable.helpers import _MappableAttributesMixin
5354

5455
_PACK_I64 = struct.Struct(">q").pack
5556

@@ -70,35 +71,6 @@ def _deprecated_to_pb(self):
7071
# Provide to_pb alias with DeprecationWarning for backwards compatibility with legacy client code
7172
RowFilter.to_pb = _deprecated_to_pb # type: ignore[attr-defined]
7273
TimestampRange.to_pb = _deprecated_to_pb # type: ignore[attr-defined]
73-
74-
75-
class _MappableAttributesMixin:
76-
"""
77-
Mixin for classes that need some of their attribute names remapped.
78-
79-
This is for taking some of the classes from the data client row filters
80-
that are 1:1 with their legacy client counterparts but with some of their
81-
attributes renamed. To use in a class, override the base class with this mixin
82-
class and define a map _attribute_map from legacy client attributes to data client
83-
attributes.
84-
85-
Attributes are remapped and redefined in __init__ as well as getattr/setattr.
86-
"""
87-
88-
def __init__(self, *args, **kwargs):
89-
new_kwargs = {self._attribute_map.get(k, k): v for (k, v) in kwargs.items()}
90-
super(_MappableAttributesMixin, self).__init__(*args, **new_kwargs)
91-
92-
def __getattr__(self, name):
93-
if name not in self._attribute_map:
94-
raise AttributeError
95-
return getattr(self, self._attribute_map[name])
96-
97-
def __setattr__(self, name, value):
98-
attribute = self._attribute_map.get(name, name)
99-
super(_MappableAttributesMixin, self).__setattr__(attribute, value)
100-
101-
10274
# The classes defined below are to provide constructors and members
10375
# that have an interface that does not match the one used by the data
10476
# client, for backwards compatibility purposes.

‎packages/google-cloud-bigtable/google/cloud/bigtable/row_set.py‎

Lines changed: 42 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,15 @@
1414

1515
"""User-friendly container for Google Cloud Bigtable RowSet"""
1616

17-
from google.cloud._helpers import _to_bytes # type: ignore
17+
from google.cloud._helpers import _to_bytes
18+
19+
from google.cloud.bigtable.data.read_rows_query import (
20+
ReadRowsQuery,
21+
)
22+
from google.cloud.bigtable.data.read_rows_query import (
23+
RowRange as BaseRowRange,
24+
)
25+
from google.cloud.bigtable.helpers import _MappableAttributesMixin
1826

1927

2028
class RowSet(object):
@@ -25,30 +33,25 @@ class RowSet(object):
2533
"""
2634

2735
def __init__(self):
28-
self.row_keys = []
29-
self.row_ranges = []
36+
self._read_rows_query = ReadRowsQuery()
3037

3138
def __eq__(self, other):
3239
if not isinstance(other, self.__class__):
3340
return NotImplemented
3441

35-
if len(other.row_keys) != len(self.row_keys):
36-
return False
37-
38-
if len(other.row_ranges) != len(self.row_ranges):
39-
return False
40-
41-
if not set(other.row_keys) == set(self.row_keys):
42-
return False
43-
44-
if not set(other.row_ranges) == set(self.row_ranges):
45-
return False
46-
47-
return True
42+
return self._read_rows_query == other._read_rows_query
4843

4944
def __ne__(self, other):
5045
return not self == other
5146

47+
@property
48+
def row_keys(self):
49+
return self._read_rows_query.row_keys
50+
51+
@property
52+
def row_ranges(self):
53+
return self._read_rows_query.row_ranges
54+
5255
def add_row_key(self, row_key):
5356
"""Add row key to row_keys list.
5457
@@ -62,7 +65,7 @@ def add_row_key(self, row_key):
6265
:type row_key: bytes
6366
:param row_key: The key of a row to read
6467
"""
65-
self.row_keys.append(row_key)
68+
self._read_rows_query.add_key(row_key)
6669

6770
def add_row_range(self, row_range):
6871
"""Add row_range to row_ranges list.
@@ -77,7 +80,7 @@ def add_row_range(self, row_range):
7780
:type row_range: class:`RowRange`
7881
:param row_range: The row range object having start and end key
7982
"""
80-
self.row_ranges.append(row_range)
83+
self._read_rows_query.add_range(row_range)
8184

8285
def add_row_range_from_keys(
8386
self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False
@@ -109,7 +112,7 @@ def add_row_range_from_keys(
109112
considered inclusive. The default is False (exclusive).
110113
"""
111114
row_range = RowRange(start_key, end_key, start_inclusive, end_inclusive)
112-
self.row_ranges.append(row_range)
115+
self._read_rows_query.add_range(row_range)
113116

114117
def add_row_range_with_prefix(self, row_key_prefix):
115118
"""Add row range to row_ranges list that start with the row_key_prefix from the row keys
@@ -135,22 +138,21 @@ def _update_message_request(self, message):
135138
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
136139
:param message: The ``ReadRowsRequest`` protobuf
137140
"""
138-
for each in self.row_keys:
141+
for each in self._read_rows_query.row_keys:
139142
message.rows.row_keys._pb.append(_to_bytes(each))
140143

141-
for each in self.row_ranges:
142-
r_kwrags = each.get_range_kwargs()
143-
message.rows.row_ranges.append(r_kwrags)
144+
for each in self._read_rows_query.row_ranges:
145+
message.rows.row_ranges.append(each._to_pb())
144146

145147

146-
class RowRange(object):
148+
class RowRange(_MappableAttributesMixin, BaseRowRange):
147149
"""Convenience wrapper of google.bigtable.v2.RowRange
148150
149-
:type start_key: bytes
151+
:type start_key: str | bytes
150152
:param start_key: (Optional) Start key of the row range. If left empty,
151153
will be interpreted as the empty string.
152154
153-
:type end_key: bytes
155+
:type end_key: str | bytes
154156
:param end_key: (Optional) End key of the row range. If left empty,
155157
will be interpreted as the empty string and range will
156158
be unbounded on the high end.
@@ -164,49 +166,31 @@ class RowRange(object):
164166
considered inclusive. The default is False (exclusive).
165167
"""
166168

167-
def __init__(
168-
self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False
169-
):
170-
self.start_key = start_key
171-
self.start_inclusive = start_inclusive
172-
self.end_key = end_key
173-
self.end_inclusive = end_inclusive
169+
_attribute_map = {
170+
"start_inclusive": "start_is_inclusive",
171+
"end_inclusive": "end_is_inclusive",
172+
}
174173

175174
def _key(self):
176-
"""A tuple key that uniquely describes this field.
177-
178-
Used to compute this instance's hashcode and evaluate equality.
179-
180-
Returns:
181-
Tuple[str]: The contents of this :class:`.RowRange`.
182-
"""
183-
return (self.start_key, self.start_inclusive, self.end_key, self.end_inclusive)
175+
return (
176+
self.start_key,
177+
self.end_key,
178+
self.start_is_inclusive,
179+
self.end_is_inclusive,
180+
)
184181

185182
def __hash__(self):
186183
return hash(self._key())
187184

188-
def __eq__(self, other):
189-
if not isinstance(other, self.__class__):
190-
return NotImplemented
191-
return self._key() == other._key()
192-
193-
def __ne__(self, other):
194-
return not self == other
195-
196185
def get_range_kwargs(self):
197186
"""Convert row range object to dict which can be passed to
198187
google.bigtable.v2.RowRange add method.
199188
"""
200189
range_kwargs = {}
201190
if self.start_key is not None:
202-
start_key_key = "start_key_open"
203-
if self.start_inclusive:
204-
start_key_key = "start_key_closed"
205-
range_kwargs[start_key_key] = _to_bytes(self.start_key)
206-
191+
key = "start_key_closed" if self.start_is_inclusive else "start_key_open"
192+
range_kwargs[key] = self.start_key
207193
if self.end_key is not None:
208-
end_key_key = "end_key_open"
209-
if self.end_inclusive:
210-
end_key_key = "end_key_closed"
211-
range_kwargs[end_key_key] = _to_bytes(self.end_key)
194+
key = "end_key_closed" if self.end_is_inclusive else "end_key_open"
195+
range_kwargs[key] = self.end_key
212196
return range_kwargs

‎packages/google-cloud-bigtable/tests/unit/v2_client/test_row_set.py‎

Lines changed: 64 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -48,38 +48,6 @@ def test_row_set__eq__type_differ():
4848
assert not (row_set1 == row_set2)
4949

5050

51-
def test_row_set__eq__len_row_keys_differ():
52-
from google.cloud.bigtable.row_set import RowSet
53-
54-
row_key1 = b"row_key1"
55-
row_key2 = b"row_key1"
56-
57-
row_set1 = RowSet()
58-
row_set2 = RowSet()
59-
60-
row_set1.add_row_key(row_key1)
61-
row_set1.add_row_key(row_key2)
62-
row_set2.add_row_key(row_key2)
63-
64-
assert not (row_set1 == row_set2)
65-
66-
67-
def test_row_set__eq__len_row_ranges_differ():
68-
from google.cloud.bigtable.row_set import RowRange, RowSet
69-
70-
row_range1 = RowRange(b"row_key4", b"row_key9")
71-
row_range2 = RowRange(b"row_key4", b"row_key9")
72-
73-
row_set1 = RowSet()
74-
row_set2 = RowSet()
75-
76-
row_set1.add_row_range(row_range1)
77-
row_set1.add_row_range(row_range2)
78-
row_set2.add_row_range(row_range2)
79-
80-
assert not (row_set1 == row_set2)
81-
82-
8351
def test_row_set__eq__row_keys_differ():
8452
from google.cloud.bigtable.row_set import RowSet
8553

@@ -223,8 +191,8 @@ def test_row_range_constructor():
223191
start_key = "row_key1"
224192
end_key = "row_key9"
225193
row_range = RowRange(start_key, end_key)
226-
assert start_key == row_range.start_key
227-
assert end_key == row_range.end_key
194+
assert start_key == row_range.start_key.decode()
195+
assert end_key == row_range.end_key.decode()
228196
assert row_range.start_inclusive
229197
assert not row_range.end_inclusive
230198

@@ -311,6 +279,68 @@ def test_row_range_get_range_kwargs_open_closed():
311279
assert expected_result == actual_result
312280

313281

282+
def test_row_range_get_range_kwargs_unbounded_start():
283+
from google.cloud.bigtable.row_set import RowRange
284+
285+
end_key = b"row_key9"
286+
expected_result = {"end_key_open": end_key}
287+
row_range = RowRange(None, end_key)
288+
actual_result = row_range.get_range_kwargs()
289+
assert expected_result == actual_result
290+
291+
292+
def test_row_range_get_range_kwargs_unbounded_end():
293+
from google.cloud.bigtable.row_set import RowRange
294+
295+
start_key = b"row_key1"
296+
expected_result = {"start_key_closed": start_key}
297+
row_range = RowRange(start_key, None)
298+
actual_result = row_range.get_range_kwargs()
299+
assert expected_result == actual_result
300+
301+
302+
def test_mappable_attributes_mixin_guard_recursion():
303+
import pytest
304+
305+
from google.cloud.bigtable.helpers import _MappableAttributesMixin
306+
307+
class Uninitialized(_MappableAttributesMixin):
308+
pass
309+
310+
obj = Uninitialized()
311+
with pytest.raises(AttributeError):
312+
_ = obj._attribute_map
313+
with pytest.raises(AttributeError):
314+
_ = obj.non_existent_attribute
315+
316+
# Verify setattr on _attribute_map doesn't cause recursion
317+
obj._attribute_map = {"old_attr": "new_attr"}
318+
assert obj._attribute_map == {"old_attr": "new_attr"}
319+
320+
321+
def test_mappable_attributes_mixin_remap():
322+
import pytest
323+
324+
from google.cloud.bigtable.helpers import _MappableAttributesMixin
325+
326+
class DummyBase:
327+
def __init__(self, target_attr=None):
328+
self.target_attr = target_attr
329+
330+
class MappedClass(_MappableAttributesMixin, DummyBase):
331+
_attribute_map = {"source_attr": "target_attr"}
332+
333+
instance = MappedClass(source_attr="hello")
334+
assert instance.target_attr == "hello"
335+
assert instance.source_attr == "hello"
336+
337+
instance.source_attr = "world"
338+
assert instance.target_attr == "world"
339+
340+
with pytest.raises(AttributeError):
341+
_ = instance.unknown_attr
342+
343+
314344
def _ReadRowsRequestPB(*args, **kw):
315345
from google.cloud.bigtable_v2.types import bigtable as messages_v2_pb2
316346

0 commit comments

Comments
 (0)