Uh oh!
There was an error while loading. Please reload this page.
This repository was archived by the owner on Jun 8, 2026. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 103
feat: Batch Write API implementation and samples#1027
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
a32dd63
feat: Batch Write API implementation and samples
sunny1612 96e6e15
Update sample
sunny1612 1dc89f8
Merge branch 'main' into feat-batch-write
harshachinta edf304e
Merge branch 'main' into feat-batch-write
harshachinta 7708302
review comments
sunny1612 38d9b83
return public class for mutation groups
sunny1612 e584d96
Merge branch 'main' into feat-batch-write
fdc26d7
Merge branch 'main' into feat-batch-write
harshachinta 25e6999
Update google/cloud/spanner_v1/batch.py
7d57ac2
Update google/cloud/spanner_v1/batch.py
2435fe6
Merge branch 'main' into feat-batch-write
harshachinta 0a2aba4
review comments
sunny1612 e401452
remove doc
sunny1612 dc94850
feat(spanner): nit sample data refactoring
harshachinta 1e8bac4
Merge branch 'main' into feat-batch-write
harshachinta 8e3cbf2
Merge branch 'main' into feat-batch-write
harshachinta a0937cd
review comments
sunny1612 a4cf000
fix test
sunny1612 0263cb6
Merge branch 'main' into feat-batch-write
harshachinta 06ab2ca
Merge branch 'main' into feat-batch-write
harshachinta File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -18,6 +18,7 @@ | ||
| from google.cloud.spanner_v1 import CommitRequest | ||
| from google.cloud.spanner_v1 import Mutation | ||
| from google.cloud.spanner_v1 import TransactionOptions | ||
| from google.cloud.spanner_v1 import BatchWriteRequest | ||
| from google.cloud.spanner_v1._helpers import _SessionWrapper | ||
| from google.cloud.spanner_v1._helpers import _make_list_value_pbs | ||
| @@ -215,6 +216,99 @@ def __exit__(self, exc_type, exc_val, exc_tb): | ||
| self.commit() | ||
| class MutationGroup(_BatchBase): | ||
| """A container for mutations. | ||
| Clients should use :class:`~google.cloud.spanner_v1.MutationGroups` to | ||
| obtain instances instead of directly creating instances. | ||
| :type session: :class:`~google.cloud.spanner_v1.session.Session` | ||
| :param session: The session used to perform the commit. | ||
| :type mutations: list | ||
| :param mutations: The list into which mutations are to be accumulated. | ||
| """ | ||
| def __init__(self, session, mutations=[]): | ||
| super(MutationGroup, self).__init__(session) | ||
| self._mutations = mutations | ||
| class MutationGroups(_SessionWrapper): | ||
| """Accumulate mutation groups for transmission during :meth:`batch_write`. | ||
| :type session: :class:`~google.cloud.spanner_v1.session.Session` | ||
| :param session: the session used to perform the commit | ||
| """ | ||
| committed = None | ||
| def __init__(self, session): | ||
| super(MutationGroups, self).__init__(session) | ||
| self._mutation_groups = [] | ||
| def _check_state(self): | ||
| """Checks if the object's state is valid for making API requests. | ||
| :raises: :exc:`ValueError` if the object's state is invalid for making | ||
| API requests. | ||
| """ | ||
| if self.committed is not None: | ||
| raise ValueError("MutationGroups already committed") | ||
| def group(self): | ||
| """Returns a new `MutationGroup` to which mutations can be added.""" | ||
| mutation_group = BatchWriteRequest.MutationGroup() | ||
| self._mutation_groups.append(mutation_group) | ||
| return MutationGroup(self._session, mutation_group.mutations) | ||
| def batch_write(self, request_options=None): | ||
| """Executes batch_write. | ||
| :type request_options: | ||
| :class:`google.cloud.spanner_v1.types.RequestOptions` | ||
| :param request_options: | ||
| (Optional) Common options for this request. | ||
| If a dict is provided, it must be of the same form as the protobuf | ||
| message :class:`~google.cloud.spanner_v1.types.RequestOptions`. | ||
| :rtype: :class:`Iterable[google.cloud.spanner_v1.types.BatchWriteResponse]` | ||
| :returns: a sequence of responses for each batch. | ||
| """ | ||
| self._check_state() | ||
| database = self._session._database | ||
| api = database.spanner_api | ||
| metadata = _metadata_with_prefix(database.name) | ||
| if database._route_to_leader_enabled: | ||
| metadata.append( | ||
| _metadata_with_leader_aware_routing(database._route_to_leader_enabled) | ||
| ) | ||
| trace_attributes = {"num_mutation_groups": len(self._mutation_groups)} | ||
| if request_options is None: | ||
| request_options = RequestOptions() | ||
| elif type(request_options) is dict: | ||
| request_options = RequestOptions(request_options) | ||
| request = BatchWriteRequest( | ||
| session=self._session.name, | ||
| mutation_groups=self._mutation_groups, | ||
| request_options=request_options, | ||
| ) | ||
| with trace_call("CloudSpanner.BatchWrite", self._session, trace_attributes): | ||
| method = functools.partial( | ||
| api.batch_write, | ||
| request=request, | ||
| metadata=metadata, | ||
| ) | ||
| response = _retry( | ||
| method, | ||
| allowed_exceptions={InternalServerError: _check_rst_stream_error}, | ||
| ) | ||
| self.committed = True | ||
| return response | ||
This conversation was marked as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| def _make_write_pb(table, columns, values): | ||
| """Helper for :meth:`Batch.insert` et al. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -50,6 +50,7 @@ | ||
| _metadata_with_leader_aware_routing, | ||
| ) | ||
| from google.cloud.spanner_v1.batch import Batch | ||
| from google.cloud.spanner_v1.batch import MutationGroups | ||
| from google.cloud.spanner_v1.keyset import KeySet | ||
| from google.cloud.spanner_v1.pool import BurstyPool | ||
| from google.cloud.spanner_v1.pool import SessionCheckout | ||
| @@ -734,6 +735,17 @@ def batch(self, request_options=None): | ||
| """ | ||
| return BatchCheckout(self, request_options) | ||
| def mutation_groups(self): | ||
This conversation was marked as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| """Return an object which wraps a mutation_group. | ||
| The wrapper *must* be used as a context manager, with the mutation group | ||
| as the value returned by the wrapper. | ||
| :rtype: :class:`~google.cloud.spanner_v1.database.MutationGroupsCheckout` | ||
| :returns: new wrapper | ||
| """ | ||
| return MutationGroupsCheckout(self) | ||
| def batch_snapshot(self, read_timestamp=None, exact_staleness=None): | ||
| """Return an object which wraps a batch read / query. | ||
| @@ -1040,6 +1052,39 @@ def __exit__(self, exc_type, exc_val, exc_tb): | ||
| self._database._pool.put(self._session) | ||
| class MutationGroupsCheckout(object): | ||
| """Context manager for using mutation groups from a database. | ||
| Inside the context manager, checks out a session from the database, | ||
| creates mutation groups from it, making the groups available. | ||
| Caller must *not* use the object to perform API requests outside the scope | ||
| of the context manager. | ||
| :type database: :class:`~google.cloud.spanner_v1.database.Database` | ||
| :param database: database to use | ||
| """ | ||
| def __init__(self, database): | ||
| self._database = database | ||
| self._session = None | ||
| def __enter__(self): | ||
| """Begin ``with`` block.""" | ||
| session = self._session = self._database._pool.get() | ||
| return MutationGroups(session) | ||
| def __exit__(self, exc_type, exc_val, exc_tb): | ||
| """End ``with`` block.""" | ||
This conversation was marked as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| if isinstance(exc_val, NotFound): | ||
| # If NotFound exception occurs inside the with block | ||
| # then we validate if the session still exists. | ||
This conversation was marked as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| if not self._session.exists(): | ||
| self._session = self._database._pool._new_session() | ||
| self._session.create() | ||
| self._database._pool.put(self._session) | ||
| class SnapshotCheckout(object): | ||
| """Context manager for using a snapshot from a database. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.