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
use TryStream;
use fmt;
use ;
/// Newtype wrapper around dynamically-typed, JSON-compatible [`pbjson_types::Value`]s.
///
/// This implements [`tokio_postgres::types::ToSql`] as a means of interfacing between the loose types of
/// JSON and the richer type system encoded in the Postgres protocol.
;
/// gRPC-compatible connection behavior across database connection types. All inputs and outputs
/// are based on protobuf's JSON-compatible well-known-types [`pbjson_types::Struct`] and
/// [`pbjson_types::Value`].
///
/// #### Example:
///
/// ```rust
/// use postgrpc::pools::{Connection, Parameter};
/// use tonic::{Row, Status};
///
/// // implementing a real StructStream (a fallible stream of Structs)
/// // is an exercise left to the reader
/// struct StructStream;
///
/// impl From<Vec<Row>> for StructStream {
/// // also an exercise for the reader
/// }
///
/// #[async_trait]
/// impl Connection for tokio_postgres::Client {
/// type Error = Status;
/// type RowStream = StructStream;
///
/// async fn query(
/// &self,
/// statement: &str,
/// parameters: &[Parameter],
/// ) -> Result<Self::RowStream, Self::Error> {
/// // Parameter implements ToSql, so can be used directly in query()
/// let rows: Vec<_> = self
/// .query(statement, parameters)
/// .await
/// .map_error(|error| Status::invalid_argument(error.to_string()))?;
///
/// // it's best to stream rows instead of collecting them into a Vec
/// // but this is only meant to be a quick example
/// Ok(StructStream::from(rows))
/// }
///
/// #[tracing::instrument(skip(self))]
/// async fn batch(&self, query: &str) -> Result<(), Self::Error> {
/// tracing::trace!("Executing batch query on Connection");
/// self.batch_execute(query).await.map_err(|error| Status::invalid_argument(error.to_string()))
/// }
/// }
/// ```
/// Connection pool behavior that can be customized across async pool implementations.
///
/// The key difference between a [`Pool`] and most other connection pools is the way new
/// connections are accessed: by building connection logic around a `Key` that can be derived from
/// a [`tonic::Request`], all connection isolation and preparation can be handled internally to the
/// pool. Furthermore, pools don't _have_ to be traditional pools, but can hand out shared access
/// to a single [`Connection`].
///
/// #### Example:
///
/// ```
/// use postgrpc::pools::{Pool, Connection};
/// use std::collections::BTreeMap;
/// use tokio::sync::RwLock;
/// use uuid::Uuid;
/// use tonic::Status;
///
/// // a simple connection wrapper
/// // (implementing postgrpc::Connection is an exercise for the reader)
/// #[derive(Clone)]
/// struct MyConnection(Arc<tokio_postgres::Client>);
///
/// // a toy pool wrapping a collection of tokio_postgres::Clients
/// // accessible by unique IDs that are provided by the caller
/// struct MyPool {
/// connections: RwLock<BTreeMap<Uuid, MyConnection>>,
/// config: tokio_postgres::config::Config
/// }
///
/// #[postgrpc::async_trait]
/// impl Pool for MyPool {
/// type Key: Uuid;
/// type Connection: MyConnection;
/// type Error: Status;
///
/// async fn get_connection(&self, key: Self::Key) -> Result<Self::Connection, Self::Error> {
/// // get a connection from the pool or store one for later
/// let connections = self.connections.read().await;
///
/// match connections.get(&key) {
/// Some(connection) => Ok(Arc::clone(connection.0)),
/// None => {
/// // drop the previous lock on the connections
/// drop(connections);
///
/// // connect to the database using the configuration
/// let (client, connection) = self
/// .config
/// .connect(tokio_postgres::NoTls)
/// .map_error(|error| Status::internal(error.to_string()))?;
///
/// // spawn the raw connection off onto an executor
/// tokio::spawn(async move {
/// if let Err(error) = connection.await {
/// eprintln!("connection error: {}", error);
/// }
/// });
///
/// // store a reference to the connection for later
/// let connection = MyConnection(Arc::new(client));
/// self.connections.write().await.insert(key, connection);
///
/// // return another reference to the connection for use
/// Ok(connection)
/// }
/// }
/// }
/// }
/// ```