-
Notifications
You must be signed in to change notification settings - Fork 122
/
SpannerSample.java
2275 lines (2155 loc) · 90.7 KB
/
SpannerSample.java
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
/*
* Copyright 2017 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.
*/
package com.example.spanner;
import static com.google.cloud.spanner.Type.StructField;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.retrying.RetryingFuture;
import com.google.api.gax.rpc.NotFoundException;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.KeyRange;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerBatchUpdateException;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient.ListBackupOperationsPagedResponse;
import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient.ListBackupsPagedResponse;
import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient.ListDatabaseOperationsPagedResponse;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.io.BaseEncoding;
import com.google.longrunning.Operation;
import com.google.protobuf.FieldMask;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Timestamp;
import com.google.spanner.admin.database.v1.Backup;
import com.google.spanner.admin.database.v1.BackupInfo;
import com.google.spanner.admin.database.v1.BackupName;
import com.google.spanner.admin.database.v1.CopyBackupMetadata;
import com.google.spanner.admin.database.v1.CreateBackupMetadata;
import com.google.spanner.admin.database.v1.CreateDatabaseRequest;
import com.google.spanner.admin.database.v1.DatabaseName;
import com.google.spanner.admin.database.v1.InstanceName;
import com.google.spanner.admin.database.v1.ListBackupOperationsRequest;
import com.google.spanner.admin.database.v1.ListBackupsRequest;
import com.google.spanner.admin.database.v1.ListDatabaseOperationsRequest;
import com.google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata;
import com.google.spanner.admin.database.v1.RestoreDatabaseMetadata;
import com.google.spanner.admin.database.v1.RestoreDatabaseRequest;
import com.google.spanner.admin.database.v1.RestoreInfo;
import com.google.spanner.v1.ExecuteSqlRequest.QueryOptions;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Example code for using the Cloud Spanner API. This example demonstrates all the common operations
* that can be done on Cloud Spanner. These are:
*
* <p>
*
* <ul>
* <li>Creating a Cloud Spanner database.
* <li>Writing, reading and executing SQL queries.
* <li>Writing data using a read-write transaction.
* <li>Using an index to read and execute SQL queries over data.
* <li>Using commit timestamp for tracking when a record was last updated.
* <li>Using Google API Extensions for Java to make thread-safe requests via long-running
* operations. http://googleapis.github.io/gax-java/
* </ul>
*/
public class SpannerSample {
/**
* Class to contain singer sample data.
*/
static class Singer {
final long singerId;
final String firstName;
final String lastName;
Singer(long singerId, String firstName, String lastName) {
this.singerId = singerId;
this.firstName = firstName;
this.lastName = lastName;
}
}
/**
* Class to contain album sample data.
*/
static class Album {
final long singerId;
final long albumId;
final String albumTitle;
Album(long singerId, long albumId, String albumTitle) {
this.singerId = singerId;
this.albumId = albumId;
this.albumTitle = albumTitle;
}
}
/**
* Class to contain performance sample data.
*/
static class Performance {
final long singerId;
final long venueId;
final String eventDate;
final long revenue;
Performance(long singerId, long venueId, String eventDate, long revenue) {
this.singerId = singerId;
this.venueId = venueId;
this.eventDate = eventDate;
this.revenue = revenue;
}
}
/**
* Class to contain venue sample data.
*/
static class Venue {
final long venueId;
final String venueName;
final String venueInfo;
final long capacity;
final Value availableDates;
final String lastContactDate;
final boolean outdoorVenue;
final float popularityScore;
final BigDecimal revenue;
final Value venueDetails;
Venue(
long venueId,
String venueName,
String venueInfo,
long capacity,
Value availableDates,
String lastContactDate,
boolean outdoorVenue,
float popularityScore,
BigDecimal revenue,
Value venueDetails) {
this.venueId = venueId;
this.venueName = venueName;
this.venueInfo = venueInfo;
this.capacity = capacity;
this.availableDates = availableDates;
this.lastContactDate = lastContactDate;
this.outdoorVenue = outdoorVenue;
this.popularityScore = popularityScore;
this.revenue = revenue;
this.venueDetails = venueDetails;
}
}
// [START spanner_insert_data]
static final List<Singer> SINGERS =
Arrays.asList(
new Singer(1, "Marc", "Richards"),
new Singer(2, "Catalina", "Smith"),
new Singer(3, "Alice", "Trentor"),
new Singer(4, "Lea", "Martin"),
new Singer(5, "David", "Lomond"));
static final List<Album> ALBUMS =
Arrays.asList(
new Album(1, 1, "Total Junk"),
new Album(1, 2, "Go, Go, Go"),
new Album(2, 1, "Green"),
new Album(2, 2, "Forever Hold Your Peace"),
new Album(2, 3, "Terrified"));
// [END spanner_insert_data]
// [START spanner_insert_data_with_timestamp_column]
static final List<Performance> PERFORMANCES =
Arrays.asList(
new Performance(1, 4, "2017-10-05", 11000),
new Performance(1, 19, "2017-11-02", 15000),
new Performance(2, 42, "2017-12-23", 7000));
// [END spanner_insert_data_with_timestamp_column]
// [START spanner_insert_datatypes_data]
static Value availableDates1 =
Value.dateArray(
Arrays.asList(
Date.parseDate("2020-12-01"),
Date.parseDate("2020-12-02"),
Date.parseDate("2020-12-03")));
static Value availableDates2 =
Value.dateArray(
Arrays.asList(
Date.parseDate("2020-11-01"),
Date.parseDate("2020-11-05"),
Date.parseDate("2020-11-15")));
static Value availableDates3 =
Value.dateArray(Arrays.asList(Date.parseDate("2020-10-01"), Date.parseDate("2020-10-07")));
static String exampleBytes1 = BaseEncoding.base64().encode("Hello World 1".getBytes());
static String exampleBytes2 = BaseEncoding.base64().encode("Hello World 2".getBytes());
static String exampleBytes3 = BaseEncoding.base64().encode("Hello World 3".getBytes());
static final List<Venue> VENUES =
Arrays.asList(
new Venue(
4,
"Venue 4",
exampleBytes1,
1800,
availableDates1,
"2018-09-02",
false,
0.85543f,
new BigDecimal("215100.10"),
Value.json(
"[{\"name\":\"room 1\",\"open\":true},{\"name\":\"room 2\",\"open\":false}]")),
new Venue(
19,
"Venue 19",
exampleBytes2,
6300,
availableDates2,
"2019-01-15",
true,
0.98716f,
new BigDecimal("1200100.00"),
Value.json("{\"rating\":9,\"open\":true}")),
new Venue(
42,
"Venue 42",
exampleBytes3,
3000,
availableDates3,
"2018-10-01",
false,
0.72598f,
new BigDecimal("390650.99"),
Value.json(
"{\"name\":null,"
+ "\"open\":{\"Monday\":true,\"Tuesday\":false},"
+ "\"tags\":[\"large\",\"airy\"]}")));
// [END spanner_insert_datatypes_data]
// [START spanner_create_database]
static void createDatabase(DatabaseAdminClient dbAdminClient,
InstanceName instanceName, String databaseId) {
CreateDatabaseRequest createDatabaseRequest =
CreateDatabaseRequest.newBuilder()
.setCreateStatement("CREATE DATABASE `" + databaseId + "`")
.setParent(instanceName.toString())
.addAllExtraStatements(Arrays.asList(
"CREATE TABLE Singers ("
+ " SingerId INT64 NOT NULL,"
+ " FirstName STRING(1024),"
+ " LastName STRING(1024),"
+ " SingerInfo BYTES(MAX),"
+ " FullName STRING(2048) AS "
+ " (ARRAY_TO_STRING([FirstName, LastName], \" \")) STORED"
+ ") PRIMARY KEY (SingerId)",
"CREATE TABLE Albums ("
+ " SingerId INT64 NOT NULL,"
+ " AlbumId INT64 NOT NULL,"
+ " AlbumTitle STRING(MAX)"
+ ") PRIMARY KEY (SingerId, AlbumId),"
+ " INTERLEAVE IN PARENT Singers ON DELETE CASCADE")).build();
try {
// Initiate the request which returns an OperationFuture.
com.google.spanner.admin.database.v1.Database db =
dbAdminClient.createDatabaseAsync(createDatabaseRequest).get();
System.out.println("Created database [" + db.getName() + "]");
} catch (ExecutionException e) {
// If the operation failed during execution, expose the cause.
throw (SpannerException) e.getCause();
} catch (InterruptedException e) {
// Throw when a thread is waiting, sleeping, or otherwise occupied,
// and the thread is interrupted, either before or during the activity.
throw SpannerExceptionFactory.propagateInterrupt(e);
}
}
// [END spanner_create_database]
// [START spanner_create_table_with_timestamp_column]
static void createTableWithTimestamp(DatabaseAdminClient dbAdminClient,
DatabaseName databaseName) {
try {
// Initiate the request which returns an OperationFuture.
dbAdminClient.updateDatabaseDdlAsync(
databaseName,
Arrays.asList(
"CREATE TABLE Performances ("
+ " SingerId INT64 NOT NULL,"
+ " VenueId INT64 NOT NULL,"
+ " EventDate Date,"
+ " Revenue INT64, "
+ " LastUpdateTime TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true)"
+ ") PRIMARY KEY (SingerId, VenueId, EventDate),"
+ " INTERLEAVE IN PARENT Singers ON DELETE CASCADE")).get();
System.out.println(
"Created Performances table in database: [" + databaseName.toString() + "]");
} catch (ExecutionException e) {
// If the operation failed during execution, expose the cause.
throw (SpannerException) e.getCause();
} catch (InterruptedException e) {
// Throw when a thread is waiting, sleeping, or otherwise occupied,
// and the thread is interrupted, either before or during the activity.
throw SpannerExceptionFactory.propagateInterrupt(e);
}
}
// [END spanner_create_table_with_timestamp_column]
// [START spanner_insert_data_with_timestamp_column]
static void writeExampleDataWithTimestamp(DatabaseClient dbClient) {
List<Mutation> mutations = new ArrayList<>();
for (Performance performance : PERFORMANCES) {
mutations.add(
Mutation.newInsertBuilder("Performances")
.set("SingerId")
.to(performance.singerId)
.set("VenueId")
.to(performance.venueId)
.set("EventDate")
.to(performance.eventDate)
.set("Revenue")
.to(performance.revenue)
.set("LastUpdateTime")
.to(Value.COMMIT_TIMESTAMP)
.build());
}
dbClient.write(mutations);
}
// [END spanner_insert_data_with_timestamp_column]
// [START spanner_insert_data]
static void writeExampleData(DatabaseClient dbClient) {
List<Mutation> mutations = new ArrayList<>();
for (Singer singer : SINGERS) {
mutations.add(
Mutation.newInsertBuilder("Singers")
.set("SingerId")
.to(singer.singerId)
.set("FirstName")
.to(singer.firstName)
.set("LastName")
.to(singer.lastName)
.build());
}
for (Album album : ALBUMS) {
mutations.add(
Mutation.newInsertBuilder("Albums")
.set("SingerId")
.to(album.singerId)
.set("AlbumId")
.to(album.albumId)
.set("AlbumTitle")
.to(album.albumTitle)
.build());
}
dbClient.write(mutations);
}
// [END spanner_insert_data]
// [START spanner_delete_data]
static void deleteExampleData(DatabaseClient dbClient) {
List<Mutation> mutations = new ArrayList<>();
// KeySet.Builder can be used to delete a specific set of rows.
// Delete the Albums with the key values (2,1) and (2,3).
mutations.add(
Mutation.delete(
"Albums", KeySet.newBuilder().addKey(Key.of(2, 1)).addKey(Key.of(2, 3)).build()));
// KeyRange can be used to delete rows with a key in a specific range.
// Delete a range of rows where the column key is >=3 and <5
mutations.add(
Mutation.delete("Singers", KeySet.range(KeyRange.closedOpen(Key.of(3), Key.of(5)))));
// KeySet.all() can be used to delete all the rows in a table.
// Delete remaining Singers rows, which will also delete the remaining Albums rows since it was
// defined with ON DELETE CASCADE.
mutations.add(Mutation.delete("Singers", KeySet.all()));
dbClient.write(mutations);
System.out.printf("Records deleted.\n");
}
// [END spanner_delete_data]
// [START spanner_query_data]
static void query(DatabaseClient dbClient) {
try (ResultSet resultSet =
dbClient
.singleUse() // Execute a single read or query against Cloud Spanner.
.executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s\n", resultSet.getLong(0), resultSet.getLong(1), resultSet.getString(2));
}
}
}
// [END spanner_query_data]
// [START spanner_read_data]
static void read(DatabaseClient dbClient) {
try (ResultSet resultSet =
dbClient
.singleUse()
.read(
"Albums",
KeySet.all(), // Read all rows in a table.
Arrays.asList("SingerId", "AlbumId", "AlbumTitle"))) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s\n", resultSet.getLong(0), resultSet.getLong(1), resultSet.getString(2));
}
}
}
// [END spanner_read_data]
// [START spanner_add_column]
static void addMarketingBudget(DatabaseAdminClient adminClient, DatabaseName databaseName) {
try {
// Initiate the request which returns an OperationFuture.
adminClient.updateDatabaseDdlAsync(
databaseName,
Arrays.asList("ALTER TABLE Albums ADD COLUMN MarketingBudget INT64")).get();
System.out.println("Added MarketingBudget column");
} catch (ExecutionException e) {
// If the operation failed during execution, expose the cause.
throw (SpannerException) e.getCause();
} catch (InterruptedException e) {
// Throw when a thread is waiting, sleeping, or otherwise occupied,
// and the thread is interrupted, either before or during the activity.
throw SpannerExceptionFactory.propagateInterrupt(e);
}
}
// [END spanner_add_column]
// Before executing this method, a new column MarketingBudget has to be added to the Albums
// table by applying the DDL statement "ALTER TABLE Albums ADD COLUMN MarketingBudget INT64".
// [START spanner_update_data]
static void update(DatabaseClient dbClient) {
// Mutation can be used to update/insert/delete a single row in a table. Here we use
// newUpdateBuilder to create update mutations.
List<Mutation> mutations =
Arrays.asList(
Mutation.newUpdateBuilder("Albums")
.set("SingerId")
.to(1)
.set("AlbumId")
.to(1)
.set("MarketingBudget")
.to(100000)
.build(),
Mutation.newUpdateBuilder("Albums")
.set("SingerId")
.to(2)
.set("AlbumId")
.to(2)
.set("MarketingBudget")
.to(500000)
.build());
// This writes all the mutations to Cloud Spanner atomically.
dbClient.write(mutations);
}
// [END spanner_update_data]
// [START spanner_read_write_transaction]
static void writeWithTransaction(DatabaseClient dbClient) {
dbClient
.readWriteTransaction()
.run(transaction -> {
// Transfer marketing budget from one album to another. We do it in a transaction to
// ensure that the transfer is atomic.
Struct row =
transaction.readRow("Albums", Key.of(2, 2), Arrays.asList("MarketingBudget"));
long album2Budget = row.getLong(0);
// Transaction will only be committed if this condition still holds at the time of
// commit. Otherwise it will be aborted and the callable will be rerun by the
// client library.
long transfer = 200000;
if (album2Budget >= transfer) {
long album1Budget =
transaction
.readRow("Albums", Key.of(1, 1), Arrays.asList("MarketingBudget"))
.getLong(0);
album1Budget += transfer;
album2Budget -= transfer;
transaction.buffer(
Mutation.newUpdateBuilder("Albums")
.set("SingerId")
.to(1)
.set("AlbumId")
.to(1)
.set("MarketingBudget")
.to(album1Budget)
.build());
transaction.buffer(
Mutation.newUpdateBuilder("Albums")
.set("SingerId")
.to(2)
.set("AlbumId")
.to(2)
.set("MarketingBudget")
.to(album2Budget)
.build());
}
return null;
});
}
// [END spanner_read_write_transaction]
// [START spanner_query_data_with_new_column]
static void queryMarketingBudget(DatabaseClient dbClient) {
// Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to
// null. A try-with-resource block is used to automatically release resources held by
// ResultSet.
try (ResultSet resultSet =
dbClient
.singleUse()
.executeQuery(Statement.of("SELECT SingerId, AlbumId, MarketingBudget FROM Albums"))) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s\n",
resultSet.getLong("SingerId"),
resultSet.getLong("AlbumId"),
// We check that the value is non null. ResultSet getters can only be used to retrieve
// non null values.
resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
}
}
}
// [END spanner_query_data_with_new_column]
// [START spanner_create_index]
static void addIndex(DatabaseAdminClient adminClient, DatabaseName databaseName) {
try {
// Initiate the request which returns an OperationFuture.
adminClient.updateDatabaseDdlAsync(
databaseName,
Arrays.asList("CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)")).get();
System.out.println("Added AlbumsByAlbumTitle index");
} catch (ExecutionException e) {
// If the operation failed during execution, expose the cause.
throw (SpannerException) e.getCause();
} catch (InterruptedException e) {
// Throw when a thread is waiting, sleeping, or otherwise occupied,
// and the thread is interrupted, either before or during the activity.
throw SpannerExceptionFactory.propagateInterrupt(e);
}
}
// [END spanner_create_index]
// Before running this example, add the index AlbumsByAlbumTitle by applying the DDL statement
// "CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)".
// [START spanner_query_data_with_index]
static void queryUsingIndex(DatabaseClient dbClient) {
Statement statement =
Statement
// We use FORCE_INDEX hint to specify which index to use. For more details see
// https://cloud.google.com/spanner/docs/query-syntax#from-clause
.newBuilder(
"SELECT AlbumId, AlbumTitle, MarketingBudget "
+ "FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle} "
+ "WHERE AlbumTitle >= @StartTitle AND AlbumTitle < @EndTitle")
// We use @BoundParameters to help speed up frequently executed queries.
// For more details see https://cloud.google.com/spanner/docs/sql-best-practices
.bind("StartTitle")
.to("Aardvark")
.bind("EndTitle")
.to("Goo")
.build();
try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
while (resultSet.next()) {
System.out.printf(
"%d %s %s\n",
resultSet.getLong("AlbumId"),
resultSet.getString("AlbumTitle"),
resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
}
}
}
// [END spanner_query_data_with_index]
// [START spanner_read_data_with_index]
static void readUsingIndex(DatabaseClient dbClient) {
try (ResultSet resultSet =
dbClient
.singleUse()
.readUsingIndex(
"Albums",
"AlbumsByAlbumTitle",
KeySet.all(),
Arrays.asList("AlbumId", "AlbumTitle"))) {
while (resultSet.next()) {
System.out.printf("%d %s\n", resultSet.getLong(0), resultSet.getString(1));
}
}
}
// [END spanner_read_data_with_index]
// [START spanner_create_storing_index]
static void addStoringIndex(DatabaseAdminClient adminClient, DatabaseName databaseName) {
try {
// Initiate the request which returns an OperationFuture.
adminClient.updateDatabaseDdlAsync(
databaseName,
Arrays.asList(
"CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) "
+ "STORING (MarketingBudget)")).get();
System.out.println("Added AlbumsByAlbumTitle2 index");
} catch (ExecutionException e) {
// If the operation failed during execution, expose the cause.
throw (SpannerException) e.getCause();
} catch (InterruptedException e) {
// Throw when a thread is waiting, sleeping, or otherwise occupied,
// and the thread is interrupted, either before or during the activity.
throw SpannerExceptionFactory.propagateInterrupt(e);
}
}
// [END spanner_create_storing_index]
// Before running this example, create a storing index AlbumsByAlbumTitle2 by applying the DDL
// statement "CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)".
// [START spanner_read_data_with_storing_index]
static void readStoringIndex(DatabaseClient dbClient) {
// We can read MarketingBudget also from the index since it stores a copy of MarketingBudget.
try (ResultSet resultSet =
dbClient
.singleUse()
.readUsingIndex(
"Albums",
"AlbumsByAlbumTitle2",
KeySet.all(),
Arrays.asList("AlbumId", "AlbumTitle", "MarketingBudget"))) {
while (resultSet.next()) {
System.out.printf(
"%d %s %s\n",
resultSet.getLong(0),
resultSet.getString(1),
resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
}
}
}
// [END spanner_read_data_with_storing_index]
// [START spanner_read_only_transaction]
static void readOnlyTransaction(DatabaseClient dbClient) {
// ReadOnlyTransaction must be closed by calling close() on it to release resources held by it.
// We use a try-with-resource block to automatically do so.
try (ReadOnlyTransaction transaction = dbClient.readOnlyTransaction()) {
ResultSet queryResultSet =
transaction.executeQuery(
Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"));
while (queryResultSet.next()) {
System.out.printf(
"%d %d %s\n",
queryResultSet.getLong(0), queryResultSet.getLong(1), queryResultSet.getString(2));
}
try (ResultSet readResultSet =
transaction.read(
"Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "AlbumTitle"))) {
while (readResultSet.next()) {
System.out.printf(
"%d %d %s\n",
readResultSet.getLong(0), readResultSet.getLong(1), readResultSet.getString(2));
}
}
}
}
// [END spanner_read_only_transaction]
// [START spanner_read_stale_data]
static void readStaleData(DatabaseClient dbClient) {
try (ResultSet resultSet =
dbClient
.singleUse(TimestampBound.ofExactStaleness(15, TimeUnit.SECONDS))
.read(
"Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "MarketingBudget"))) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s\n",
resultSet.getLong(0),
resultSet.getLong(1),
resultSet.isNull(2) ? "NULL" : resultSet.getLong("MarketingBudget"));
}
}
}
// [END spanner_read_stale_data]
// [START spanner_add_timestamp_column]
static void addCommitTimestamp(DatabaseAdminClient adminClient, DatabaseName databaseName) {
try {
// Initiate the request which returns an OperationFuture.
adminClient.updateDatabaseDdlAsync(
databaseName,
Arrays.asList(
"ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP "
+ "OPTIONS (allow_commit_timestamp=true)")).get();
System.out.println("Added LastUpdateTime as a commit timestamp column in Albums table.");
} catch (ExecutionException e) {
// If the operation failed during execution, expose the cause.
throw (SpannerException) e.getCause();
} catch (InterruptedException e) {
// Throw when a thread is waiting, sleeping, or otherwise occupied,
// and the thread is interrupted, either before or during the activity.
throw SpannerExceptionFactory.propagateInterrupt(e);
}
}
// [END spanner_add_timestamp_column]
// Before executing this method, a new column MarketingBudget has to be added to the Albums
// table by applying the DDL statement "ALTER TABLE Albums ADD COLUMN MarketingBudget INT64".
// In addition this update expects the LastUpdateTime column added by applying the DDL statement
// "ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP OPTIONS (allow_commit_timestamp=true)"
// [START spanner_update_data_with_timestamp_column]
static void updateWithTimestamp(DatabaseClient dbClient) {
// Mutation can be used to update/insert/delete a single row in a table. Here we use
// newUpdateBuilder to create update mutations.
List<Mutation> mutations =
Arrays.asList(
Mutation.newUpdateBuilder("Albums")
.set("SingerId")
.to(1)
.set("AlbumId")
.to(1)
.set("MarketingBudget")
.to(1000000)
.set("LastUpdateTime")
.to(Value.COMMIT_TIMESTAMP)
.build(),
Mutation.newUpdateBuilder("Albums")
.set("SingerId")
.to(2)
.set("AlbumId")
.to(2)
.set("MarketingBudget")
.to(750000)
.set("LastUpdateTime")
.to(Value.COMMIT_TIMESTAMP)
.build());
// This writes all the mutations to Cloud Spanner atomically.
dbClient.write(mutations);
}
// [END spanner_update_data_with_timestamp_column]
// [START spanner_query_data_with_timestamp_column]
static void queryMarketingBudgetWithTimestamp(DatabaseClient dbClient) {
// Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to
// null. A try-with-resource block is used to automatically release resources held by
// ResultSet.
try (ResultSet resultSet =
dbClient
.singleUse()
.executeQuery(
Statement.of(
"SELECT SingerId, AlbumId, MarketingBudget, LastUpdateTime FROM Albums"
+ " ORDER BY LastUpdateTime DESC"))) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s %s\n",
resultSet.getLong("SingerId"),
resultSet.getLong("AlbumId"),
// We check that the value is non null. ResultSet getters can only be used to retrieve
// non null values.
resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"),
resultSet.isNull("LastUpdateTime") ? "NULL" : resultSet.getTimestamp("LastUpdateTime"));
}
}
}
// [END spanner_query_data_with_timestamp_column]
static void querySingersTable(DatabaseClient dbClient) {
try (ResultSet resultSet =
dbClient
.singleUse()
.executeQuery(Statement.of("SELECT SingerId, FirstName, LastName FROM Singers"))) {
while (resultSet.next()) {
System.out.printf(
"%s %s %s\n",
resultSet.getLong("SingerId"),
resultSet.getString("FirstName"),
resultSet.getString("LastName"));
}
}
}
static void queryPerformancesTable(DatabaseClient dbClient) {
// Rows without an explicit value for Revenue will have a Revenue equal to
// null. A try-with-resource block is used to automatically release resources held by
// ResultSet.
try (ResultSet resultSet =
dbClient
.singleUse()
.executeQuery(
Statement.of(
"SELECT SingerId, VenueId, EventDate, Revenue, LastUpdateTime "
+ "FROM Performances ORDER BY LastUpdateTime DESC"))) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s %s %s\n",
resultSet.getLong("SingerId"),
resultSet.getLong("VenueId"),
resultSet.getDate("EventDate"),
// We check that the value is non null. ResultSet getters can only be used to retrieve
// non null values.
resultSet.isNull("Revenue") ? "NULL" : resultSet.getLong("Revenue"),
resultSet.getTimestamp("LastUpdateTime"));
}
}
}
// [START spanner_write_data_for_struct_queries]
static void writeStructExampleData(DatabaseClient dbClient) {
final List<Singer> singers =
Arrays.asList(
new Singer(6, "Elena", "Campbell"),
new Singer(7, "Gabriel", "Wright"),
new Singer(8, "Benjamin", "Martinez"),
new Singer(9, "Hannah", "Harris"));
List<Mutation> mutations = new ArrayList<>();
for (Singer singer : singers) {
mutations.add(
Mutation.newInsertBuilder("Singers")
.set("SingerId")
.to(singer.singerId)
.set("FirstName")
.to(singer.firstName)
.set("LastName")
.to(singer.lastName)
.build());
}
dbClient.write(mutations);
System.out.println("Inserted example data for struct parameter queries.");
}
// [END spanner_write_data_for_struct_queries]
static void queryWithStruct(DatabaseClient dbClient) {
// [START spanner_create_struct_with_data]
Struct name =
Struct.newBuilder().set("FirstName").to("Elena").set("LastName").to("Campbell").build();
// [END spanner_create_struct_with_data]
// [START spanner_query_data_with_struct]
Statement s =
Statement.newBuilder(
"SELECT SingerId FROM Singers "
+ "WHERE STRUCT<FirstName STRING, LastName STRING>(FirstName, LastName) "
+ "= @name")
.bind("name")
.to(name)
.build();
try (ResultSet resultSet = dbClient.singleUse().executeQuery(s)) {
while (resultSet.next()) {
System.out.printf("%d\n", resultSet.getLong("SingerId"));
}
}
// [END spanner_query_data_with_struct]
}
static void queryWithArrayOfStruct(DatabaseClient dbClient) {
// [START spanner_create_user_defined_struct]
Type nameType =
Type.struct(
Arrays.asList(
StructField.of("FirstName", Type.string()),
StructField.of("LastName", Type.string())));
// [END spanner_create_user_defined_struct]
// [START spanner_create_array_of_struct_with_data]
List<Struct> bandMembers = new ArrayList<>();
bandMembers.add(
Struct.newBuilder().set("FirstName").to("Elena").set("LastName").to("Campbell").build());
bandMembers.add(
Struct.newBuilder().set("FirstName").to("Gabriel").set("LastName").to("Wright").build());
bandMembers.add(
Struct.newBuilder().set("FirstName").to("Benjamin").set("LastName").to("Martinez").build());
// [END spanner_create_array_of_struct_with_data]
// [START spanner_query_data_with_array_of_struct]
Statement s =
Statement.newBuilder(
"SELECT SingerId FROM Singers WHERE "
+ "STRUCT<FirstName STRING, LastName STRING>(FirstName, LastName) "
+ "IN UNNEST(@names) "
+ "ORDER BY SingerId DESC")
.bind("names")
.toStructArray(nameType, bandMembers)
.build();
try (ResultSet resultSet = dbClient.singleUse().executeQuery(s)) {
while (resultSet.next()) {
System.out.printf("%d\n", resultSet.getLong("SingerId"));
}
}
// [END spanner_query_data_with_array_of_struct]
}
// [START spanner_field_access_on_struct_parameters]
static void queryStructField(DatabaseClient dbClient) {
Statement s =
Statement.newBuilder("SELECT SingerId FROM Singers WHERE FirstName = @name.FirstName")
.bind("name")
.to(
Struct.newBuilder()
.set("FirstName")
.to("Elena")
.set("LastName")
.to("Campbell")
.build())
.build();
try (ResultSet resultSet = dbClient.singleUse().executeQuery(s)) {
while (resultSet.next()) {
System.out.printf("%d\n", resultSet.getLong("SingerId"));
}
}
}
// [END spanner_field_access_on_struct_parameters]
// [START spanner_field_access_on_nested_struct_parameters]
static void queryNestedStructField(DatabaseClient dbClient) {
Type nameType =
Type.struct(
Arrays.asList(
StructField.of("FirstName", Type.string()),
StructField.of("LastName", Type.string())));
Struct songInfo =
Struct.newBuilder()
.set("song_name")
.to("Imagination")
.set("artistNames")
.toStructArray(
nameType,
Arrays.asList(
Struct.newBuilder()
.set("FirstName")
.to("Elena")
.set("LastName")
.to("Campbell")
.build(),
Struct.newBuilder()
.set("FirstName")
.to("Hannah")
.set("LastName")
.to("Harris")
.build()))
.build();
Statement s =
Statement.newBuilder(
"SELECT SingerId, @song_info.song_name "
+ "FROM Singers WHERE "
+ "STRUCT<FirstName STRING, LastName STRING>(FirstName, LastName) "
+ "IN UNNEST(@song_info.artistNames)")
.bind("song_info")
.to(songInfo)
.build();
try (ResultSet resultSet = dbClient.singleUse().executeQuery(s)) {
while (resultSet.next()) {
System.out.printf("%d %s\n", resultSet.getLong("SingerId"), resultSet.getString(1));
}
}
}
// [END spanner_field_access_on_nested_struct_parameters]
// [START spanner_dml_standard_insert]
static void insertUsingDml(DatabaseClient dbClient) {
dbClient
.readWriteTransaction()
.run(transaction -> {