-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat(spanner): BatchWrite Sample #2191
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
surbhigarg92
wants to merge
1
commit into
GoogleCloudPlatform:main
Choose a base branch
from
surbhigarg92:spanner-batch-write-sample
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+208
−0
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| <?php | ||
| /** | ||
| * Copyright 2026 Google Inc. | ||
| * | ||
| * 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 | ||
| * | ||
| * http://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. | ||
| */ | ||
|
|
||
| /** | ||
| * For instructions on how to run the full sample: | ||
| * | ||
| * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/main/spanner/README.md | ||
| */ | ||
|
|
||
| namespace Google\Cloud\Samples\Spanner; | ||
|
|
||
| // [START spanner_batch_write_at_least_once] | ||
| use Google\Cloud\Spanner\SpannerClient; | ||
| use Google\Cloud\Spanner\V1\Mutation; | ||
| use Google\Cloud\Spanner\V1\Mutation\Write; | ||
| use Google\Cloud\Spanner\V1\BatchWriteRequest\MutationGroup; | ||
|
|
||
| /** | ||
| * Inserts sample data into the given database via BatchWrite API. | ||
| * The database and table must already exist and can be created using `create_database`. | ||
| * | ||
| * Example: | ||
| * ``` | ||
| * batch_write($projectId, $instanceId, $databaseId); | ||
| * ``` | ||
| * | ||
| * @param string $projectId The Google Cloud project ID. | ||
| * @param string $instanceId The Spanner instance ID. | ||
| * @param string $databaseId The Spanner database ID. | ||
| */ | ||
| function batch_write(string $projectId, string $instanceId, string $databaseId): void | ||
| { | ||
| $spanner = new SpannerClient(['projectId' => $projectId]); | ||
| $database = $spanner->instance($instanceId)->database($databaseId); | ||
|
|
||
| // Create Mutation Groups | ||
| // All mutations within a single group are applied atomically. | ||
| // Mutations across groups are applied non-atomically. | ||
|
|
||
| // Group 1: Single mutation | ||
| $mutationGroup1 = new MutationGroup([ | ||
| 'mutations' => [ | ||
| new Mutation([ | ||
| 'insert_or_update' => new Write([ | ||
| 'table' => 'Singers', | ||
| 'columns' => ['SingerId', 'FirstName', 'LastName'], | ||
| 'values' => [ | ||
| [16, 'Scarlet', 'Terry'] | ||
| ] | ||
| ]) | ||
| ]) | ||
| ] | ||
| ]); | ||
|
|
||
| // Group 2: Multiple mutations | ||
| $mutationGroup2 = new MutationGroup([ | ||
| 'mutations' => [ | ||
| new Mutation([ | ||
| 'insert_or_update' => new Write([ | ||
| 'table' => 'Singers', | ||
| 'columns' => ['SingerId', 'FirstName'], | ||
| 'values' => [ | ||
| [17, 'Marc'] | ||
| ] | ||
| ]) | ||
| ]), | ||
| new Mutation([ | ||
| 'insert_or_update' => new Write([ | ||
| 'table' => 'Singers', | ||
| 'columns' => ['SingerId', 'FirstName', 'LastName'], | ||
| 'values' => [ | ||
| [18, 'Catalina', 'Smith'] | ||
| ] | ||
| ]) | ||
| ]), | ||
| new Mutation([ | ||
| 'insert_or_update' => new Write([ | ||
| 'table' => 'Albums', | ||
| 'columns' => ['SingerId', 'AlbumId', 'AlbumTitle'], | ||
| 'values' => [ | ||
| [17, 1, 'Total Junk'] | ||
| ] | ||
| ]) | ||
| ]), | ||
| new Mutation([ | ||
| 'insert_or_update' => new Write([ | ||
| 'table' => 'Albums', | ||
| 'columns' => ['SingerId', 'AlbumId', 'AlbumTitle'], | ||
| 'values' => [ | ||
| [18, 2, 'Go, Go, Go'] | ||
| ] | ||
| ]) | ||
| ]) | ||
| ] | ||
| ]); | ||
|
|
||
| $responses = $database->batchWriteAtLeastOnce([$mutationGroup1, $mutationGroup2], [ | ||
| 'requestOptions' => ['transactionTag' => 'batch-write-tag'] | ||
| ]); | ||
|
|
||
| // Check the response code of each response to determine whether the mutation group(s) were applied successfully. | ||
| foreach ($responses as $response) { | ||
| $status = $response->getStatus(); | ||
| $indexes = implode(', ', iterator_to_array($response->getIndexes())); | ||
| if ($status->getCode() === 0) { | ||
| $timestamp = $response->getCommitTimestamp(); | ||
| printf('Mutation group indexes [%s] have been applied with commit timestamp %s' . PHP_EOL, | ||
| $indexes, | ||
| $timestamp ? $timestamp->getSeconds() : 'Unknown' | ||
| ); | ||
| } else { | ||
| printf('Mutation group indexes [%s] could not be applied with error code %s and error message %s' . PHP_EOL, | ||
| $indexes, | ||
| $status->getCode(), | ||
| $status->getMessage() | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| // [END spanner_batch_write_at_least_once] | ||
|
|
||
| // The following 2 lines are only needed to run the samples | ||
| require_once __DIR__ . '/../../testing/sample_helpers.php'; | ||
| \Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); | ||
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 |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| <?php | ||
| /** | ||
| * Copyright 2026 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 | ||
| * | ||
| * http://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. | ||
| */ | ||
|
|
||
| namespace Google\Cloud\Samples\Spanner; | ||
|
|
||
| use Google\Cloud\Spanner\SpannerClient; | ||
| use Google\Cloud\TestUtils\EventuallyConsistentTestTrait; | ||
| use Google\Cloud\TestUtils\TestTrait; | ||
| use PHPUnitRetry\RetryTrait; | ||
| use PHPUnit\Framework\TestCase; | ||
|
|
||
| /** | ||
| * @retryAttempts 3 | ||
| * @retryDelayMethod exponentialBackoff | ||
| */ | ||
| class spannerBatchWriteTest extends TestCase | ||
| { | ||
| use TestTrait { | ||
| TestTrait::runFunctionSnippet as traitRunFunctionSnippet; | ||
| } | ||
|
|
||
| use RetryTrait, EventuallyConsistentTestTrait; | ||
|
|
||
| /** @var string instanceId */ | ||
| protected static $instanceId; | ||
|
|
||
| /** @var string databaseId */ | ||
| protected static $databaseId; | ||
|
|
||
| public static function setUpBeforeClass(): void | ||
| { | ||
| if (!extension_loaded('grpc')) { | ||
| self::markTestSkipped('Must enable grpc extension.'); | ||
| } | ||
| self::$instanceId = self::requireEnv('GOOGLE_SPANNER_INSTANCE_ID'); | ||
| self::$databaseId = self::requireEnv('GOOGLE_SPANNER_DATABASE_ID'); | ||
| } | ||
|
|
||
| /** | ||
| * @test | ||
| */ | ||
| public function testBatchWrite() | ||
| { | ||
| $output = $this->runFunctionSnippet('batch_write'); | ||
| $this->assertStringContainsString('Mutation group indexes', $output); | ||
| $this->assertStringContainsString('have been applied', $output); | ||
| } | ||
|
|
||
| private function runFunctionSnippet($sampleName, $params = []) | ||
| { | ||
| return $this->traitRunFunctionSnippet( | ||
| $sampleName, | ||
| array_merge([self::$projectId, self::$instanceId, self::$databaseId], array_values($params)) | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The class name
spannerBatchWriteTestdoes not adhere to the PSR-1 coding standard, which requires class names to be inStudlyCaps(also known asPascalCase). For consistency and to follow best practices, please rename the class toSpannerBatchWriteTest.References