Google Cloud Spanner C++ Client
A C++ Client Library for Google Cloud Spanner
database_environment.cc
Go to the documentation of this file.
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
18 #include "google/cloud/internal/getenv.h"
19 #include "google/cloud/testing_util/assert_ok.h"
20 
21 namespace google {
22 namespace cloud {
23 namespace spanner_testing {
24 inline namespace SPANNER_CLIENT_NS {
25 
26 google::cloud::spanner::Database* DatabaseEnvironment::db_;
27 google::cloud::internal::DefaultPRNG* DatabaseEnvironment::generator_;
28 
29 void DatabaseEnvironment::SetUp() {
30  auto project_id =
31  google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value_or("");
32  ASSERT_FALSE(project_id.empty());
33  auto instance_id =
34  google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_SPANNER_INSTANCE")
35  .value_or("");
36  ASSERT_FALSE(instance_id.empty());
37 
38  generator_ = new google::cloud::internal::DefaultPRNG(
39  google::cloud::internal::MakeDefaultPRNG());
40  auto database_id = spanner_testing::RandomDatabaseName(*generator_);
41 
42  db_ = new spanner::Database(project_id, instance_id, database_id);
43 
44  std::cout << "Creating database and table " << std::flush;
45  spanner::DatabaseAdminClient admin_client;
46  auto database_future =
47  admin_client.CreateDatabase(*db_, {R"""(CREATE TABLE Singers (
48  SingerId INT64 NOT NULL,
49  FirstName STRING(1024),
50  LastName STRING(1024)
51  ) PRIMARY KEY (SingerId))"""});
52  int i = 0;
53  int const timeout = 120;
54  while (++i < timeout) {
55  auto status = database_future.wait_for(std::chrono::seconds(1));
56  if (status == std::future_status::ready) break;
57  std::cout << '.' << std::flush;
58  }
59  if (i >= timeout) {
60  std::cout << "TIMEOUT\n";
61  FAIL();
62  }
63  auto database = database_future.get();
64  ASSERT_STATUS_OK(database);
65  std::cout << "DONE\n";
66 }
67 
68 void DatabaseEnvironment::TearDown() {
69  spanner::DatabaseAdminClient admin_client;
70  auto drop_status = admin_client.DropDatabase(*db_);
71  EXPECT_STATUS_OK(drop_status);
72 }
73 
74 } // namespace SPANNER_CLIENT_NS
75 } // namespace spanner_testing
76 } // namespace cloud
77 } // namespace google
std::string RandomDatabaseName(google::cloud::internal::DefaultPRNG &generator)
Create a random database name given a PRNG generator.
#define SPANNER_CLIENT_NS
Definition: version.h:22