-
Notifications
You must be signed in to change notification settings - Fork 443
/
Copy pathDatabase.php
2293 lines (2168 loc) · 86.2 KB
/
Database.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Copyright 2016 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.
*/
namespace Google\Cloud\Spanner;
use Google\ApiCore\ApiException;
use Google\ApiCore\ValidationException;
use Google\Cloud\Core\Exception\AbortedException;
use Google\Cloud\Core\Exception\NotFoundException;
use Google\Cloud\Core\Exception\ServiceException;
use Google\Cloud\Core\Iam\Iam;
use Google\Cloud\Core\Iterator\ItemIterator;
use Google\Cloud\Core\LongRunning\LongRunningConnectionInterface;
use Google\Cloud\Core\LongRunning\LongRunningOperation;
use Google\Cloud\Core\LongRunning\LROTrait;
use Google\Cloud\Core\Retry;
use Google\Cloud\Spanner\Admin\Database\V1\Database\State;
use Google\Cloud\Spanner\Admin\Database\V1\DatabaseAdminClient;
use Google\Cloud\Spanner\Admin\Database\V1\DatabaseDialect;
use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient;
use Google\Cloud\Spanner\Connection\ConnectionInterface;
use Google\Cloud\Spanner\Connection\IamDatabase;
use Google\Cloud\Spanner\Session\Session;
use Google\Cloud\Spanner\Session\SessionPoolInterface;
use Google\Cloud\Spanner\V1\SpannerClient as GapicSpannerClient;
use Google\Cloud\Spanner\V1\TypeCode;
use Google\Rpc\Code;
/**
* Represents a Cloud Spanner Database.
*
* Example:
* ```
* use Google\Cloud\Spanner\SpannerClient;
*
* $spanner = new SpannerClient();
*
* $database = $spanner->connect('my-instance', 'my-database');
* ```
*
* ```
* // Databases can also be connected to via an Instance.
* use Google\Cloud\Spanner\SpannerClient;
*
* $spanner = new SpannerClient();
*
* $instance = $spanner->instance('my-instance');
* $database = $instance->database('my-database');
* ```
*
* @method resumeOperation() {
* Resume a Long Running Operation
*
* Example:
* ```
* $operation = $database->resumeOperation($operationName);
* ```
*
* @param string $operationName The Long Running Operation name.
* @param array $info [optional] The operation data.
* @return LongRunningOperation
* }
* @method longRunningOperations() {
* List long running operations.
*
* Example:
* ```
* $operations = $database->longRunningOperations();
* ```
*
* @param array $options [optional] {
* Configuration Options.
*
* @type string $name The name of the operation collection.
* @type string $filter The standard list filter.
* @type int $pageSize Maximum number of results to return per
* request.
* @type int $resultLimit Limit the number of results returned in total.
* **Defaults to** `0` (return all results).
* @type string $pageToken A previously-returned page token used to
* resume the loading of results from a specific point.
* }
* @return ItemIterator<InstanceConfiguration>
* }
*/
class Database
{
use LROTrait;
use TransactionConfigurationTrait;
use RequestHeaderTrait;
const STATE_CREATING = State::CREATING;
const STATE_READY = State::READY;
const STATE_READY_OPTIMIZING = State::READY_OPTIMIZING;
const MAX_RETRIES = 10;
const TYPE_BOOL = TypeCode::BOOL;
const TYPE_INT64 = TypeCode::INT64;
const TYPE_FLOAT32 = TypeCode::FLOAT32;
const TYPE_FLOAT64 = TypeCode::FLOAT64;
const TYPE_TIMESTAMP = TypeCode::TIMESTAMP;
const TYPE_DATE = TypeCode::DATE;
const TYPE_STRING = TypeCode::STRING;
const TYPE_BYTES = TypeCode::BYTES;
const TYPE_ARRAY = TypeCode::PBARRAY;
const TYPE_STRUCT = TypeCode::STRUCT;
const TYPE_NUMERIC = TypeCode::NUMERIC;
const TYPE_PG_NUMERIC = 'pgNumeric';
const TYPE_PG_JSONB = 'pgJsonb';
const TYPE_JSON = TypeCode::JSON;
const TYPE_PG_OID = 'pgOid';
/**
* @var ConnectionInterface
* @internal
*/
private $connection;
/**
* @var Instance
*/
private $instance;
/**
* @var Operation
*/
private $operation;
/**
* @var string
*/
private $projectId;
/**
* @var string
*/
private $name;
/**
* @var array
*/
private $info;
/**
* @var Iam|null
*/
private $iam;
/**
* @var Session|null
*/
private $session;
/**
* @var SessionPoolInterface|null
*/
private $sessionPool;
/**
* @var bool
*/
private $isRunningTransaction = false;
/**
* @var string|null
*/
private $databaseRole;
/**
* @var array
*/
private $directedReadOptions;
/**
* @var bool
*/
private $returnInt64AsObject;
/**
* Create an object representing a Database.
*
* @param ConnectionInterface $connection The connection to the
* Cloud Spanner Admin API. This object is created by SpannerClient,
* and should not be instantiated outside of this client.
* @param Instance $instance The instance in which the database exists.
* @param LongRunningConnectionInterface $lroConnection An implementation
* mapping to methods which handle LRO resolution in the service.
* @param array $lroCallables
* @param string $projectId The project ID.
* @param string $name The database name or ID.
* @param SessionPoolInterface $sessionPool [optional] The session pool
* implementation.
* @param bool $returnInt64AsObject [optional If true, 64 bit integers will
* be returned as a {@see \Google\Cloud\Core\Int64} object for 32 bit
* platform compatibility. **Defaults to** false.
* @param string $databaseRole The user created database role which creates the session.
*/
public function __construct(
ConnectionInterface $connection,
Instance $instance,
LongRunningConnectionInterface $lroConnection,
array $lroCallables,
$projectId,
$name,
?SessionPoolInterface $sessionPool = null,
$returnInt64AsObject = false,
array $info = [],
$databaseRole = ''
) {
$this->connection = $connection;
$this->instance = $instance;
$this->projectId = $projectId;
$this->name = $this->fullyQualifiedDatabaseName($name);
$this->sessionPool = $sessionPool;
$this->operation = new Operation($connection, $returnInt64AsObject);
$this->info = $info;
if ($this->sessionPool) {
$this->sessionPool->setDatabase($this);
}
$this->setLroProperties($lroConnection, $lroCallables, $this->name);
$this->databaseRole = $databaseRole;
$this->directedReadOptions = $instance->directedReadOptions();
$this->returnInt64AsObject = $returnInt64AsObject;
}
/**
* Return the database state.
*
* When databases are created or restored, they may take some time before
* they are ready for use. This method allows for checking whether a
* database is ready. Note that this value is cached within the class instance,
* so if you are polling it, first call {@see \Google\Cloud\Spanner\Database::reload()}
* to refresh the cached value.
*
* Example:
* ```
* if ($database->state() === Database::STATE_READY) {
* echo 'Database is ready!';
* }
* ```
*
* @param array $options [optional] Configuration options.
* @return int|null
*/
public function state(array $options = [])
{
$info = $this->info($options);
return (isset($info['state']))
? $info['state']
: null;
}
/**
* List completed and pending backups belonging to this database.
*
* Example:
* ```
* $backups = $database->backups();
* ```
*
* @param array $options [optional] {
* Configuration options.
* @type string $filter The standard list filter.
* **NOTE**: This method always sets the database filter as a name of this database.
* User may provide additional filter expressions which would be appended in the form of
* "(database:<databaseName>) AND (<additional filter expression from user>)"
* @type int $pageSize Maximum number of results to return per request.
* @type int $resultLimit Limit the number of results returned in total.
* **Defaults to** `0` (return all results).
* @type string $pageToken A previously-returned page token used to
* resume the loading of results from a specific point.
* }
*
* @return ItemIterator<Backup>
*/
public function backups(array $options = [])
{
$filter = 'database:' . $this->name();
if (isset($options['filter'])) {
$filter = sprintf('(%1$s) AND (%2$s)', $filter, $this->pluck('filter', $options));
}
return $this->instance->backups([
'filter' => $filter
] + $options);
}
/**
* Create a backup for this database.
*
* Example:
* ```
* $operation = $database->createBackup('my-backup', new \DateTime('+7 hours'));
* ```
*
* @param string $name The backup name.
* @param \DateTimeInterface $expireTime The expiration time of the backup,
* with microseconds granularity that must be at least 6 hours and
* at most 366 days. Once the expireTime has passed, the backup is
* eligible to be automatically deleted by Cloud Spanner.
* @param array $options [optional] Configuration options.
*
* @return LongRunningOperation<Backup>
*/
public function createBackup($name, \DateTimeInterface $expireTime, array $options = [])
{
$backup = $this->instance->backup($name);
return $backup->create($this->name(), $expireTime, $options);
}
/**
* Return the fully-qualified database name.
*
* Example:
* ```
* $name = $database->name();
* ```
*
* @return string
*/
public function name()
{
return $this->name;
}
/**
* Get the database info
*
* Example:
* ```
* $info = $database->info();
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.Database Database
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] Configuration options.
* @return array
*/
public function info(array $options = [])
{
return $this->info ?: $this->reload($options);
}
/**
* Reload the database info from the Cloud Spanner API.
*
* Example:
* ```
* $info = $database->reload();
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.Database Database
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] Configuration options.
* @return array
*/
public function reload(array $options = [])
{
return $this->info = $this->connection->getDatabase([
'name' => $this->name
] + $options);
}
/**
* Check if the database exists.
*
* This method sends a service request.
*
* **NOTE**: Requires `https://www.googleapis.com/auth/spanner.admin` scope.
*
* Example:
* ```
* if ($database->exists()) {
* echo 'Database exists!';
* }
* ```
*
* @param array $options [optional] Configuration options.
* @return bool
*/
public function exists(array $options = [])
{
try {
$this->reload($options);
} catch (NotFoundException $e) {
return false;
}
return true;
}
/**
* Create a new Cloud Spanner database.
*
* Example:
* ```
* $operation = $database->create();
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#createdatabaserequest CreateDatabaseRequest
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] {
* Configuration Options
*
* @type string[] $statements Additional DDL statements.
* }
* @return LongRunningOperation<Database>
*/
public function create(array $options = [])
{
$statements = $this->pluck('statements', $options, false) ?: [];
$dialect = $options['databaseDialect'] ?? null;
$createStatement = $this->getCreateDbStatement($dialect);
$operation = $this->connection->createDatabase([
'instance' => $this->instance->name(),
'createStatement' => $createStatement,
'extraStatements' => $statements
] + $options);
return $this->resumeOperation($operation['name'], $operation);
}
/**
* Restores to this database from a backup.
*
* **NOTE**: A restore operation can only be made to a non-existing database.
*
* Example:
* ```
* $operation = $database->restore($backup);
* ```
*
* @param Backup|string $backup The backup to restore, given as a Backup instance or a string of the form
* `projects/<project>/instances/<instance>/backups/<backup>`.
* @param array $options [optional] Configuration options.
*
* @return LongRunningOperation<Database>
*/
public function restore($backup, array $options = [])
{
return $this->instance->createDatabaseFromBackup($this->name, $backup, $options);
}
/**
* Update an existing Cloud Spanner database.
*
* Example:
* ```
* $operation = $database->updateDatabase(['enableDropProtection' => true]);
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#updatedatabaserequest UpdateDatabaseRequest
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] {
* Configuration Options
*
* @type bool $enableDropProtection If `true`, delete operations for Database
* and Instance will be blocked. **Defaults to** `false`.
* }
* @return LongRunningOperation<Database>
*/
public function updateDatabase(array $options = [])
{
$fieldMask = [];
if (isset($options['enableDropProtection'])) {
$fieldMask[] = 'enable_drop_protection';
}
return $this->connection->updateDatabase([
'database' => [
'name' => $this->name,
'enableDropProtection' => $options['enableDropProtection'] ?? false,
],
'updateMask' => [
'paths' => $fieldMask
]
] + $options);
}
/**
* Update the Database schema by running a SQL statement.
*
* **NOTE**: Requires `https://www.googleapis.com/auth/spanner.admin` scope.
*
* Example:
* ```
* $database->updateDdl(
* 'CREATE TABLE Users (
* id INT64 NOT NULL,
* name STRING(100) NOT NULL
* password STRING(100) NOT NULL
* )'
* );
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/docs/data-definition-language Data Definition Language
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.UpdateDatabaseDdlRequest UpdateDDLRequest
* @codingStandardsIgnoreEnd
*
* @param string $statement A DDL statements to run against a database.
* @param array $options [optional] Configuration options.
* @return LongRunningOperation
*/
public function updateDdl($statement, array $options = [])
{
return $this->updateDdlBatch([$statement], $options);
}
/**
* Update the Database schema by running a set of SQL statements.
*
* **NOTE**: Requires `https://www.googleapis.com/auth/spanner.admin` scope.
*
* Example:
* ```
* $database->updateDdlBatch([
* 'CREATE TABLE Users (
* id INT64 NOT NULL,
* name STRING(100) NOT NULL,
* password STRING(100) NOT NULL
* ) PRIMARY KEY (id)',
* 'CREATE TABLE Posts (
* id INT64 NOT NULL,
* title STRING(100) NOT NULL,
* content STRING(MAX) NOT NULL
* ) PRIMARY KEY(id)'
* ]);
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/docs/data-definition-language Data Definition Language
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.UpdateDatabaseDdlRequest UpdateDDLRequest
* @codingStandardsIgnoreEnd
*
* @param string[] $statements A list of DDL statements to run against a database.
* @param array $options [optional] Configuration options.
* @return LongRunningOperation
*/
public function updateDdlBatch(array $statements, array $options = [])
{
$operation = $this->connection->updateDatabaseDdl($options + [
'name' => $this->name,
'statements' => $statements,
]);
return $this->resumeOperation($operation['name'], $operation);
}
/**
* Drop the database.
*
* Please note that after a database is dropped, all sessions attached to it
* will be invalid and unusable. Calls to this method will clear any session
* pool attached to this database class instance and delete any sessions
* attached to the database class instance.
*
* **NOTE**: Requires `https://www.googleapis.com/auth/spanner.admin` scope.
*
* Example:
* ```
* $database->drop();
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DropDatabaseRequest DropDatabaseRequest
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] Configuration options.
* @return void
*/
public function drop(array $options = [])
{
$this->connection->dropDatabase($options + [
'name' => $this->name
]);
if ($this->sessionPool) {
$this->sessionPool->clear();
}
if ($this->session) {
$this->session->delete($options);
$this->session = null;
}
}
/**
* Get a list of all database DDL statements.
*
* **NOTE**: Requires `https://www.googleapis.com/auth/spanner.admin` scope.
*
* Example:
* ```
* $statements = $database->ddl();
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#getdatabaseddlrequest GetDatabaseDdlRequest
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] Configuration options.
* @return array
*/
public function ddl(array $options = [])
{
$ddl = $this->connection->getDatabaseDDL($options + [
'name' => $this->name
]);
if (isset($ddl['statements'])) {
return $ddl['statements'];
}
return [];
}
/**
* Manage the database IAM policy
*
* Example:
* ```
* $iam = $database->iam();
* ```
*
* @return Iam
*/
public function iam()
{
if (!$this->iam) {
$this->iam = new Iam(
new IamDatabase($this->connection),
$this->name
);
}
return $this->iam;
}
/**
* Create a snapshot to read from a database at a point in time.
*
* If no configuration options are provided, transaction will be opened with
* strong consistency.
*
* Snapshots are executed behind the scenes using a Read-Only Transaction.
*
* Example:
* ```
* $snapshot = $database->snapshot();
* ```
*
* ```
* // Take a shapshot with a returned timestamp.
* $snapshot = $database->snapshot([
* 'returnReadTimestamp' => true
* ]);
*
* $timestamp = $snapshot->readTimestamp();
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.BeginTransactionRequest BeginTransactionRequest
* @see https://cloud.google.com/spanner/docs/transactions Transactions
*
* @param array $options [optional] {
* Configuration Options
*
* See [ReadOnly](https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.TransactionOptions.ReadOnly)
* for detailed description of available options.
*
* Please note that only one of `$strong`, `$readTimestamp` or
* `$exactStaleness` may be set in a request.
*
* @type bool $returnReadTimestamp If true, the Cloud Spanner-selected
* read timestamp is included in the Transaction message that
* describes the transaction.
* @type bool $strong Read at a timestamp where all previously committed
* transactions are visible.
* @type Timestamp $readTimestamp Executes all reads at the given
* timestamp.
* @type Duration $exactStaleness Represents a number of seconds. Executes
* all reads at a timestamp that is $exactStaleness old.
* @type Timestamp $minReadTimestamp Executes all reads at a
* timestamp >= min_read_timestamp. Only available when
* `$options.singleUse` is true.
* @type Duration $maxStaleness Read data at a timestamp >= NOW - max_staleness
* seconds. Guarantees that all writes that have committed more
* than the specified number of seconds ago are visible. Only
* available when `$options.singleUse` is true.
* @type bool $singleUse If true, a Transaction ID will not be allocated
* up front. Instead, the transaction will be considered
* "single-use", and may be used for only a single operation.
* **Defaults to** `false`.
* @type array $sessionOptions Session configuration and request options.
* Session labels may be applied using the `labels` key.
* @type array $directedReadOptions Directed read options.
* {@see \Google\Cloud\Spanner\V1\DirectedReadOptions}
* If using the `replicaSelection::type` setting, utilize the constants available in
* {@see \Google\Cloud\Spanner\V1\DirectedReadOptions\ReplicaSelection\Type} to set a value.
* }
* @return Snapshot
* @throws \BadMethodCallException If attempting to call this method within
* an existing transaction.
* @codingStandardsIgnoreEnd
*/
public function snapshot(array $options = [])
{
if ($this->isRunningTransaction) {
throw new \BadMethodCallException('Nested transactions are not supported by this client.');
}
$options += [
'singleUse' => false
];
$options['transactionOptions'] = $this->configureSnapshotOptions($options);
$options['directedReadOptions'] = $this->configureDirectedReadOptions(
$options,
$this->directedReadOptions ?? []
);
$session = $this->selectSession(
SessionPoolInterface::CONTEXT_READ,
$this->pluck('sessionOptions', $options, false) ?: []
);
try {
return $this->operation->snapshot($session, $options);
} finally {
$session->setExpiration();
}
}
/**
* Create and return a new read/write Transaction.
*
* When manually using a Transaction, it is advised that retry logic be
* implemented to reapply all operations when an instance of
* {@see \Google\Cloud\Core\Exception\AbortedException} is thrown.
*
* If you wish Google Cloud PHP to handle retry logic for you (recommended
* for most cases), use {@see \Google\Cloud\Spanner\Database::runTransaction()}.
*
* Please note that once a transaction reads data, it will lock the read
* data, preventing other users from modifying that data. For this reason,
* it is important that every transaction commits or rolls back as early as
* possible. Do not hold transactions open longer than necessary.
*
* Example:
* ```
* $transaction = $database->transaction();
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.BeginTransactionRequest BeginTransactionRequest
* @see https://cloud.google.com/spanner/docs/transactions Transactions
* @codingStandardsIgnoreEnd
*
* @param array $options [optional] {
* Configuration Options.
*
* @type bool $singleUse If true, a Transaction ID will not be allocated
* up front. Instead, the transaction will be considered
* "single-use", and may be used for only a single operation.
* **Defaults to** `false`.
* @type array $sessionOptions Session configuration and request options.
* Session labels may be applied using the `labels` key.
* @type string $tag A transaction tag. Requests made using this transaction will
* use this as the transaction tag.
* }
* @return Transaction
* @throws \BadMethodCallException If attempting to call this method within
* an existing transaction.
*/
public function transaction(array $options = [])
{
if ($this->isRunningTransaction) {
throw new \BadMethodCallException('Nested transactions are not supported by this client.');
}
// There isn't anything configurable here.
$options['transactionOptions'] = $this->configureTransactionOptions();
$session = $this->selectSession(
SessionPoolInterface::CONTEXT_READWRITE,
$this->pluck('sessionOptions', $options, false) ?: []
);
try {
return $this->operation->transaction($session, $options);
} finally {
$session->setExpiration();
}
}
/**
* Execute Read/Write operations inside a Transaction.
*
* Using this method and providing a callable operation provides certain
* benefits including automatic retry when a transaction fails. In case of a
* failure, all transaction operations, including reads, are re-applied in a
* new transaction.
*
* If a transaction exceeds the maximum number of retries,
* {@see \Google\Cloud\Core\Exception\AbortedException} will be thrown. Any other
* exception types will immediately bubble up and will interrupt the retry
* operation.
*
* Please note that once a transaction reads data, it will lock the read
* data, preventing other users from modifying that data. For this reason,
* it is important that every transaction commits or rolls back as early as
* possible. Do not hold transactions open longer than necessary.
*
* Please also note that nested transactions are NOT supported by this client.
* Attempting to call `runTransaction` inside a transaction callable will
* raise a `BadMethodCallException`.
*
* If a callable finishes executing without invoking
* {@see \Google\Cloud\Spanner\Transaction::commit()} or
* {@see \Google\Cloud\Spanner\Transaction::rollback()}, the transaction will
* automatically be rolled back and `\RuntimeException` thrown.
*
* Example:
* ```
* use Google\Cloud\Spanner\Timestamp;
*
* $transaction = $database->runTransaction(function (Transaction $t) use ($username, $password) {
* $rows = $t->execute('SELECT * FROM Users WHERE Name = @name and PasswordHash = @password', [
* 'parameters' => [
* 'name' => $username,
* 'password' => password_hash($password, PASSWORD_DEFAULT)
* ]
* ])->rows();
* $user = $rows->current();
*
* if ($user) {
* // Do something here to grant the user access.
* // Maybe set a cookie?
*
* $user['lastLoginTime'] = new Timestamp(new \DateTime);
* $user['loginCount'] = $user['loginCount'] + 1;
* $t->update('Users', $user);
*
* $t->commit();
* } else {
* $t->rollback();
* }
* });
* ```
*
* @codingStandardsIgnoreStart
* @see https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.BeginTransactionRequest BeginTransactionRequest
* @see https://cloud.google.com/spanner/docs/transactions Transactions
* @codingStandardsIgnoreEnd
*
* @param callable $operation The operations to run in the transaction.
* **Signature:** `function (Transaction $transaction)`.
* @param array $options [optional] {
* Configuration Options
*
* @type int $maxRetries The number of times to attempt to apply the
* operation before failing. **Defaults to ** `10`.
* @type bool $singleUse If true, a Transaction ID will not be allocated
* up front. Instead, the transaction will be considered
* "single-use", and may be used for only a single operation. Note
* that in a single-use transaction, only a single operation may
* be executed, and rollback is not available. **Defaults to**
* `false`.
* @type array $sessionOptions Session configuration and request options.
* Session labels may be applied using the `labels` key.
* @type string $tag A transaction tag. Requests made using this transaction will
* use this as the transaction tag.
* }
* @return mixed The return value of `$operation`.
* @throws \RuntimeException If a transaction is not committed or rolled back.
* @throws \BadMethodCallException If attempting to call this method within
* an existing transaction.
*/
public function runTransaction(callable $operation, array $options = [])
{
if ($this->isRunningTransaction) {
throw new \BadMethodCallException('Nested transactions are not supported by this client.');
}
$options += [
'maxRetries' => self::MAX_RETRIES,
];
// There isn't anything configurable here.
$options['transactionOptions'] = $this->configureTransactionOptions($options['transactionOptions'] ?? []);
$session = $this->selectSession(
SessionPoolInterface::CONTEXT_READWRITE,
$this->pluck('sessionOptions', $options, false) ?: []
);
$attempt = 0;
$startTransactionFn = function ($session, $options) use (&$attempt) {
// Initial attempt requires to set `begin` options (ILB).
if ($attempt === 0) {
// Partitioned DML does not support ILB.
if (!isset($options['transactionOptions']['partitionedDml'])) {
$options['begin'] = $options['transactionOptions'];
}
} else {
$options['isRetry'] = true;
}
$transaction = $this->operation->transaction($session, $options);
$attempt++;
return $transaction;
};
$delayFn = function (\Exception $e) {
if ($e instanceof AbortedException) {
return $e->getRetryDelay();
}
if ($e instanceof ServiceException &&
$e->getCode() === Code::INTERNAL &&
strpos($e->getMessage(), 'RST_STREAM') !== false
) {
return $e->getRetryDelay();
}
throw $e;
};
$transactionFn = function ($operation, $session, $options) use ($startTransactionFn) {
$transaction = call_user_func_array($startTransactionFn, [
$session,
$options
]);
// Prevent nested transactions.
$this->isRunningTransaction = true;
try {
$res = call_user_func($operation, $transaction);
} finally {
$this->isRunningTransaction = false;
}
$active = $transaction->state() === Transaction::STATE_ACTIVE;
$singleUse = $transaction->type() === Transaction::TYPE_SINGLE_USE;
if ($active && !$singleUse) {
$transaction->rollback($options);
throw new \RuntimeException('Transactions must be rolled back or committed.');
}
return $res;
};
$retry = new Retry($options['maxRetries'], $delayFn);
try {
return $retry->execute($transactionFn, [$operation, $session, $options]);
} finally {
$session->setExpiration();
}
}
/**
* Insert a row.
*
* Mutations are committed in a single-use transaction.
*
* Since this method does not feature replay protection, it may attempt to
* apply mutations more than once; if the mutations are not idempotent, this
* may lead to a failure being reported when the mutation was previously
* applied.
*
* Example: