-
Notifications
You must be signed in to change notification settings - Fork 382
/
Copy pathsamples.cc
4748 lines (4274 loc) · 202 KB
/
samples.cc
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 2019 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
//
// https://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.
//! [START spanner_quickstart]
#include "google/cloud/spanner/client.h"
//! [END spanner_quickstart]
#include "google/cloud/spanner/admin/database_admin_client.h"
#include "google/cloud/spanner/admin/database_admin_options.h"
#include "google/cloud/spanner/admin/instance_admin_client.h"
#include "google/cloud/spanner/admin/instance_admin_options.h"
#include "google/cloud/spanner/backoff_policy.h"
#include "google/cloud/spanner/backup.h"
#include "google/cloud/spanner/connection_options.h"
#include "google/cloud/spanner/create_instance_request_builder.h"
#include "google/cloud/spanner/row.h"
#include "google/cloud/spanner/testing/debug_log.h" // TODO(#4758): remove
#include "google/cloud/spanner/testing/instance_location.h"
#include "google/cloud/spanner/testing/pick_instance_config.h"
#include "google/cloud/spanner/testing/pick_random_instance.h"
#include "google/cloud/spanner/testing/random_backup_name.h"
#include "google/cloud/spanner/testing/random_database_name.h"
#include "google/cloud/spanner/testing/random_instance_name.h"
#include "google/cloud/spanner/update_instance_request_builder.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include "google/cloud/kms_key_name.h"
#include "google/cloud/log.h"
#include "google/cloud/project.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include <chrono>
#include <iomanip>
#include <iterator>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
namespace {
//! [START spanner_get_instance_config] [get-instance-config]
void GetInstanceConfig(google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id,
std::string const& config_id) {
auto project = google::cloud::Project(project_id);
auto config = client.GetInstanceConfig(project.FullName() +
"/instanceConfigs/" + config_id);
if (!config) throw std::move(config).status();
std::cout << "The instanceConfig " << config->name()
<< " exists and its metadata is:\n"
<< config->DebugString();
}
//! [END spanner_get_instance_config] [get-instance-config]
void GetInstanceConfigCommand(std::vector<std::string> argv) {
if (argv.size() != 2) {
throw std::runtime_error("get-instance-config <project-id> <config-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
GetInstanceConfig(std::move(client), argv[0], argv[1]);
}
//! [START spanner_list_instance_configs] [list-instance-configs]
void ListInstanceConfigs(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id) {
int count = 0;
auto project = google::cloud::Project(project_id);
for (auto& config : client.ListInstanceConfigs(project.FullName())) {
if (!config) throw std::move(config).status();
++count;
std::cout << "Instance config [" << count << "]:\n"
<< config->DebugString();
}
if (count == 0) {
std::cout << "No instance configs found in project " << project_id << "\n";
}
}
//! [END spanner_list_instance_configs] [list-instance-configs]
void ListInstanceConfigsCommand(std::vector<std::string> argv) {
if (argv.size() != 1) {
throw std::runtime_error("list-instance-configs <project-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
ListInstanceConfigs(std::move(client), argv[0]);
}
// [START spanner_create_instance_config]
void CreateInstanceConfig(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id, std::string const& user_config_id,
std::string const& base_config_id) {
auto project = google::cloud::Project(project_id);
auto base_config = client.GetInstanceConfig(
project.FullName() + "/instanceConfigs/" + base_config_id);
if (!base_config) throw std::move(base_config).status();
if (base_config->optional_replicas().empty()) {
throw std::runtime_error("No optional replicas in base config");
}
google::spanner::admin::instance::v1::CreateInstanceConfigRequest request;
request.set_parent(project.FullName());
request.set_instance_config_id(user_config_id);
auto* request_config = request.mutable_instance_config();
request_config->set_name(project.FullName() + "/instanceConfigs/" +
user_config_id);
request_config->set_display_name("My instance config");
// The user-managed instance config must contain all the replicas
// of the base config plus at least one of the optional replicas.
*request_config->mutable_replicas() = base_config->replicas();
for (auto const& replica : base_config->optional_replicas()) {
*request_config->add_replicas() = replica;
}
request_config->set_base_config(base_config->name());
*request_config->mutable_leader_options() = base_config->leader_options();
request.set_validate_only(false);
auto user_config = client.CreateInstanceConfig(request).get();
if (!user_config) throw std::move(user_config).status();
std::cout << "Created instance config [" << user_config_id << "]:\n"
<< user_config->DebugString();
}
// [END spanner_create_instance_config]
void CreateInstanceConfigCommand(std::vector<std::string> argv) {
if (argv.size() != 3) {
throw std::runtime_error(
"create-instance-config <project-id> <config-id> <base-config-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
CreateInstanceConfig(std::move(client), argv[0], argv[1], argv[2]);
}
// [START spanner_update_instance_config]
void UpdateInstanceConfig(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id, std::string const& config_id) {
auto project = google::cloud::Project(project_id);
auto config = client.GetInstanceConfig(project.FullName() +
"/instanceConfigs/" + config_id);
if (!config) throw std::move(config).status();
google::spanner::admin::instance::v1::UpdateInstanceConfigRequest request;
auto* request_config = request.mutable_instance_config();
request_config->set_name(config->name());
request_config->mutable_labels()->insert({"key", "value"});
request.mutable_update_mask()->add_paths("labels");
request_config->set_etag(config->etag());
request.set_validate_only(false);
auto updated_config = client.UpdateInstanceConfig(request).get();
if (!updated_config) throw std::move(updated_config).status();
std::cout << "Updated instance config [" << config_id << "]:\n"
<< updated_config->DebugString();
}
// [END spanner_update_instance_config]
void UpdateInstanceConfigCommand(std::vector<std::string> argv) {
if (argv.size() != 2) {
throw std::runtime_error("update-instance-config <project-id> <config-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
UpdateInstanceConfig(std::move(client), argv[0], argv[1]);
}
// [START spanner_delete_instance_config]
void DeleteInstanceConfig(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id, std::string const& config_id) {
auto project = google::cloud::Project(project_id);
auto config_name = project.FullName() + "/instanceConfigs/" + config_id;
auto status = client.DeleteInstanceConfig(config_name);
if (!status.ok()) throw std::move(status);
std::cout << "Instance config " << config_name << " successfully deleted\n";
}
// [END spanner_delete_instance_config]
void DeleteInstanceConfigCommand(std::vector<std::string> argv) {
if (argv.size() != 2) {
throw std::runtime_error("delete-instance-config <project-id> <config-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
DeleteInstanceConfig(std::move(client), argv[0], argv[1]);
}
// [START spanner_list_instance_config_operations]
void ListInstanceConfigOperations(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id) {
auto project = google::cloud::Project(project_id);
google::spanner::admin::database::v1::ListBackupOperationsRequest request;
request.set_parent(project.FullName());
request.set_filter(
std::string("metadata.@type=type.googleapis.com/") +
"google.spanner.admin.instance.v1.CreateInstanceConfigMetadata");
for (auto& operation :
client.ListInstanceConfigOperations(project.FullName())) {
if (!operation) throw std::move(operation).status();
google::spanner::admin::instance::v1::CreateInstanceConfigMetadata metadata;
operation->metadata().UnpackTo(&metadata);
std::cout << "CreateInstanceConfig metadata is:\n"
<< metadata.DebugString();
}
request.set_filter(
std::string("metadata.@type=type.googleapis.com/") +
"google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata");
for (auto& operation :
client.ListInstanceConfigOperations(project.FullName())) {
if (!operation) throw std::move(operation).status();
google::spanner::admin::instance::v1::UpdateInstanceConfigMetadata metadata;
operation->metadata().UnpackTo(&metadata);
std::cout << "UpdateInstanceConfig metadata is:\n"
<< metadata.DebugString();
}
}
// [END spanner_list_instance_config_operations]
void ListInstanceConfigOperationsCommand(std::vector<std::string> argv) {
if (argv.size() != 1) {
throw std::runtime_error("list-instance-config-operations <project-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
ListInstanceConfigOperations(std::move(client), argv[0]);
}
//! [get-instance]
void GetInstance(google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id,
std::string const& instance_id) {
google::cloud::spanner::Instance in(project_id, instance_id);
auto instance = client.GetInstance(in.FullName());
if (!instance) throw std::move(instance).status();
std::cout << "The instance " << instance->name()
<< " exists and its metadata is:\n"
<< instance->DebugString();
}
//! [get-instance]
void GetInstanceCommand(std::vector<std::string> argv) {
if (argv.size() != 2) {
throw std::runtime_error("get-instance <project-id> <instance-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
GetInstance(std::move(client), argv[0], argv[1]);
}
//! [list-instances]
void ListInstances(google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id) {
int count = 0;
auto project = google::cloud::Project(project_id);
for (auto& instance : client.ListInstances(project.FullName())) {
if (!instance) throw std::move(instance).status();
++count;
std::cout << "Instance [" << count << "]:\n" << instance->DebugString();
}
if (count == 0) {
std::cout << "No instances found in project " << project_id << "\n";
}
}
//! [list-instances]
void ListInstancesCommand(std::vector<std::string> argv) {
if (argv.size() != 1) {
throw std::runtime_error("list-instances <project-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
ListInstances(std::move(client), argv[0]);
}
//! [START spanner_create_instance] [create-instance]
void CreateInstance(google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id,
std::string const& instance_id,
std::string const& display_name,
std::string const& config_id) {
namespace spanner = ::google::cloud::spanner;
spanner::Instance in(project_id, instance_id);
auto project = google::cloud::Project(project_id);
std::string config_name =
project.FullName() + "/instanceConfigs/" + config_id;
auto instance =
client
.CreateInstance(spanner::CreateInstanceRequestBuilder(in, config_name)
.SetDisplayName(display_name)
.SetNodeCount(1)
.SetLabels({{"cloud_spanner_samples", "true"}})
.Build())
.get();
if (!instance) throw std::move(instance).status();
std::cout << "Created instance [" << in << "]:\n" << instance->DebugString();
}
//! [END spanner_create_instance] [create-instance]
// [START spanner_create_instance_with_processing_units]
void CreateInstanceWithProcessingUnits(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& display_name, std::string const& config_id) {
namespace spanner = ::google::cloud::spanner;
spanner::Instance in(project_id, instance_id);
auto project = google::cloud::Project(project_id);
std::string config_name =
project.FullName() + "/instanceConfigs/" + config_id;
auto instance =
client
.CreateInstance(spanner::CreateInstanceRequestBuilder(in, config_name)
.SetDisplayName(display_name)
.SetProcessingUnits(500)
.SetLabels({{"cloud_spanner_samples", "true"}})
.Build())
.get();
if (!instance) throw std::move(instance).status();
std::cout << "Created instance [" << in << "]:\n" << instance->DebugString();
instance = client.GetInstance(in.FullName());
if (!instance) throw std::move(instance).status();
std::cout << "Instance " << in << " has " << instance->processing_units()
<< " processing units.\n";
}
// [END spanner_create_instance_with_processing_units]
void CreateInstanceCommand(std::vector<std::string> argv) {
bool low_cost = !argv.empty() && argv.front() == "--low-cost";
if (low_cost) argv.erase(argv.begin());
if (argv.size() != 3 && argv.size() != 4) {
throw std::runtime_error(
"create-instance [--low-cost] <project-id> <instance-id>"
" <display-name> [config-id]");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
std::string config_id = argv.size() == 4 ? argv[3] : "regional-us-central1";
if (low_cost) {
CreateInstanceWithProcessingUnits(std::move(client), argv[0], argv[1],
argv[2], config_id);
} else {
CreateInstance(std::move(client), argv[0], argv[1], argv[2], config_id);
}
}
//! [update-instance]
void UpdateInstance(google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id,
std::string const& instance_id,
std::string const& new_display_name) {
google::cloud::spanner::Instance in(project_id, instance_id);
auto f = client.UpdateInstance(
google::cloud::spanner::UpdateInstanceRequestBuilder(in)
.SetDisplayName(new_display_name)
.Build());
auto instance = f.get();
if (!instance) throw std::move(instance).status();
std::cout << "Updated instance [" << in << "]\n";
}
//! [update-instance]
void UpdateInstanceCommand(std::vector<std::string> argv) {
if (argv.size() != 3) {
throw std::runtime_error(
"update-instance <project-id> <instance-id> <new-display-name>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
UpdateInstance(std::move(client), argv[0], argv[1], argv[2]);
}
//! [delete-instance]
void DeleteInstance(google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id,
std::string const& instance_id) {
google::cloud::spanner::Instance in(project_id, instance_id);
auto status = client.DeleteInstance(in.FullName());
if (!status.ok()) throw std::move(status);
std::cout << "Deleted instance [" << in << "]\n";
}
//! [delete-instance]
void DeleteInstanceCommand(std::vector<std::string> argv) {
if (argv.size() != 2) {
throw std::runtime_error("delete-instance <project-id> <instance-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
DeleteInstance(std::move(client), argv[0], argv[1]);
}
//! [instance-get-iam-policy]
void InstanceGetIamPolicy(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id, std::string const& instance_id) {
google::cloud::spanner::Instance in(project_id, instance_id);
auto actual = client.GetIamPolicy(in.FullName());
if (!actual) throw std::move(actual).status();
std::cout << "The IAM policy for instance " << instance_id << " is:\n"
<< actual->DebugString();
}
//! [instance-get-iam-policy]
void InstanceGetIamPolicyCommand(std::vector<std::string> argv) {
if (argv.size() != 2) {
throw std::runtime_error(
"instance-get-iam-policy <project-id> <instance-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
InstanceGetIamPolicy(std::move(client), argv[0], argv[1]);
}
//! [add-database-reader]
void AddDatabaseReader(google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id,
std::string const& instance_id,
std::string const& new_reader) {
google::cloud::spanner::Instance in(project_id, instance_id);
auto result = client.SetIamPolicy(
in.FullName(),
[&new_reader](google::iam::v1::Policy current)
-> absl::optional<google::iam::v1::Policy> {
// Find (or create) the binding for "roles/spanner.databaseReader".
auto& binding = [¤t]() -> google::iam::v1::Binding& {
auto role_pos = std::find_if(
current.mutable_bindings()->begin(),
current.mutable_bindings()->end(),
[](google::iam::v1::Binding const& b) {
return b.role() == "roles/spanner.databaseReader" &&
!b.has_condition();
});
if (role_pos != current.mutable_bindings()->end()) {
return *role_pos;
}
auto& binding = *current.add_bindings();
binding.set_role("roles/spanner.databaseReader");
return binding;
}();
auto member_pos = std::find(binding.members().begin(),
binding.members().end(), new_reader);
if (member_pos != binding.members().end()) {
std::cout << "The entity " << new_reader
<< " is already a database reader:\n"
<< current.DebugString();
return {};
}
binding.add_members(new_reader);
return current;
});
if (!result) throw std::move(result).status();
std::cout << "Successfully added " << new_reader
<< " to the database reader role:\n"
<< result->DebugString();
}
//! [add-database-reader]
void AddDatabaseReaderCommand(std::vector<std::string> argv) {
if (argv.size() != 3) {
throw std::runtime_error(
"add-database-reader <project-id> <instance-id> <new-reader>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
AddDatabaseReader(std::move(client), argv[0], argv[1], argv[2]);
}
//! [remove-database-reader]
void RemoveDatabaseReader(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& reader) {
google::cloud::spanner::Instance in(project_id, instance_id);
auto result = client.SetIamPolicy(
in.FullName(),
[&reader](google::iam::v1::Policy current)
-> absl::optional<google::iam::v1::Policy> {
// Find the binding for "roles/spanner.databaseReader".
auto role_pos =
std::find_if(current.mutable_bindings()->begin(),
current.mutable_bindings()->end(),
[](google::iam::v1::Binding const& b) {
return b.role() == "roles/spanner.databaseReader" &&
!b.has_condition();
});
if (role_pos == current.mutable_bindings()->end()) {
std::cout << "Nothing to do as the roles/spanner.databaseReader role "
"is empty\n";
return {};
}
role_pos->mutable_members()->erase(
std::remove(role_pos->mutable_members()->begin(),
role_pos->mutable_members()->end(), reader),
role_pos->mutable_members()->end());
return current;
});
if (!result) throw std::move(result).status();
std::cout << "Successfully removed " << reader
<< " from the database reader role:\n"
<< result->DebugString();
}
//! [remove-database-reader]
void RemoveDatabaseReaderCommand(std::vector<std::string> argv) {
if (argv.size() != 3) {
throw std::runtime_error(
"remove-database-reader <project-id> <instance-id> <existing-reader>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
RemoveDatabaseReader(std::move(client), argv[0], argv[1], argv[2]);
}
//! [instance-test-iam-permissions]
void InstanceTestIamPermissions(
google::cloud::spanner_admin::InstanceAdminClient client,
std::string const& project_id, std::string const& instance_id) {
google::cloud::spanner::Instance in(project_id, instance_id);
auto actual =
client.TestIamPermissions(in.FullName(), {"spanner.databases.list"});
if (!actual) throw std::move(actual).status();
char const* msg = actual->permissions().empty() ? "does not" : "does";
std::cout
<< "The caller " << msg
<< " have permission to list databases on the Cloud Spanner instance "
<< in.instance_id() << "\n";
}
//! [instance-test-iam-permissions]
void InstanceTestIamPermissionsCommand(std::vector<std::string> argv) {
if (argv.size() != 2) {
throw std::runtime_error(
"instance-test-iam-permissions <project-id> <instance-id>");
}
google::cloud::spanner_admin::InstanceAdminClient client(
google::cloud::spanner_admin::MakeInstanceAdminConnection());
InstanceTestIamPermissions(std::move(client), argv[0], argv[1]);
}
google::cloud::spanner::Timestamp DatabaseNow(
google::cloud::spanner::Client client) {
auto rows = client.ExecuteQuery(
google::cloud::spanner::SqlStatement("SELECT CURRENT_TIMESTAMP()"));
using RowType = std::tuple<google::cloud::spanner::Timestamp>;
auto row = google::cloud::spanner::GetSingularRow(
google::cloud::spanner::StreamOf<RowType>(rows));
if (!row) throw std::move(row).status();
return std::get<0>(*row);
}
google::cloud::spanner::Timestamp TimestampAdd(
google::cloud::spanner::Timestamp ts, absl::Duration d) {
auto const t = ts.get<absl::Time>().value();
return google::cloud::spanner::MakeTimestamp(t + d).value();
}
google::cloud::spanner::Client MakeSampleClient(
std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
return google::cloud::spanner::Client(google::cloud::spanner::MakeConnection(
google::cloud::spanner::Database(project_id, instance_id, database_id)));
}
//! [create-database] [START spanner_create_database]
void CreateDatabase(google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id,
std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
google::spanner::admin::database::v1::CreateDatabaseRequest request;
request.set_parent(database.instance().FullName());
request.set_create_statement("CREATE DATABASE `" + database.database_id() +
"`");
request.add_extra_statements(R"""(
CREATE TABLE Singers (
SingerId INT64 NOT NULL,
FirstName STRING(1024),
LastName STRING(1024),
SingerInfo BYTES(MAX),
FullName STRING(2049)
AS (ARRAY_TO_STRING([FirstName, LastName], " ")) STORED
) PRIMARY KEY (SingerId))""");
request.add_extra_statements(R"""(
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)""");
auto db = client.CreateDatabase(request).get();
if (!db) throw std::move(db).status();
std::cout << "Database " << db->name() << " created.\n";
}
//! [create-database] [END spanner_create_database]
// [START spanner_create_database_with_version_retention_period]
void CreateDatabaseWithVersionRetentionPeriod(
google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
google::spanner::admin::database::v1::CreateDatabaseRequest request;
request.set_parent(database.instance().FullName());
request.set_create_statement("CREATE DATABASE `" + database.database_id() +
"`");
request.add_extra_statements("ALTER DATABASE `" + database.database_id() +
"` " +
"SET OPTIONS (version_retention_period='2h')");
request.add_extra_statements(R"""(
CREATE TABLE Singers (
SingerId INT64 NOT NULL,
FirstName STRING(1024),
LastName STRING(1024),
SingerInfo BYTES(MAX),
FullName STRING(2049)
AS (ARRAY_TO_STRING([FirstName, LastName], " ")) STORED
) PRIMARY KEY (SingerId))""");
request.add_extra_statements(R"""(
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)""");
auto db = client.CreateDatabase(request).get();
if (!db) throw std::move(db).status();
std::cout << "Database " << db->name() << " created.\n";
auto ddl = client.GetDatabaseDdl(db->name());
if (!ddl) throw std::move(ddl).status();
std::cout << "Database DDL is:\n" << ddl->DebugString();
}
// [END spanner_create_database_with_version_retention_period]
// [START spanner_create_database_with_default_leader]
void CreateDatabaseWithDefaultLeader(
google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id, std::string const& default_leader) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
google::spanner::admin::database::v1::CreateDatabaseRequest request;
request.set_parent(database.instance().FullName());
request.set_create_statement("CREATE DATABASE `" + database.database_id() +
"`");
request.add_extra_statements("ALTER DATABASE `" + database_id + "` " +
"SET OPTIONS (default_leader='" +
default_leader + "')");
auto db = client.CreateDatabase(request).get();
if (!db) throw std::move(db).status();
std::cout << "Database " << db->name() << " created.\n" << db->DebugString();
}
// [END spanner_create_database_with_default_leader]
// [START spanner_update_database_with_default_leader]
void UpdateDatabaseWithDefaultLeader(
google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id, std::string const& default_leader) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
std::vector<std::string> statements;
statements.push_back("ALTER DATABASE `" + database_id + "` " +
"SET OPTIONS (default_leader='" + default_leader + "')");
auto metadata =
client.UpdateDatabaseDdl(database.FullName(), std::move(statements))
.get();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "`default_leader` altered, new DDL metadata:\n"
<< metadata->DebugString();
}
// [END spanner_update_database_with_default_leader]
// [START spanner_create_table_with_datatypes]
void CreateTableWithDatatypes(
google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
auto metadata = client
.UpdateDatabaseDdl(database.FullName(), {R"""(
CREATE TABLE Venues (
VenueId INT64 NOT NULL,
VenueName STRING(100),
VenueInfo BYTES(MAX),
Capacity INT64,
AvailableDates ARRAY<DATE>,
LastContactDate DATE,
OutdoorVenue BOOL,
PopularityScore FLOAT64,
LastUpdateTime TIMESTAMP NOT NULL OPTIONS
(allow_commit_timestamp=true)
) PRIMARY KEY (VenueId))"""})
.get();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "`Venues` table created, new DDL:\n" << metadata->DebugString();
}
// [END spanner_create_table_with_datatypes]
// [START spanner_create_table_with_timestamp_column]
void CreateTableWithTimestamp(
google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
auto metadata = client
.UpdateDatabaseDdl(database.FullName(), {R"""(
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();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "`Performances` table created, new DDL:\n"
<< metadata->DebugString();
}
// [END spanner_create_table_with_timestamp_column]
// [START spanner_create_index]
void AddIndex(google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
auto metadata =
client
.UpdateDatabaseDdl(
database.FullName(),
{"CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)"})
.get();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "`AlbumsByAlbumTitle` Index successfully added, new DDL:\n"
<< metadata->DebugString();
}
// [END spanner_create_index]
//! [get-database]
void GetDatabase(google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
namespace spanner = ::google::cloud::spanner;
auto database = client.GetDatabase(
spanner::Database(project_id, instance_id, database_id).FullName());
if (!database) throw std::move(database).status();
std::cout << "Database metadata is:\n" << database->DebugString();
}
//! [get-database]
//! [START spanner_get_database_ddl] [get-database-ddl]
void GetDatabaseDdl(google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id,
std::string const& instance_id,
std::string const& database_id) {
namespace spanner = ::google::cloud::spanner;
auto database = client.GetDatabaseDdl(
spanner::Database(project_id, instance_id, database_id).FullName());
if (!database) throw std::move(database).status();
std::cout << "Database metadata is:\n" << database->DebugString();
}
//! [END spanner_get_database_ddl] [get-database-ddl]
//! [START spanner_add_and_drop_database_roles]
void AddAndDropDatabaseRoles(
google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id, std::string const& role_parent,
std::string const& role_child) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
std::vector<std::string> grant_statements = {
"CREATE ROLE " + role_parent,
"GRANT SELECT ON TABLE Singers TO ROLE " + role_parent,
"CREATE ROLE " + role_child,
"GRANT ROLE " + role_parent + " TO ROLE " + role_child,
};
auto metadata =
client.UpdateDatabaseDdl(database.FullName(), grant_statements).get();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "Created roles " << role_parent << " and " << role_child
<< " and granted privileges\n";
std::vector<std::string> revoke_statements = {
"REVOKE ROLE " + role_parent + " FROM ROLE " + role_child,
"DROP ROLE " + role_child,
};
metadata =
client.UpdateDatabaseDdl(database.FullName(), revoke_statements).get();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "Revoked privileges and dropped role " << role_child << "\n";
}
//! [END spanner_add_and_drop_database_roles]
//! [START spanner_read_data_with_database_role]
void ReadDataWithDatabaseRole(std::string const& project_id,
std::string const& instance_id,
std::string const& database_id,
std::string const& role) {
namespace spanner = ::google::cloud::spanner;
auto client = spanner::Client(spanner::MakeConnection(
spanner::Database(project_id, instance_id, database_id),
google::cloud::Options{}.set<spanner::SessionCreatorRoleOption>(role)));
spanner::SqlStatement select_star("SELECT * FROM Singers");
auto rows = client.ExecuteQuery(std::move(select_star));
using RowType =
std::tuple<std::int64_t, std::string, std::string, spanner::Bytes>;
for (auto& row : spanner::StreamOf<RowType>(rows)) {
if (!row) throw std::move(row).status();
std::cout << "SingerId: " << std::get<0>(*row) << ", "
<< "FirstName: " << std::get<1>(*row) << ", "
<< "LastName: " << std::get<2>(*row) << "\n";
}
}
//! [END spanner_read_data_with_database_role]
//! [START spanner_list_database_roles]
void ListDatabaseRoles(google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id,
std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
std::cout << "Database Roles are:\n";
for (auto& role : client.ListDatabaseRoles(database.FullName())) {
if (!role) throw std::move(role).status();
std::cout << role->name() << "\n";
}
}
//! [END spanner_list_database_roles]
//! [START spanner_enable_fine_grained_access]
void EnableFineGrainedAccess(
google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id, std::string const& iam_member,
std::string const& database_role, std::string const& title) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
google::iam::v1::GetIamPolicyRequest request;
request.set_resource(database.FullName());
request.mutable_options()->set_requested_policy_version(3);
auto policy = client.GetIamPolicy(request);
if (!policy) throw std::move(policy).status();
if (policy->version() < 3) policy->set_version(3);
auto& binding = *policy->add_bindings();
binding.set_role("roles/spanner.fineGrainedAccessUser");
binding.add_members(iam_member);
auto& condition = *binding.mutable_condition();
condition.set_expression("resource.name.endsWith(\"/databaseRoles/" +
database_role + "\")");
condition.set_title(title);
auto new_policy =
client.SetIamPolicy(database.FullName(), *std::move(policy));
if (!new_policy) throw std::move(new_policy).status();
std::cout << "Enabled fine-grained access in IAM. New policy has version "
<< new_policy->version() << "\n";
}
//! [END spanner_enable_fine_grained_access]
//! [update-database] [START spanner_add_column]
void AddColumn(google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
auto metadata =
client
.UpdateDatabaseDdl(
database.FullName(),
{"ALTER TABLE Albums ADD COLUMN MarketingBudget INT64"})
.get();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "Added MarketingBudget column\n";
}
//! [update-database] [END spanner_add_column]
// [START spanner_add_timestamp_column]
void AddTimestampColumn(
google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
auto metadata =
client
.UpdateDatabaseDdl(
database.FullName(),
{"ALTER TABLE Albums ADD COLUMN LastUpdateTime TIMESTAMP "
"OPTIONS (allow_commit_timestamp=true)"})
.get();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "Added LastUpdateTime column\n";
}
// [END spanner_add_timestamp_column]
// [START spanner_create_storing_index]
void AddStoringIndex(google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id,
std::string const& instance_id,
std::string const& database_id) {
google::cloud::spanner::Database database(project_id, instance_id,
database_id);
auto metadata = client
.UpdateDatabaseDdl(database.FullName(), {R"""(
CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle)
STORING (MarketingBudget))"""})
.get();
google::cloud::spanner_testing::LogUpdateDatabaseDdl( //! TODO(#4758)
client, database, metadata.status()); //! TODO(#4758)
if (!metadata) throw std::move(metadata).status();
std::cout << "`AlbumsByAlbumTitle2` Index successfully added, new DDL:\n"
<< metadata->DebugString();
}
// [END spanner_create_storing_index]
//! [START spanner_list_databases] [list-databases]
void ListDatabases(google::cloud::spanner_admin::DatabaseAdminClient client,
std::string const& project_id,
std::string const& instance_id) {
google::cloud::spanner::Instance in(project_id, instance_id);
int count = 0;
for (auto& database : client.ListDatabases(in.FullName())) {
if (!database) throw std::move(database).status();
std::cout << "Database " << database->name() << " full metadata:\n"
<< database->DebugString();
++count;
}
if (count == 0) {
std::cout << "No databases found in instance " << instance_id
<< " for project << " << project_id << "\n";
}
}
//! [END spanner_list_databases] [list-databases]
void ListDatabasesCommand(std::vector<std::string> argv) {
if (argv.size() != 2) {
throw std::runtime_error("list-databases <project-id> <instance-id>");
}
google::cloud::spanner_admin::DatabaseAdminClient client(
google::cloud::spanner_admin::MakeDatabaseAdminConnection());
ListDatabases(std::move(client), argv[0], argv[1]);
}