Google Cloud Spanner C++ Client
A C++ Client Library for Google Cloud Spanner
sql_statement.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 
16 #include <algorithm>
17 
18 namespace google {
19 namespace cloud {
20 namespace spanner {
21 inline namespace SPANNER_CLIENT_NS {
22 
23 namespace internal {
24 SqlStatementProto ToProto(SqlStatement s) {
25  SqlStatementProto statement_proto;
26  statement_proto.set_sql(std::move(s.statement_));
27  if (!s.params_.empty()) {
28  auto& values = *statement_proto.mutable_params()->mutable_fields();
29  auto& types = *statement_proto.mutable_param_types();
30  for (auto& param : s.params_) {
31  auto type_and_value = internal::ToProto(std::move(param.second));
32  values[param.first] = std::move(type_and_value.second);
33  types[param.first] = std::move(type_and_value.first);
34  }
35  }
36  return statement_proto;
37 }
38 } // namespace internal
39 
40 std::vector<std::string> SqlStatement::ParameterNames() const {
41  std::vector<std::string> keys;
42  keys.reserve(params_.size());
43  for (auto const& p : params_) {
44  keys.push_back(p.first);
45  }
46  return keys;
47 }
48 
49 google::cloud::StatusOr<Value> SqlStatement::GetParameter(
50  std::string const& parameter_name) const {
51  auto iter = params_.find(parameter_name);
52  if (iter != params_.end()) {
53  return iter->second;
54  }
55  return Status(StatusCode::kNotFound, "No such parameter: " + parameter_name);
56 }
57 
58 std::ostream& operator<<(std::ostream& os, SqlStatement const& stmt) {
59  os << stmt.statement_;
60  for (auto const& param : stmt.params_) {
61  os << "\n[param]: {" << param.first << "=" << param.second << "}";
62  }
63  return os;
64 }
65 
66 } // namespace SPANNER_CLIENT_NS
67 } // namespace spanner
68 } // namespace cloud
69 } // namespace google
std::ostream & operator<<(std::ostream &os, SqlStatement const &stmt)
Contains all the Cloud Spanner C++ client types and functions.
#define SPANNER_CLIENT_NS
Definition: version.h:22
Represents a potentially parameterized SQL statement.
Definition: sql_statement.h:55