Skip to main content

oxtel_sql/sqlx/
v0_8.rs

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