google_cloud_rust/
spanner.rs

1// Copyright 2020 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//     https://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
15//! Spanner client.
16
17use std::sync::Arc;
18
19use google_cloud_rust_raw::spanner::v1::{
20    spanner::{CreateSessionRequest, Session},
21    spanner_grpc::SpannerClient,
22};
23use grpcio::{CallOption, ChannelBuilder, ChannelCredentials, EnvBuilder, MetadataBuilder};
24
25#[allow(dead_code)]
26pub struct Client {
27    database: String,
28    client: SpannerClient,
29    session: Session,
30}
31
32impl Client {
33    /// Creates a new Spanner client.
34    ///
35    /// # Examples
36    ///
37    /// ```no_run
38    /// use google_cloud_rust::spanner;
39    ///
40    /// let db = "projects/my_project/instances/my_instance/databases/my_database";
41    /// let client = spanner::Client::new(db);
42    /// ```
43    pub fn new(database: &str) -> crate::Result<Client> {
44        let database = database.to_string();
45        let endpoint = "spanner.googleapis.com:443";
46
47        // Set up the gRPC environment.
48        let env = Arc::new(EnvBuilder::new().build());
49        let creds = ChannelCredentials::google_default_credentials()?;
50
51        // Create a Spanner client.
52        let chan = ChannelBuilder::new(Arc::clone(&env))
53            .max_send_message_len(100 << 20)
54            .max_receive_message_len(100 << 20)
55            .set_credentials(creds)
56            .connect(&endpoint);
57        let client = SpannerClient::new(chan);
58
59        let mut req = CreateSessionRequest::new();
60        req.set_database(database.to_string());
61        let mut meta = MetadataBuilder::new();
62        meta.add_str("google-cloud-resource-prefix", &database)?;
63        meta.add_str("x-goog-api-client", "googleapis-rs")?;
64        let opt = CallOption::default().headers(meta.build());
65        let session = client.create_session_opt(&req, opt)?;
66
67        Ok(Client {
68            database,
69            client,
70            session,
71        })
72    }
73}