|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright 2019 Google LLC |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * For instructions on how to run the full sample: |
| 20 | + * |
| 21 | + * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/spanner/README.md |
| 22 | + */ |
| 23 | + |
| 24 | +namespace Google\Cloud\Samples\Spanner; |
| 25 | + |
| 26 | +// [START spanner_dml_batch_update] |
| 27 | +use Google\Cloud\Spanner\SpannerClient; |
| 28 | +use Google\Cloud\Spanner\Transaction; |
| 29 | + |
| 30 | +/** |
| 31 | + * Updates sample data in the database with Batch DML. |
| 32 | + * |
| 33 | + * This requires the `MarketingBudget` column which must be created before |
| 34 | + * running this sample. You can add the column by running the `add_column` |
| 35 | + * sample or by running this DDL statement against your database: |
| 36 | + * |
| 37 | + * ALTER TABLE Albums ADD COLUMN MarketingBudget INT64 |
| 38 | + * |
| 39 | + * Example: |
| 40 | + * ``` |
| 41 | + * update_data_with_batch_dml($instanceId, $databaseId); |
| 42 | + * ``` |
| 43 | + * |
| 44 | + * @param string $instanceId The Spanner instance ID. |
| 45 | + * @param string $databaseId The Spanner database ID. |
| 46 | + */ |
| 47 | +function update_data_with_batch_dml($instanceId, $databaseId) |
| 48 | +{ |
| 49 | + $spanner = new SpannerClient(); |
| 50 | + $instance = $spanner->instance($instanceId); |
| 51 | + $database = $instance->database($databaseId); |
| 52 | + |
| 53 | + $batchDmlResult = $database->runTransaction(function (Transaction $t) { |
| 54 | + $result = $t->executeUpdateBatch([ |
| 55 | + [ |
| 56 | + 'sql' => "INSERT INTO Albums " |
| 57 | + . "(SingerId, AlbumId, AlbumTitle, MarketingBudget) " |
| 58 | + . "VALUES (1, 3, 'Test Album Title', 10000)" |
| 59 | + ], |
| 60 | + [ |
| 61 | + 'sql' => "UPDATE Albums " |
| 62 | + . "SET MarketingBudget = MarketingBudget * 2 " |
| 63 | + . "WHERE SingerId = 1 and AlbumId = 3" |
| 64 | + ], |
| 65 | + ]); |
| 66 | + $t->commit(); |
| 67 | + $rowCounts = count($result->rowCounts()); |
| 68 | + printf('Executed %s SQL statements using Batch DML.' . PHP_EOL, |
| 69 | + $rowCounts); |
| 70 | + }); |
| 71 | +} |
| 72 | +// [END spanner_dml_batch_update] |
0 commit comments