xitca-postgres 0.4.0

an async postgres client
Documentation
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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use core::{
    future::Future,
    mem,
    num::NonZeroUsize,
    ops::Deref,
    pin::Pin,
    task::{Context, Poll},
};

use lru::LruCache;
use tokio::sync::SemaphorePermit;
use xitca_io::bytes::BytesMut;

use crate::{
    BoxedFuture,
    client::{Client, ClientBorrow, ClientBorrowMut},
    copy::{r#Copy, CopyIn, CopyOut},
    driver::codec::AsParams,
    error::Error,
    execute::Execute,
    query::{RowAffected, RowStreamOwned},
    session::Session,
    statement::{Statement, StatementNamed, StatementQuery},
    transaction::{Transaction, TransactionBuilder},
};

use super::Pool;

/// a RAII type for connection. it manages the lifetime of connection and it's [`CachedStatement`] cache.
/// a set of public is exposed to interact with them.
///
/// # Caching
/// PoolConnection contains cache set of [`CachedStatement`] to speed up regular used sql queries. when calling
/// [`Execute::execute`] on a [`StatementNamed`] with &[`PoolConnection`] the pool connection does nothing
/// special and function the same as a regular [`Client`]. In order to utilize the cache caller must execute
/// the named statement with &mut [`PoolConnection`]. With a mutable reference of pool connection it will do
/// local cache look up for statement and hand out one in the type of [`CachedStatement`] if any found. If no
/// copy is found in the cache pool connection will prepare a new statement and insert it into the cache.
///
/// ## Examples
/// ```
/// # use xitca_postgres::{pool::Pool, Execute, Error, Statement};
/// # async fn cached(pool: &Pool) -> Result<(), Error> {
/// let mut conn = pool.get().await?;
/// // prepare a statement without caching
/// Statement::named("SELECT 1", &[]).execute(&conn).await?;
/// // prepare a statement with caching from conn.
/// Statement::named("SELECT 1", &[]).execute(&mut conn).await?;
/// # Ok(())
/// # }
/// ```
///
/// * When to use caching or not:
/// - query statement repeatedly called intensely can benefit from cache.
/// - query statement with low latency requirement can benefit from upfront cache.
/// - rare query statement can benefit from no caching by reduce resource usage from the server side. For low
///   latency of rare query consider use [`StatementNamed::bind`] as alternative.
pub struct PoolConnection<'a> {
    pub(super) pool: &'a Pool,
    pub(super) conn: Option<PoolClient>,
    pub(super) _permit: SemaphorePermit<'a>,
}

impl<'a> PoolConnection<'a> {
    /// function the same as [`Client::transaction`]
    #[inline]
    pub fn transaction(&mut self) -> impl Future<Output = Result<Transaction<'_, Self>, Error>> + Send {
        TransactionBuilder::new().begin(self)
    }

    /// owned version of [`PoolConnection::transaction`]
    #[inline]
    pub fn transaction_owned(self) -> impl Future<Output = Result<Transaction<'a, Self>, Error>> + Send {
        TransactionBuilder::new().begin_owned(self)
    }

    /// function the same as [`Client::copy_in`]
    #[inline]
    pub fn copy_in(&mut self, stmt: &Statement) -> impl Future<Output = Result<CopyIn<'_, Self>, Error>> + Send {
        CopyIn::new(self, stmt)
    }

    /// function the same as [`Client::copy_out`]
    #[inline]
    pub async fn copy_out(&self, stmt: &Statement) -> Result<CopyOut, Error> {
        CopyOut::new(self, stmt).await
    }

    /// a shortcut to move and take ownership of self.
    /// an important behavior of [PoolConnection] is it supports pipelining. eagerly drop it after usage can
    /// contribute to more queries being pipelined. especially before any `await` point.
    ///
    /// # Examples
    /// ```rust
    /// use xitca_postgres::{pool::Pool, Error, Execute};
    ///
    /// async fn example(pool: &Pool) -> Result<(), Error> {
    ///     // get a connection from pool and start a query.
    ///     let mut conn = pool.get().await?;
    ///
    ///     "SELECT *".execute(&conn).await?;
    ///     
    ///     // connection is kept across await point. making it unusable to other concurrent
    ///     // callers to example function. and no pipelining will happen until it's released.
    ///     conn = conn;
    ///
    ///     // start another query but this time consume ownership and when res is returned
    ///     // connection is dropped and went back to pool.
    ///     let res = "SELECT *".execute(&conn.consume());
    ///
    ///     // connection can't be used anymore in this scope but other concurrent callers
    ///     // to example function is able to use it and if they follow the same calling
    ///     // convention pipelining could happen and reduce syscall overhead.
    ///
    ///     // let res = "SELECT *".execute(&conn);
    ///
    ///     // without connection the response can still be collected asynchronously
    ///     res.await?;
    ///
    ///     // therefore a good calling convention for independent queries could be:
    ///     let conn = pool.get().await?;
    ///     let res1 = "SELECT *".execute(&conn);
    ///     let res2 = "SELECT *".execute(&conn);
    ///     let res3 = "SELECT *".execute(&conn.consume());
    ///
    ///     // all three queries can be pipelined into a single write syscall. and possibly
    ///     // even more can be pipelined after conn.consume() is called if there are concurrent
    ///     // callers use the same connection.
    ///     
    ///     res1.await?;
    ///     res2.await?;
    ///     res3.await?;
    ///
    ///     // it should be noted that pipelining is an optional crate feature for some potential
    ///     // performance gain.
    ///     // it's totally fine to ignore and use the apis normally with zero thought put into it.
    ///
    ///     Ok(())
    /// }
    /// ```
    #[inline(always)]
    pub fn consume(self) -> Self {
        self
    }

    /// function the same as [`Client::cancel_token`]
    pub fn cancel_token(&self) -> Session {
        self.conn().client.cancel_token()
    }

    fn insert_cache<'c>(cache: &'c mut Cache, cli: &Client, named: &str, stmt: Statement) -> &'c CachedStatement {
        if let Some((_, stmt)) = cache.push(Box::from(named), CachedStatement { stmt }) {
            drop(stmt.stmt.into_guarded(&cli));
        }
        cache.peek_mru().unwrap().1
    }

    fn conn(&self) -> &PoolClient {
        self.conn.as_ref().unwrap()
    }

    fn conn_mut(&mut self) -> &mut PoolClient {
        self.conn.as_mut().unwrap()
    }
}

impl ClientBorrow for PoolConnection<'_> {
    #[inline]
    fn borrow_cli_ref(&self) -> &Client {
        &self.conn().client
    }
}

impl ClientBorrowMut for PoolConnection<'_> {
    #[inline]
    fn borrow_cli_mut(&mut self) -> &mut Client {
        &mut self.conn_mut().client
    }
}

impl r#Copy for PoolConnection<'_> {
    #[inline]
    fn send_one_way<F>(&self, func: F) -> Result<(), Error>
    where
        F: FnOnce(&mut BytesMut) -> Result<(), Error>,
    {
        self.conn().client.send_one_way(func)
    }
}

impl Drop for PoolConnection<'_> {
    fn drop(&mut self) {
        let conn = self.conn.take().unwrap();
        self.pool.conn.lock().unwrap().push_back(conn);
    }
}

/// Cached [`Statement`] from [`PoolConnection`]
///
/// Can be used for the same purpose without the ability to cancel actively
/// It's lifetime is managed by [`PoolConnection`]
pub struct CachedStatement {
    stmt: Statement,
}

impl Clone for CachedStatement {
    fn clone(&self) -> Self {
        Self {
            stmt: self.stmt.duplicate(),
        }
    }
}

impl Deref for CachedStatement {
    type Target = Statement;

    fn deref(&self) -> &Self::Target {
        &self.stmt
    }
}

pub(super) struct PoolClient {
    client: Client,
    cache: Cache,
}

impl PoolClient {
    pub(super) fn closed(&self) -> bool {
        self.client.closed()
    }
}

type Cache = LruCache<Box<str>, CachedStatement>;

impl PoolClient {
    pub(super) fn new(client: Client, cap: NonZeroUsize) -> Self {
        Self {
            client,
            cache: LruCache::new(cap),
        }
    }
}

impl<'c, E> Execute<&'c PoolConnection<'_>> for E
where
    E: Execute<&'c Client>,
{
    type ExecuteOutput = E::ExecuteOutput;
    type QueryOutput = E::QueryOutput;

    #[inline]
    fn execute(self, cli: &'c PoolConnection<'_>) -> Self::ExecuteOutput {
        E::execute(self, cli.borrow_cli_ref())
    }

    #[inline]
    fn query(self, cli: &'c PoolConnection<'_>) -> Self::QueryOutput {
        E::query(self, cli.borrow_cli_ref())
    }
}

impl<'c, 's> Execute<&'c mut PoolConnection<'_>> for StatementNamed<'s>
where
    's: 'c,
{
    type ExecuteOutput = StatementCacheFuture<'c>;
    type QueryOutput = Self::ExecuteOutput;

    fn execute(self, cli: &'c mut PoolConnection) -> Self::ExecuteOutput {
        match cli.conn_mut().cache.get(self.stmt) {
            Some(stmt) => StatementCacheFuture::Cached(stmt.clone()),
            None => StatementCacheFuture::Prepared(Box::pin(async move {
                let conn = cli.conn_mut();
                let name = self.stmt;
                let stmt = self.execute(&conn.client).await?.leak();
                Ok(PoolConnection::insert_cache(&mut conn.cache, &conn.client, name, stmt).clone())
            })),
        }
    }

    #[inline]
    fn query(self, cli: &'c mut PoolConnection) -> Self::QueryOutput {
        self.execute(cli)
    }
}

pub enum StatementCacheFuture<'c> {
    Cached(CachedStatement),
    Prepared(BoxedFuture<'c, Result<CachedStatement, Error>>),
    Done,
}

impl Future for StatementCacheFuture<'_> {
    type Output = Result<CachedStatement, Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        match mem::replace(this, Self::Done) {
            Self::Cached(stmt) => Poll::Ready(Ok(stmt)),
            Self::Prepared(mut fut) => {
                let res = fut.as_mut().poll(cx);
                if res.is_pending() {
                    drop(mem::replace(this, Self::Prepared(fut)));
                }
                res
            }
            Self::Done => panic!("StatementCacheFuture polled after finish"),
        }
    }
}

#[cfg(not(feature = "nightly"))]
impl<'c, 's, P> Execute<&'c mut PoolConnection<'_>> for StatementQuery<'s, P>
where
    P: AsParams + Send + 'c,
    's: 'c,
{
    type ExecuteOutput = BoxedFuture<'c, Result<RowAffected, Error>>;
    type QueryOutput = BoxedFuture<'c, Result<RowStreamOwned, Error>>;

    fn execute(self, conn: &'c mut PoolConnection<'_>) -> Self::ExecuteOutput {
        Box::pin(async move {
            let StatementQuery { stmt, types, params } = self;

            let conn = conn.conn_mut();

            let stmt = match conn.cache.get(stmt) {
                Some(stmt) => stmt,
                None => {
                    let prepared_stmt = Statement::named(stmt, types).execute(&conn.client).await?.leak();
                    PoolConnection::insert_cache(&mut conn.cache, &conn.client, stmt, prepared_stmt)
                }
            };

            stmt.bind(params).query(&conn.client).await.map(RowAffected::from)
        })
    }

    fn query(self, conn: &'c mut PoolConnection<'_>) -> Self::QueryOutput {
        Box::pin(async move {
            let StatementQuery { stmt, types, params } = self;

            let conn = conn.conn_mut();

            let stmt = match conn.cache.get(stmt) {
                Some(stmt) => stmt,
                None => {
                    let prepared_stmt = Statement::named(stmt, types).execute(&conn.client).await?.leak();
                    PoolConnection::insert_cache(&mut conn.cache, &conn.client, stmt, prepared_stmt)
                }
            };

            stmt.bind(params).into_owned().query(&conn.client).await
        })
    }
}

#[cfg(feature = "nightly")]
impl<'c, 's, 'p, P> Execute<&'c mut PoolConnection<'p>> for StatementQuery<'s, P>
where
    P: AsParams + Send + 'c,
    's: 'c,
    'p: 'c,
{
    type ExecuteOutput = impl Future<Output = Result<RowAffected, Error>> + Send + 'c;
    type QueryOutput = impl Future<Output = Result<RowStreamOwned, Error>> + Send + 'c;

    fn execute(self, conn: &'c mut PoolConnection<'p>) -> Self::ExecuteOutput {
        async move {
            let StatementQuery { stmt, types, params } = self;

            let conn = conn.conn_mut();

            let stmt = match conn.cache.get(stmt) {
                Some(stmt) => stmt,
                None => {
                    let prepared_stmt = Statement::named(stmt, types).execute(&conn.client).await?.leak();
                    PoolConnection::insert_cache(&mut conn.cache, &conn.client, stmt, prepared_stmt)
                }
            };

            stmt.bind(params).query(&conn.client).await.map(RowAffected::from)
        }
    }

    fn query(self, conn: &'c mut PoolConnection<'p>) -> Self::QueryOutput {
        async move {
            let StatementQuery { stmt, types, params } = self;

            let conn = conn.conn_mut();

            let stmt = match conn.cache.get(stmt) {
                Some(stmt) => stmt,
                None => {
                    let prepared_stmt = Statement::named(stmt, types).execute(&conn.client).await?.leak();
                    PoolConnection::insert_cache(&mut conn.cache, &conn.client, stmt, prepared_stmt)
                }
            };

            stmt.bind(params).into_owned().query(&conn.client).await
        }
    }
}