Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions spanner/src/batch_write.php
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], [

Check failure on line 111 in spanner/src/batch_write.php

View workflow job for this annotation

GitHub Actions / staticanalysis

Call to an undefined method Google\Cloud\Spanner\Database::batchWriteAtLeastOnce().
'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);
70 changes: 70 additions & 0 deletions spanner/test/spannerBatchWriteTest.php
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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The class name spannerBatchWriteTest does not adhere to the PSR-1 coding standard, which requires class names to be in StudlyCaps (also known as PascalCase). For consistency and to follow best practices, please rename the class to SpannerBatchWriteTest.

class SpannerBatchWriteTest extends TestCase
References
  1. According to PSR-1: Basic Coding Standard, class names MUST be declared in StudlyCaps. (link)

{
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))
);
}
}
Loading