Skip to main content

oxtel_sql/sqlx/
v0_9.rs

1//! sqlx 0.9. See the [`sqlx`](super) module for what's recorded.
2
3use std::fmt;
4use std::ops::{Deref, DerefMut};
5use std::sync::Arc;
6use std::time::Instant;
7
8use futures_core::future::BoxFuture;
9use futures_core::stream::BoxStream;
10use futures_util::TryStreamExt;
11use sqlx::database::Database;
12use sqlx::error::BoxDynError;
13use sqlx::pool::PoolConnection;
14use sqlx::{
15    ConnectOptions, Connection as _, Describe, Either, Error, Execute, Executor, SqlStr,
16    Statement as _,
17};
18use sqlx_0_9 as sqlx;
19
20use super::{Fail, QueryCall, Recorded, Target, has_url, record_one, statement};
21use crate::pool::{Lease, Waiting};
22use crate::record::analyze;
23
24/// What a query yields as it runs: a statement's result, or a row.
25type Step<DB> = Either<<DB as Database>::QueryResult, <DB as Database>::Row>;
26
27fn is_row<DB: Database>(step: &Step<DB>) -> bool {
28    step.is_right()
29}
30
31fn one_row<R>(row: &Option<R>) -> u64 {
32    u64::from(row.is_some())
33}
34
35fn no_rows<T>(_: &T) -> u64 {
36    0
37}
38
39fn fail(error: &Error) -> Fail {
40    let kind = match error {
41        Error::Database(e) => return Fail::new(e.code().map(|c| c.into_owned()), Some("Database")),
42        Error::Configuration(_) => "Configuration",
43        Error::InvalidArgument(_) => "InvalidArgument",
44        Error::Io(_) => "Io",
45        Error::Tls(_) => "Tls",
46        Error::Protocol(_) => "Protocol",
47        Error::RowNotFound => "RowNotFound",
48        Error::TypeNotFound { .. } => "TypeNotFound",
49        Error::ColumnIndexOutOfBounds { .. } => "ColumnIndexOutOfBounds",
50        Error::ColumnNotFound(_) => "ColumnNotFound",
51        Error::ColumnDecode { .. } => "ColumnDecode",
52        Error::Encode(_) => "Encode",
53        Error::Decode(_) => "Decode",
54        Error::AnyDriverError(_) => "AnyDriverError",
55        Error::PoolTimedOut => "PoolTimedOut",
56        Error::PoolClosed => "PoolClosed",
57        Error::WorkerCrashed => "WorkerCrashed",
58        Error::InvalidSavePointStatement => "InvalidSavePointStatement",
59        Error::BeginFailed => "BeginFailed",
60        _ => return Fail::new(None, None),
61    };
62    Fail::new(None, Some(kind))
63}
64
65/// In sqlx 0.9, reading a query's text consumes the query, so it's read
66/// as sqlx reads it: the query runs wrapped in this, which keeps the text.
67struct Watched<E> {
68    inner: E,
69    statement: super::Statement,
70}
71
72/// Wrap `query`, returning where its text will be kept.
73fn watch<E>(query: E) -> (super::Statement, Watched<E>) {
74    let statement = statement(None);
75    let watched = Watched {
76        inner: query,
77        statement: std::sync::Arc::clone(&statement),
78    };
79    (statement, watched)
80}
81
82fn remember(statement: &super::Statement, sql: &str) {
83    let mut slot = statement.lock().unwrap_or_else(|e| e.into_inner());
84    if slot.is_none() {
85        *slot = Some(analyze(sql));
86    }
87}
88
89impl<'q, DB: Database, E: Execute<'q, DB>> Execute<'q, DB> for Watched<E> {
90    fn sql(self) -> SqlStr {
91        let sql = self.inner.sql();
92        remember(&self.statement, sql.as_str());
93        sql
94    }
95
96    fn statement(&self) -> Option<&DB::Statement> {
97        let statement = self.inner.statement();
98        if let Some(prepared) = statement {
99            remember(&self.statement, prepared.sql().as_str());
100        }
101        statement
102    }
103
104    fn take_arguments(&mut self) -> Result<Option<DB::Arguments>, BoxDynError> {
105        self.inner.take_arguments()
106    }
107
108    fn persistent(&self) -> bool {
109        self.inner.persistent()
110    }
111}
112
113/// An instrumented sqlx pool. Run queries on `&pool`; [`begin`](Pool::begin)
114/// and [`acquire`](Pool::acquire) give an instrumented transaction or
115/// connection. It dereferences to sqlx's [`Pool`](sqlx::Pool).
116pub struct Pool<DB: Database> {
117    inner: sqlx::Pool<DB>,
118    target: Arc<Target>,
119}
120
121/// A connection out of the pool, and the lease that records its use when
122/// it's back. `conn` is declared first, so it's returned before the lease
123/// ends.
124struct Leased<DB: Database> {
125    conn: PoolConnection<DB>,
126    _lease: Lease,
127}
128
129impl<DB: Database> Pool<DB> {
130    /// Instrument a pool. The database's name and server come from its
131    /// connection options; its name in the pool metrics is
132    /// `server.address:server.port/db.namespace`.
133    pub fn new(pool: sqlx::Pool<DB>) -> Self {
134        crate::record::describe_metrics();
135        crate::pool::describe_metrics();
136        let url = has_url(DB::NAME).then(|| pool.connect_options().to_url_lossy());
137        let target = Target::new(
138            DB::NAME,
139            url.as_ref().map(|u| (u.host_str(), u.port(), u.path())),
140        );
141        Pool {
142            inner: pool,
143            target: Arc::new(target),
144        }
145    }
146
147    /// Name the pool in its metrics, for a program with more than one.
148    pub fn with_name(mut self, name: &str) -> Self {
149        self.target = Arc::new(self.target.with_pool_name(name));
150        self
151    }
152
153    /// The wrapped pool.
154    pub fn get_ref(&self) -> &sqlx::Pool<DB> {
155        &self.inner
156    }
157
158    /// Take a connection from the pool, instrumented.
159    pub async fn acquire(&self) -> Result<Connection<DB>, Error> {
160        Ok(Connection {
161            leased: self.lease().await?,
162            target: Arc::clone(&self.target),
163        })
164    }
165
166    /// Start a transaction. Its `BEGIN`, which includes waiting for a
167    /// connection, is recorded as a call.
168    pub async fn begin(&self) -> Result<Transaction<'static, DB>, Error> {
169        let call = QueryCall::start(&self.target, statement(Some(analyze("BEGIN"))));
170        let inner = record_one(call, self.inner.begin(), no_rows, fail).await?;
171        sample(&self.inner, &self.target.pool_name);
172        Ok(Transaction {
173            inner,
174            target: Arc::clone(&self.target),
175            _lease: Some(self.lease_for_use()),
176        })
177    }
178
179    async fn lease(&self) -> Result<Leased<DB>, Error> {
180        let name = &self.target.pool_name;
181        let waiting = Waiting::start(name);
182        let started = Instant::now();
183        let result = self.inner.acquire().await;
184        drop(waiting);
185        crate::pool::record_wait(name, started, matches!(&result, Err(Error::PoolTimedOut)));
186        sample(&self.inner, name);
187        Ok(Leased {
188            conn: result?,
189            _lease: self.lease_for_use(),
190        })
191    }
192
193    fn lease_for_use(&self) -> Lease {
194        let (pool, name) = (self.inner.clone(), Arc::clone(&self.target.pool_name));
195        Lease::start(&self.target.pool_name, move || {
196            sample_returning(&pool, &name)
197        })
198    }
199}
200
201/// Set the connection counts and the pool's size limit.
202fn sample<DB: Database>(pool: &sqlx::Pool<DB>, name: &str) {
203    record(pool, name, pool.num_idle());
204}
205
206/// The counts as a connection is given back. sqlx returns it to the pool
207/// in a task of its own, so it isn't idle yet; count it as idle. Where that
208/// task has already run, the next sample puts it right.
209fn sample_returning<DB: Database>(pool: &sqlx::Pool<DB>, name: &str) {
210    record(pool, name, pool.num_idle() + 1);
211}
212
213fn record<DB: Database>(pool: &sqlx::Pool<DB>, name: &str, idle: usize) {
214    let size = pool.size() as usize;
215    let idle = idle.min(size);
216    let max = pool.options().get_max_connections() as usize;
217    crate::pool::record_counts(name, idle, size - idle, max);
218}
219
220impl<DB: Database> Clone for Pool<DB> {
221    fn clone(&self) -> Self {
222        Pool {
223            inner: self.inner.clone(),
224            target: Arc::clone(&self.target),
225        }
226    }
227}
228
229impl<DB: Database> Deref for Pool<DB> {
230    type Target = sqlx::Pool<DB>;
231
232    fn deref(&self) -> &sqlx::Pool<DB> {
233        &self.inner
234    }
235}
236
237impl<DB: Database> fmt::Debug for Pool<DB> {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        f.debug_struct("Pool")
240            .field("target", &self.target)
241            .finish_non_exhaustive()
242    }
243}
244
245impl<'p, DB> Executor<'p> for &'p Pool<DB>
246where
247    DB: Database,
248    for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>,
249{
250    type Database = DB;
251
252    fn fetch_many<'e, 'q: 'e, E>(self, query: E) -> BoxStream<'e, Result<Step<DB>, Error>>
253    where
254        'p: 'e,
255        E: 'q + Execute<'q, DB>,
256    {
257        let (statement, query) = watch(query);
258        Box::pin(async_stream::try_stream! {
259            let mut leased = self.lease().await?;
260            let call = QueryCall::start(&self.target, statement);
261            let mut steps = Recorded::new(
262                (&mut *leased.conn).fetch_many(query),
263                call,
264                is_row::<DB>,
265                fail,
266            );
267            while let Some(step) = steps.try_next().await? {
268                yield step;
269            }
270        })
271    }
272
273    fn fetch_optional<'e, 'q: 'e, E>(
274        self,
275        query: E,
276    ) -> BoxFuture<'e, Result<Option<DB::Row>, Error>>
277    where
278        'p: 'e,
279        E: 'q + Execute<'q, DB>,
280    {
281        let (statement, query) = watch(query);
282        Box::pin(async move {
283            let mut leased = self.lease().await?;
284            let call = QueryCall::start(&self.target, statement);
285            record_one(
286                call,
287                (&mut *leased.conn).fetch_optional(query),
288                one_row,
289                fail,
290            )
291            .await
292        })
293    }
294
295    fn prepare_with<'e>(
296        self,
297        sql: SqlStr,
298        parameters: &'e [DB::TypeInfo],
299    ) -> BoxFuture<'e, Result<DB::Statement, Error>>
300    where
301        'p: 'e,
302    {
303        (&self.inner).prepare_with(sql, parameters)
304    }
305
306    fn describe<'e>(self, sql: SqlStr) -> BoxFuture<'e, Result<Describe<DB>, Error>>
307    where
308        'p: 'e,
309    {
310        (&self.inner).describe(sql)
311    }
312}
313
314/// An instrumented connection out of a [`Pool`]. Run queries on
315/// `&mut connection`. It dereferences to sqlx's
316/// [`PoolConnection`].
317pub struct Connection<DB: Database> {
318    leased: Leased<DB>,
319    target: Arc<Target>,
320}
321
322impl<DB: Database> Connection<DB> {
323    /// Start a transaction on this connection. Its `BEGIN` is recorded as a
324    /// call.
325    pub async fn begin(&mut self) -> Result<Transaction<'_, DB>, Error> {
326        let call = QueryCall::start(&self.target, statement(Some(analyze("BEGIN"))));
327        let inner = record_one(call, (*self.leased.conn).begin(), no_rows, fail).await?;
328        Ok(Transaction {
329            inner,
330            target: Arc::clone(&self.target),
331            _lease: None,
332        })
333    }
334}
335
336impl<DB: Database> Deref for Connection<DB> {
337    type Target = PoolConnection<DB>;
338
339    fn deref(&self) -> &PoolConnection<DB> {
340        &self.leased.conn
341    }
342}
343
344impl<DB: Database> DerefMut for Connection<DB> {
345    fn deref_mut(&mut self) -> &mut PoolConnection<DB> {
346        &mut self.leased.conn
347    }
348}
349
350impl<DB: Database> fmt::Debug for Connection<DB> {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        f.debug_struct("Connection")
353            .field("target", &self.target)
354            .finish_non_exhaustive()
355    }
356}
357
358impl<'c, DB> Executor<'c> for &'c mut Connection<DB>
359where
360    DB: Database,
361    for<'x> &'x mut DB::Connection: Executor<'x, Database = DB>,
362{
363    type Database = DB;
364
365    fn fetch_many<'e, 'q: 'e, E>(self, query: E) -> BoxStream<'e, Result<Step<DB>, Error>>
366    where
367        'c: 'e,
368        E: 'q + Execute<'q, DB>,
369    {
370        let (statement, query) = watch(query);
371        let call = QueryCall::start(&self.target, statement);
372        Box::pin(Recorded::new(
373            (&mut *self.leased.conn).fetch_many(query),
374            call,
375            is_row::<DB>,
376            fail,
377        ))
378    }
379
380    fn fetch_optional<'e, 'q: 'e, E>(
381        self,
382        query: E,
383    ) -> BoxFuture<'e, Result<Option<DB::Row>, Error>>
384    where
385        'c: 'e,
386        E: 'q + Execute<'q, DB>,
387    {
388        let (statement, query) = watch(query);
389        let call = QueryCall::start(&self.target, statement);
390        Box::pin(record_one(
391            call,
392            (&mut *self.leased.conn).fetch_optional(query),
393            one_row,
394            fail,
395        ))
396    }
397
398    fn prepare_with<'e>(
399        self,
400        sql: SqlStr,
401        parameters: &'e [DB::TypeInfo],
402    ) -> BoxFuture<'e, Result<DB::Statement, Error>>
403    where
404        'c: 'e,
405    {
406        (&mut *self.leased.conn).prepare_with(sql, parameters)
407    }
408
409    fn describe<'e>(self, sql: SqlStr) -> BoxFuture<'e, Result<Describe<DB>, Error>>
410    where
411        'c: 'e,
412    {
413        (&mut *self.leased.conn).describe(sql)
414    }
415}
416
417/// An instrumented transaction, from [`Pool::begin`] or
418/// [`Connection::begin`]. Run queries on `&mut transaction`. Like sqlx's,
419/// dropping it without committing rolls it back, but that rollback isn't
420/// recorded. It dereferences to sqlx's [`Transaction`](sqlx::Transaction).
421pub struct Transaction<'c, DB: Database> {
422    inner: sqlx::Transaction<'c, DB>,
423    target: Arc<Target>,
424    // After `inner`, so the connection is back in the pool when it ends.
425    _lease: Option<Lease>,
426}
427
428impl<DB: Database> Transaction<'_, DB> {
429    /// Commit, recorded as a call.
430    pub async fn commit(self) -> Result<(), Error> {
431        let call = QueryCall::start(&self.target, statement(Some(analyze("COMMIT"))));
432        record_one(call, self.inner.commit(), no_rows, fail).await
433    }
434
435    /// Roll back, recorded as a call.
436    pub async fn rollback(self) -> Result<(), Error> {
437        let call = QueryCall::start(&self.target, statement(Some(analyze("ROLLBACK"))));
438        record_one(call, self.inner.rollback(), no_rows, fail).await
439    }
440}
441
442impl<'c, DB: Database> Deref for Transaction<'c, DB> {
443    type Target = sqlx::Transaction<'c, DB>;
444
445    fn deref(&self) -> &sqlx::Transaction<'c, DB> {
446        &self.inner
447    }
448}
449
450impl<'c, DB: Database> DerefMut for Transaction<'c, DB> {
451    fn deref_mut(&mut self) -> &mut sqlx::Transaction<'c, DB> {
452        &mut self.inner
453    }
454}
455
456impl<DB: Database> fmt::Debug for Transaction<'_, DB> {
457    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458        f.debug_struct("Transaction")
459            .field("target", &self.target)
460            .finish_non_exhaustive()
461    }
462}
463
464impl<'t, DB> Executor<'t> for &'t mut Transaction<'_, DB>
465where
466    DB: Database,
467    for<'x> &'x mut DB::Connection: Executor<'x, Database = DB>,
468{
469    type Database = DB;
470
471    fn fetch_many<'e, 'q: 'e, E>(self, query: E) -> BoxStream<'e, Result<Step<DB>, Error>>
472    where
473        't: 'e,
474        E: 'q + Execute<'q, DB>,
475    {
476        let (statement, query) = watch(query);
477        let call = QueryCall::start(&self.target, statement);
478        Box::pin(Recorded::new(
479            (&mut *self.inner).fetch_many(query),
480            call,
481            is_row::<DB>,
482            fail,
483        ))
484    }
485
486    fn fetch_optional<'e, 'q: 'e, E>(
487        self,
488        query: E,
489    ) -> BoxFuture<'e, Result<Option<DB::Row>, Error>>
490    where
491        't: 'e,
492        E: 'q + Execute<'q, DB>,
493    {
494        let (statement, query) = watch(query);
495        let call = QueryCall::start(&self.target, statement);
496        Box::pin(record_one(
497            call,
498            (&mut *self.inner).fetch_optional(query),
499            one_row,
500            fail,
501        ))
502    }
503
504    fn prepare_with<'e>(
505        self,
506        sql: SqlStr,
507        parameters: &'e [DB::TypeInfo],
508    ) -> BoxFuture<'e, Result<DB::Statement, Error>>
509    where
510        't: 'e,
511    {
512        (&mut *self.inner).prepare_with(sql, parameters)
513    }
514
515    fn describe<'e>(self, sql: SqlStr) -> BoxFuture<'e, Result<Describe<DB>, Error>>
516    where
517        't: 'e,
518    {
519        (&mut *self.inner).describe(sql)
520    }
521}