pub struct TimestampBound { /* private fields */ }

Implementations§

Examples found in repository?
src/client.rs (line 38)
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
    fn default() -> Self {
        ReadOnlyTransactionOption {
            timestamp_bound: TimestampBound::strong_read(),
            call_options: CallOptions::default(),
        }
    }
}

#[derive(Clone, Default)]
pub struct ReadWriteTransactionOption {
    pub begin_options: CallOptions,
    pub commit_options: CommitOptions,
}

#[derive(Clone, Debug)]
pub struct ChannelConfig {
    /// num_channels is the number of gRPC channels.
    pub num_channels: usize,
}

impl Default for ChannelConfig {
    fn default() -> Self {
        ChannelConfig { num_channels: 4 }
    }
}

/// ClientConfig has configurations for the client.
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// SessionPoolConfig is the configuration for session pool.
    pub session_config: SessionConfig,
    /// ChannelConfig is the configuration for gRPC connection.
    pub channel_config: ChannelConfig,
    /// Overriding service endpoint
    pub endpoint: String,
    /// Runtime project
    pub project: ProjectOptions,
}

impl Default for ClientConfig {
    fn default() -> Self {
        let mut config = ClientConfig {
            channel_config: Default::default(),
            session_config: Default::default(),
            endpoint: SPANNER.to_string(),
            project: ProjectOptions::new("SPANNER_EMULATOR_HOST"),
        };
        config.session_config.min_opened = config.channel_config.num_channels * 4;
        config.session_config.max_opened = config.channel_config.num_channels * 100;
        config
    }
}

impl ClientConfig {
    pub fn project(&mut self, project: Project) {
        if let ProjectOptions::Project(_) = self.project {
            self.project = ProjectOptions::Project(Some(project))
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum InitializationError {
    #[error(transparent)]
    FailedToCreateSessionPool(#[from] Status),

    #[error(transparent)]
    FailedToCreateChannelPool(#[from] google_cloud_gax::conn::Error),

    #[error(transparent)]
    Auth(#[from] google_cloud_auth::error::Error),

    #[error("invalid config: {0}")]
    InvalidConfig(String),
}

#[derive(thiserror::Error, Debug)]
pub enum TxError {
    #[error(transparent)]
    GRPC(#[from] Status),

    #[error(transparent)]
    InvalidSession(#[from] SessionError),
}

impl TryAs<Status> for TxError {
    fn try_as(&self) -> Option<&Status> {
        match self {
            TxError::GRPC(s) => Some(s),
            _ => None,
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum RunInTxError {
    #[error(transparent)]
    GRPC(#[from] Status),

    #[error(transparent)]
    InvalidSession(#[from] SessionError),

    #[error(transparent)]
    ParseError(#[from] crate::row::Error),

    #[error(transparent)]
    Any(#[from] anyhow::Error),
}

impl From<TxError> for RunInTxError {
    fn from(err: TxError) -> Self {
        match err {
            TxError::GRPC(err) => RunInTxError::GRPC(err),
            TxError::InvalidSession(err) => RunInTxError::InvalidSession(err),
        }
    }
}

impl TryAs<Status> for RunInTxError {
    fn try_as(&self) -> Option<&Status> {
        match self {
            RunInTxError::GRPC(e) => Some(e),
            _ => None,
        }
    }
}

/// Client is a client for reading and writing data to a Cloud Spanner database.
/// A client is safe to use concurrently, except for its Close method.
pub struct Client {
    sessions: Arc<SessionManager>,
}

impl Clone for Client {
    fn clone(&self) -> Self {
        Client {
            sessions: Arc::clone(&self.sessions),
        }
    }
}

impl Client {
    /// new creates a client to a database. A valid database name has
    /// the form projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID.
    pub async fn new(database: impl Into<String>) -> Result<Self, InitializationError> {
        Client::new_with_config(database, Default::default()).await
    }

    /// new creates a client to a database. A valid database name has
    /// the form projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID.
    pub async fn new_with_config(
        database: impl Into<String>,
        config: ClientConfig,
    ) -> Result<Self, InitializationError> {
        if config.session_config.max_opened > config.channel_config.num_channels * 100 {
            return Err(InitializationError::InvalidConfig(format!(
                "max session size is {} because max session size is 100 per gRPC connection",
                config.channel_config.num_channels * 100
            )));
        }

        let environment = Environment::from_project(config.project).await?;
        let pool_size = config.channel_config.num_channels;
        let conn_pool = ConnectionManager::new(pool_size, &environment, config.endpoint.as_str()).await?;
        let session_manager = SessionManager::new(database, conn_pool, config.session_config).await?;

        Ok(Client {
            sessions: Arc::new(session_manager),
        })
    }

    /// Close closes the client.
    pub async fn close(&self) {
        self.sessions.close().await;
    }

    /// single provides a read-only snapshot transaction optimized for the case
    /// where only a single read or query is needed.  This is more efficient than
    /// using read_only_transaction for a single read or query.
    /// ```
    /// use google_cloud_spanner::key::Key;
    /// use google_cloud_spanner::statement::ToKind;
    /// use google_cloud_spanner::client::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), anyhow::Error> {
    ///     const DATABASE: &str = "projects/local-project/instances/test-instance/databases/local-database";
    ///     let client = Client::new(DATABASE).await?;
    ///
    ///     let mut tx = client.single().await?;
    ///     let iter1 = tx.read("Guild",&["GuildID", "OwnerUserID"], vec![
    ///         Key::new(&"pk1"),
    ///         Key::new(&"pk2")
    ///     ]).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn single(&self) -> Result<ReadOnlyTransaction, TxError> {
        self.single_with_timestamp_bound(TimestampBound::strong_read()).await
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Converts to this type from a reference to the input type.
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Wrap the input message T in a tonic::Request
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more